From 93b131415fd647fe2733d0abc00f9a119e9cff60 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Mar 2026 21:39:31 +0000 Subject: [PATCH 1/6] Fix Convex payload decoding Co-authored-by: Dara Adedeji --- lib/collab/convex_payload.dart | 35 +++++ lib/collab/convex_strategy_repository.dart | 131 ++++++++++-------- .../remote_strategy_snapshot_provider.dart | 7 +- 3 files changed, 113 insertions(+), 60 deletions(-) create mode 100644 lib/collab/convex_payload.dart diff --git a/lib/collab/convex_payload.dart b/lib/collab/convex_payload.dart new file mode 100644 index 00000000..9580de51 --- /dev/null +++ b/lib/collab/convex_payload.dart @@ -0,0 +1,35 @@ +import 'dart:convert'; + +dynamic decodeConvexPayload(dynamic value) { + if (value is String) { + return jsonDecode(value); + } + + return value; +} + +Map decodeConvexMap(dynamic value) { + final decoded = decodeConvexPayload(value); + if (decoded is Map) { + return decoded; + } + if (decoded is Map) { + return Map.from(decoded); + } + throw const FormatException( + 'Expected Convex payload to decode to a JSON object.', + ); +} + +List decodeConvexList(dynamic value) { + final decoded = decodeConvexPayload(value); + if (decoded == null) { + return const []; + } + if (decoded is List) { + return List.from(decoded); + } + throw const FormatException( + 'Expected Convex payload to decode to a JSON array.', + ); +} diff --git a/lib/collab/convex_strategy_repository.dart b/lib/collab/convex_strategy_repository.dart index 4d8d5e39..f0291928 100644 --- a/lib/collab/convex_strategy_repository.dart +++ b/lib/collab/convex_strategy_repository.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:convex_flutter/convex_flutter.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/convex_payload.dart'; final convexStrategyRepositoryProvider = Provider( (ref) => ConvexStrategyRepository(ConvexClient.instance), @@ -20,25 +21,30 @@ class ConvexStrategyRepository { dynamic subscription; Future start() async { - subscription = await _client.subscribe( - name: 'folders:listForParent', - args: { - if (parentFolderPublicId != null) - 'parentFolderPublicId': parentFolderPublicId, - }, - onUpdate: (value) { - final raw = (value as List?) ?? const []; - final mapped = raw - .whereType() - .map((item) => - CloudFolderSummary.fromJson(Map.from(item))) - .toList(growable: false); - controller.add(mapped); - }, - onError: (message, value) { - controller.addError(Exception('folders:listForParent error: $message')); - }, - ); + try { + subscription = await _client.subscribe( + name: 'folders:listForParent', + args: { + if (parentFolderPublicId != null) + 'parentFolderPublicId': parentFolderPublicId, + }, + onUpdate: (value) { + final raw = decodeConvexList(value); + final mapped = raw + .whereType() + .map((item) => CloudFolderSummary.fromJson( + Map.from(item))) + .toList(growable: false); + controller.add(mapped); + }, + onError: (message, value) { + controller + .addError(Exception('folders:listForParent error: $message')); + }, + ); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } } start(); @@ -58,25 +64,29 @@ class ConvexStrategyRepository { dynamic subscription; Future start() async { - subscription = await _client.subscribe( - name: 'strategies:listForFolder', - args: { - if (folderPublicId != null) 'folderPublicId': folderPublicId, - }, - onUpdate: (value) { - final raw = (value as List?) ?? const []; - final mapped = raw - .whereType() - .map((item) => CloudStrategySummary.fromJson( - Map.from(item))) - .toList(growable: false); - controller.add(mapped); - }, - onError: (message, value) { - controller - .addError(Exception('strategies:listForFolder error: $message')); - }, - ); + try { + subscription = await _client.subscribe( + name: 'strategies:listForFolder', + args: { + if (folderPublicId != null) 'folderPublicId': folderPublicId, + }, + onUpdate: (value) { + final raw = decodeConvexList(value); + final mapped = raw + .whereType() + .map((item) => CloudStrategySummary.fromJson( + Map.from(item))) + .toList(growable: false); + controller.add(mapped); + }, + onError: (message, value) { + controller.addError( + Exception('strategies:listForFolder error: $message')); + }, + ); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } } start(); @@ -95,19 +105,23 @@ class ConvexStrategyRepository { dynamic subscription; Future start() async { - subscription = await _client.subscribe( - name: 'strategies:getHeader', - args: {'strategyPublicId': strategyPublicId}, - onUpdate: (value) { - controller.add( - RemoteStrategyHeader.fromJson( - Map.from(value as Map)), - ); - }, - onError: (message, value) { - controller.addError(Exception('strategies:getHeader error: $message')); - }, - ); + try { + subscription = await _client.subscribe( + name: 'strategies:getHeader', + args: {'strategyPublicId': strategyPublicId}, + onUpdate: (value) { + controller.add( + RemoteStrategyHeader.fromJson(decodeConvexMap(value)), + ); + }, + onError: (message, value) { + controller + .addError(Exception('strategies:getHeader error: $message')); + }, + ); + } catch (error, stackTrace) { + controller.addError(error, stackTrace); + } } start(); @@ -124,14 +138,13 @@ class ConvexStrategyRepository { final headerRaw = await _client.query('strategies:getHeader', { 'strategyPublicId': strategyPublicId, }); - final header = - RemoteStrategyHeader.fromJson(Map.from(headerRaw as Map)); + final header = RemoteStrategyHeader.fromJson(decodeConvexMap(headerRaw)); final pagesRaw = await _client.query('pages:listForStrategy', { 'strategyPublicId': strategyPublicId, }); - final pages = ((pagesRaw as List?) ?? const []) + final pages = decodeConvexList(pagesRaw) .whereType() .map((item) => RemotePage.fromJson(Map.from(item))) .toList(growable: false) @@ -145,9 +158,10 @@ class ConvexStrategyRepository { 'strategyPublicId': strategyPublicId, 'pagePublicId': page.publicId, }); - final elements = ((elementsRaw as List?) ?? const []) + final elements = decodeConvexList(elementsRaw) .whereType() - .map((item) => RemoteElement.fromJson(Map.from(item))) + .map( + (item) => RemoteElement.fromJson(Map.from(item))) .toList(growable: false) ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); elementsByPage[page.publicId] = elements; @@ -156,7 +170,7 @@ class ConvexStrategyRepository { 'strategyPublicId': strategyPublicId, 'pagePublicId': page.publicId, }); - final lineups = ((lineupsRaw as List?) ?? const []) + final lineups = decodeConvexList(lineupsRaw) .whereType() .map((item) => RemoteLineup.fromJson(Map.from(item))) .toList(growable: false) @@ -190,7 +204,8 @@ class ConvexStrategyRepository { }, ); - final resultList = ((response as Map)['results'] as List?) ?? const []; + final decodedResponse = decodeConvexMap(response); + final resultList = (decodedResponse['results'] as List?) ?? const []; return resultList .whereType() .map((item) => OpAck.fromJson(Map.from(item))) diff --git a/lib/providers/collab/remote_strategy_snapshot_provider.dart b/lib/providers/collab/remote_strategy_snapshot_provider.dart index 8681bebd..45214f04 100644 --- a/lib/providers/collab/remote_strategy_snapshot_provider.dart +++ b/lib/providers/collab/remote_strategy_snapshot_provider.dart @@ -4,6 +4,7 @@ import 'dart:developer'; import 'package:convex_flutter/convex_flutter.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/collab/convex_payload.dart'; import 'package:icarus/collab/convex_strategy_repository.dart'; import 'package:icarus/providers/auth_provider.dart'; import 'package:icarus/providers/collab/strategy_op_queue_provider.dart'; @@ -32,7 +33,9 @@ class RemoteStrategySnapshotNotifier Future openStrategy(String strategyPublicId) async { _activeStrategyPublicId = strategyPublicId; - ref.read(strategyOpQueueProvider.notifier).setActiveStrategy(strategyPublicId); + ref + .read(strategyOpQueueProvider.notifier) + .setActiveStrategy(strategyPublicId); state = const AsyncLoading(); await _refreshFromServer(); @@ -107,7 +110,7 @@ class RemoteStrategySnapshotNotifier name: 'pages:listForStrategy', args: {'strategyPublicId': strategyPublicId}, onUpdate: (value) { - final pageIds = ((value as List?) ?? const []) + final pageIds = decodeConvexList(value) .whereType() .map((item) => Map.from(item)) .map((item) => item['publicId'] as String?) From 2a15e42bc5e94121ccfd032740a3224999c5efbf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Mar 2026 22:28:12 +0000 Subject: [PATCH 2/6] Keep Convex auth aligned with Supabase Co-authored-by: Dara Adedeji --- lib/providers/auth_provider.dart | 183 ++++++++++++++++++++++++++++--- 1 file changed, 167 insertions(+), 16 deletions(-) diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart index 6b8a08f3..09de8e57 100644 --- a/lib/providers/auth_provider.dart +++ b/lib/providers/auth_provider.dart @@ -5,6 +5,7 @@ import 'package:convex_flutter/convex_flutter.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/app_navigator.dart'; +import 'package:icarus/collab/convex_payload.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; final authProvider = @@ -168,19 +169,44 @@ class AuthProvider extends Notifier { AuthHandleWrapper? _convexAuthHandle; Future? _inFlightConvexSetup; bool _queuedConvexSetup = false; + String? _queuedConvexTrigger; bool _showingIncidentPrompt = false; int _incidentCounter = 0; + int _authGeneration = 0; SupabaseClient get _supabase => Supabase.instance.client; ConvexClient get _convex => ConvexClient.instance; + int _advanceAuthGeneration() { + _authGeneration += 1; + return _authGeneration; + } + + String _sessionFingerprint(Session? session) { + if (session == null) { + return 'signed_out'; + } + return '${session.user.id}:${session.accessToken}'; + } + + bool _isAuthContextCurrent({ + required int generation, + required String sessionFingerprint, + }) { + return generation == _authGeneration && + _sessionFingerprint(_supabase.auth.currentSession) == + sessionFingerprint; + } + @override AppAuthState build() { final session = _supabase.auth.currentSession; + final initialGeneration = _advanceAuthGeneration(); _supabaseAuthSub ??= _supabase.auth.onAuthStateChange.listen( (event) { final currentSession = event.session; + final generation = _advanceAuthGeneration(); state = AppAuthState.fromSession( currentSession, isLoading: false, @@ -194,7 +220,13 @@ class AuthProvider extends Notifier { _clearAuthIncident(); } - unawaited(_configureConvexAuth(trigger: 'supabase:${event.event}')); + unawaited( + _configureConvexAuth( + trigger: 'supabase:${event.event}', + generation: generation, + sessionFingerprint: _sessionFingerprint(currentSession), + ), + ); }, onError: (Object error, StackTrace stackTrace) { log( @@ -217,20 +249,27 @@ class AuthProvider extends Notifier { _convexAuthHandle?.dispose(); }); - unawaited(_configureConvexAuth(trigger: 'build')); + Future.microtask(() async { + await _configureConvexAuth( + trigger: 'build', + generation: initialGeneration, + sessionFingerprint: _sessionFingerprint(session), + ); + }); return AppAuthState.fromSession( session, isConvexUserReady: false, - convexAuthStatus: - session == null ? ConvexAuthStatus.signedOut : ConvexAuthStatus.configuring, + convexAuthStatus: session == null + ? ConvexAuthStatus.signedOut + : ConvexAuthStatus.configuring, ); } bool isAuthCallbackUri(Uri uri) { final isIcarusScheme = uri.scheme.toLowerCase() == 'icarus'; - final isAuthCallback = - uri.host.toLowerCase() == 'auth' && uri.path.toLowerCase() == '/callback'; + final isAuthCallback = uri.host.toLowerCase() == 'auth' && + uri.path.toLowerCase() == '/callback'; if (!isIcarusScheme || !isAuthCallback) { return false; } @@ -308,7 +347,6 @@ class AuthProvider extends Notifier { return message; } - await _configureConvexAuth(trigger: 'email_password_sign_in'); state = state.copyWith(isLoading: false); return null; } catch (error, stackTrace) { @@ -358,7 +396,6 @@ class AuthProvider extends Notifier { return message; } - await _configureConvexAuth(trigger: 'email_password_sign_up'); state = state.copyWith(isLoading: false); return null; } catch (error, stackTrace) { @@ -380,6 +417,7 @@ class AuthProvider extends Notifier { } Future signOut() async { + final generation = _advanceAuthGeneration(); state = state.copyWith( isLoading: true, isConvexUserReady: false, @@ -391,10 +429,10 @@ class AuthProvider extends Notifier { ); try { - await _supabase.auth.signOut(); _convexAuthHandle?.dispose(); _convexAuthHandle = null; await _convex.clearAuth(); + await _supabase.auth.signOut(); state = AppAuthState.fromSession( null, isLoading: false, @@ -408,12 +446,32 @@ class AuthProvider extends Notifier { error: error, stackTrace: stackTrace, ); - state = state.copyWith( + final currentSession = _supabase.auth.currentSession; + if (currentSession == null) { + state = AppAuthState.fromSession( + null, + isLoading: false, + isConvexUserReady: false, + convexAuthStatus: ConvexAuthStatus.signedOut, + errorMessage: 'Sign out failed: $error', + ); + return; + } + + state = AppAuthState.fromSession( + currentSession, isLoading: false, isConvexUserReady: false, - convexAuthStatus: ConvexAuthStatus.incident, + convexAuthStatus: ConvexAuthStatus.configuring, errorMessage: 'Sign out failed: $error', ); + unawaited( + _configureConvexAuth( + trigger: 'sign_out_failed', + generation: generation, + sessionFingerprint: _sessionFingerprint(currentSession), + ), + ); } } @@ -431,7 +489,6 @@ class AuthProvider extends Notifier { try { await _supabase.auth.getSessionFromUrl(uri); - await _configureConvexAuth(trigger: 'callback:$source'); state = state.copyWith(isLoading: false); log('Handled auth callback [$source]: $uri', name: 'auth'); return true; @@ -537,9 +594,18 @@ class AuthProvider extends Notifier { unawaited(_showAuthIncidentPrompt(incidentId)); } - Future _configureConvexAuth({required String trigger}) async { + Future _configureConvexAuth({ + required String trigger, + int? generation, + String? sessionFingerprint, + }) async { + final targetGeneration = generation ?? _authGeneration; + final targetFingerprint = sessionFingerprint ?? + _sessionFingerprint(_supabase.auth.currentSession); + if (_inFlightConvexSetup != null) { _queuedConvexSetup = true; + _queuedConvexTrigger = trigger; await _inFlightConvexSetup; return; } @@ -548,24 +614,47 @@ class AuthProvider extends Notifier { _inFlightConvexSetup = completer.future; try { - await _runConvexAuthSetup(trigger: trigger); + await _runConvexAuthSetup( + trigger: trigger, + generation: targetGeneration, + sessionFingerprint: targetFingerprint, + ); } finally { completer.complete(); _inFlightConvexSetup = null; if (_queuedConvexSetup) { _queuedConvexSetup = false; - unawaited(_configureConvexAuth(trigger: 'queued')); + final queuedTrigger = _queuedConvexTrigger ?? 'queued'; + _queuedConvexTrigger = null; + unawaited(_configureConvexAuth(trigger: queuedTrigger)); } } } - Future _runConvexAuthSetup({required String trigger}) async { + Future _runConvexAuthSetup({ + required String trigger, + required int generation, + required String sessionFingerprint, + }) async { final session = _supabase.auth.currentSession; + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + return; + } + if (session == null) { _convexAuthHandle?.dispose(); _convexAuthHandle = null; await _convex.clearAuth(); + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + return; + } _clearAuthIncident(); state = AppAuthState.fromSession( null, @@ -589,6 +678,12 @@ class AuthProvider extends Notifier { _convexAuthHandle = await _convex.setAuthWithRefresh( fetchToken: _fetchSupabaseAccessToken, onAuthChange: (isAuthenticated) { + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + return; + } if (isAuthenticated) { return; } @@ -608,8 +703,44 @@ class AuthProvider extends Notifier { }, ); + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + _convexAuthHandle?.dispose(); + _convexAuthHandle = null; + return; + } + await _convex.reconnect(); await _convex.mutation(name: 'users:ensureCurrentUser', args: {}); + final currentUserRaw = await _convex.query('users:me', {}); + final currentUserDecoded = decodeConvexPayload(currentUserRaw); + final currentUser = currentUserDecoded is Map + ? Map.from(currentUserDecoded) + : null; + + if (currentUser == null) { + throw StateError( + 'Convex user verification failed because no current user was returned.', + ); + } + + final externalId = currentUser['externalId']?.toString(); + if (externalId != session.user.id) { + throw StateError( + 'Convex authenticated as $externalId while Supabase session is ${session.user.id}.', + ); + } + + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + _convexAuthHandle?.dispose(); + _convexAuthHandle = null; + return; + } _clearAuthIncident(); state = state.copyWith( @@ -618,6 +749,19 @@ class AuthProvider extends Notifier { clearError: true, ); } catch (error, stackTrace) { + if (_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + _convexAuthHandle?.dispose(); + _convexAuthHandle = null; + try { + await _convex.clearAuth(); + } catch (_) { + // Best-effort cleanup before surfacing auth issues. + } + } + log( 'Failed configuring Convex auth [$trigger]: $error', name: 'auth', @@ -634,6 +778,13 @@ class AuthProvider extends Notifier { return; } + if (!_isAuthContextCurrent( + generation: generation, + sessionFingerprint: sessionFingerprint, + )) { + return; + } + state = state.copyWith( isConvexUserReady: false, convexAuthStatus: ConvexAuthStatus.incident, From 39d95ff2c1a258e236b264a6874c47e37266132d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Mar 2026 23:30:41 +0000 Subject: [PATCH 3/6] Restore cloud library UI parity Co-authored-by: Dara Adedeji --- lib/widgets/cloud_library_widgets.dart | 380 +++++++++++++++++++++++++ lib/widgets/folder_navigator.dart | 123 ++++---- 2 files changed, 436 insertions(+), 67 deletions(-) create mode 100644 lib/widgets/cloud_library_widgets.dart diff --git a/lib/widgets/cloud_library_widgets.dart b/lib/widgets/cloud_library_widgets.dart new file mode 100644 index 00000000..2d5e8c9a --- /dev/null +++ b/lib/widgets/cloud_library_widgets.dart @@ -0,0 +1,380 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:icarus/collab/collab_models.dart'; +import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/strategy_view.dart'; +import 'package:icarus/widgets/strategy_tile/strategy_tile_sections.dart'; +import 'package:shadcn_ui/shadcn_ui.dart'; + +class CloudFolderPill extends ConsumerStatefulWidget { + const CloudFolderPill({ + super.key, + required this.folder, + }); + + final CloudFolderSummary folder; + + @override + ConsumerState createState() => _CloudFolderPillState(); +} + +class _CloudFolderPillState extends ConsumerState + with SingleTickerProviderStateMixin { + late final AnimationController _animationController; + late final Animation _scaleAnimation; + bool _isHovered = false; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: const Duration(milliseconds: 150), + vsync: this, + ); + _scaleAnimation = Tween( + begin: 1.0, + end: 1.03, + ).animate(CurvedAnimation( + parent: _animationController, + curve: Curves.easeOut, + )); + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final pillColor = Color.lerp( + Settings.tacticalVioletTheme.card, + Settings.tacticalVioletTheme.primary, + 0.55, + )!; + + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) { + setState(() => _isHovered = true); + _animationController.forward(); + }, + onExit: (_) { + setState(() => _isHovered = false); + _animationController.reverse(); + }, + child: GestureDetector( + onTap: () => + ref.read(folderProvider.notifier).updateID(widget.folder.publicId), + child: AnimatedBuilder( + animation: _scaleAnimation, + builder: (context, child) { + return Transform.scale( + scale: _scaleAnimation.value, + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: pillColor, + borderRadius: BorderRadius.circular(22), + border: Border.all( + color: _isHovered + ? Colors.white.withValues(alpha: 0.55) + : Colors.white.withValues(alpha: 0.18), + ), + boxShadow: [ + BoxShadow( + color: pillColor.withValues(alpha: 0.35), + blurRadius: _isHovered ? 10 : 6, + offset: const Offset(0, 3), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon( + Icons.folder_rounded, + color: Colors.white, + size: 20, + ), + const SizedBox(width: 10), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 160), + child: Text( + widget.folder.name, + style: const TextStyle( + color: Colors.white, + fontSize: 14, + fontWeight: FontWeight.w600, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ); + }, + ), + ), + ); + } +} + +class CloudStrategyTile extends ConsumerStatefulWidget { + const CloudStrategyTile({ + super.key, + required this.strategy, + }); + + final CloudStrategySummary strategy; + + @override + ConsumerState createState() => _CloudStrategyTileState(); +} + +class _CloudStrategyTileState extends ConsumerState { + Color _highlightColor = Settings.tacticalVioletTheme.border; + bool _isLoading = false; + + @override + Widget build(BuildContext context) { + final data = _CloudStrategyTileViewData.fromSummary(widget.strategy); + + return MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) => + setState(() => _highlightColor = Settings.tacticalVioletTheme.ring), + onExit: (_) => + setState(() => _highlightColor = Settings.tacticalVioletTheme.border), + child: AbsorbPointer( + absorbing: _isLoading, + child: GestureDetector( + onTap: () => _openStrategy(context), + child: Stack( + children: [ + AnimatedContainer( + duration: const Duration(milliseconds: 100), + decoration: BoxDecoration( + color: ShadTheme.of(context).colorScheme.card, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _highlightColor, width: 2), + ), + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Expanded( + child: + StrategyTileThumbnail(assetPath: data.thumbnailAsset), + ), + const SizedBox(height: 10), + Expanded(child: _CloudStrategyTileDetails(data: data)), + ], + ), + ), + const Align( + alignment: Alignment.topRight, + child: Padding( + padding: EdgeInsets.all(16), + child: Icon( + Icons.cloud_done_outlined, + color: Colors.white70, + size: 22, + ), + ), + ), + ], + ), + ), + ), + ); + } + + Future _openStrategy(BuildContext context) async { + if (_isLoading) { + return; + } + + setState(() => _isLoading = true); + _showLoadingOverlay(); + var dismissedOverlay = false; + + try { + await ref + .read(strategyProvider.notifier) + .openStrategy(widget.strategy.publicId); + if (!context.mounted) { + return; + } + Navigator.pop(context); + dismissedOverlay = true; + await Navigator.push( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 200), + reverseTransitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animation, _) => const StrategyView(), + transitionsBuilder: (context, animation, _, child) { + return FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.9, end: 1.0) + .chain(CurveTween(curve: Curves.easeOut)) + .animate(animation), + child: child, + ), + ); + }, + ), + ); + } finally { + if (!dismissedOverlay && context.mounted) { + Navigator.pop(context); + } + if (mounted) { + setState(() => _isLoading = false); + } + } + } + + void _showLoadingOverlay() { + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const Center(child: CircularProgressIndicator()), + ); + } +} + +class _CloudStrategyTileViewData { + const _CloudStrategyTileViewData({ + required this.name, + required this.mapName, + required this.thumbnailAsset, + required this.updatedLabel, + }); + + factory _CloudStrategyTileViewData.fromSummary(CloudStrategySummary summary) { + final mapName = summary.mapData.trim(); + final normalizedMap = mapName.isEmpty + ? 'unknown' + : mapName.toLowerCase().replaceAll(' ', '_'); + return _CloudStrategyTileViewData( + name: summary.name, + mapName: mapName.isEmpty + ? 'Unknown' + : mapName[0].toUpperCase() + mapName.substring(1), + thumbnailAsset: 'assets/maps/thumbnails/${normalizedMap}_thumbnail.webp', + updatedLabel: _timeAgo(summary.updatedAt), + ); + } + + final String name; + final String mapName; + final String thumbnailAsset; + final String updatedLabel; + + static String _timeAgo(DateTime date) { + final difference = DateTime.now().difference(date); + if (difference.inMinutes < 1) return 'Just now'; + if (difference.inMinutes < 60) { + final minutes = difference.inMinutes; + return '$minutes min${minutes == 1 ? '' : 's'} ago'; + } + if (difference.inHours < 24) { + final hours = difference.inHours; + return '$hours hour${hours == 1 ? '' : 's'} ago'; + } + if (difference.inDays < 30) { + final days = difference.inDays; + return '$days day${days == 1 ? '' : 's'} ago'; + } + final months = (difference.inDays / 30).floor(); + return '$months month${months == 1 ? '' : 's'} ago'; + } +} + +class _CloudStrategyTileDetails extends StatelessWidget { + const _CloudStrategyTileDetails({ + required this.data, + }); + + final _CloudStrategyTileViewData data; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: ShadTheme.of(context).colorScheme.card, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Settings.tacticalVioletTheme.border), + boxShadow: const [Settings.cardForegroundBackdrop], + ), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 130), + child: Text( + data.name, + style: const TextStyle( + fontWeight: FontWeight.w500, + overflow: TextOverflow.ellipsis, + ), + ), + ), + const SizedBox(height: 5), + Text(data.mapName), + const SizedBox(height: 8), + Container( + padding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.primary + .withValues(alpha: 0.22), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Settings.tacticalVioletTheme.primary + .withValues(alpha: 0.5), + ), + ), + child: const Text( + 'Online', + style: TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Synced', + style: TextStyle(color: Colors.deepPurpleAccent), + ), + const SizedBox(height: 5), + Text(data.updatedLabel, overflow: TextOverflow.ellipsis), + ], + ), + ], + ), + ); + } +} diff --git a/lib/widgets/folder_navigator.dart b/lib/widgets/folder_navigator.dart index 9a3cd76a..307ba99f 100644 --- a/lib/widgets/folder_navigator.dart +++ b/lib/widgets/folder_navigator.dart @@ -30,6 +30,7 @@ import 'package:icarus/providers/collab/cloud_collab_provider.dart'; import 'package:icarus/providers/collab/remote_library_provider.dart'; import 'package:icarus/providers/strategy_filter_provider.dart'; import 'package:icarus/widgets/custom_search_field.dart'; +import 'package:icarus/widgets/cloud_library_widgets.dart'; import 'package:icarus/widgets/dot_painter.dart'; import 'package:icarus/widgets/folder_pill.dart'; import 'package:icarus/widgets/ica_drop_target.dart'; @@ -185,10 +186,10 @@ class _FolderNavigatorState extends ConsumerState { if (authState.isAuthenticated) { unawaited(ref.read(authProvider.notifier).signOut()); } else { - showDialog( - context: context, - builder: (_) => const AuthDialog(), - ); + showDialog( + context: context, + builder: (_) => const AuthDialog(), + ); } }, leading: Icon( @@ -303,8 +304,8 @@ class _CloudFolderContent extends ConsumerWidget { } Comparator comparator = switch (filter.sortBy) { - SortBy.alphabetical => - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), + SortBy.alphabetical => (a, b) => + a.name.toLowerCase().compareTo(b.name.toLowerCase()), SortBy.dateCreated => (a, b) => a.createdAt.compareTo(b.createdAt), SortBy.dateUpdated => (a, b) => a.updatedAt.compareTo(b.updatedAt), }; @@ -326,55 +327,48 @@ class _CloudFolderContent extends ConsumerWidget { const _FolderToolbar(), Expanded( child: IcaDropTarget( - child: ListView( - padding: const EdgeInsets.all(16), - children: [ + child: CustomScrollView( + slivers: [ if (folders.isNotEmpty) - Wrap( - spacing: 10, - runSpacing: 10, - children: [ - for (final cloudFolder in folders) - ActionChip( - label: Text(cloudFolder.name), - onPressed: () { - ref - .read(folderProvider.notifier) - .updateID(cloudFolder.publicId); - }, - ), - ], - ), - if (folders.isNotEmpty) const SizedBox(height: 16), - if (strategies.isEmpty) - const Padding( - padding: EdgeInsets.only(top: 24), - child: Center( - child: Text('No cloud strategies in this folder'), + SliverToBoxAdapter( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Wrap( + spacing: 10, + runSpacing: 10, + children: [ + for (final cloudFolder in folders) + CloudFolderPill(folder: cloudFolder), + ], + ), ), ), - for (final strategy in strategies) - Card( - color: Settings.tacticalVioletTheme.card, - margin: const EdgeInsets.only(bottom: 12), - child: ListTile( - title: Text(strategy.name), - subtitle: Text( - '${strategy.mapData} • Updated ${strategy.updatedAt.toLocal()}', + if (strategies.isNotEmpty) + SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverGrid( + gridDelegate: + const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 320, + mainAxisExtent: 250, + crossAxisSpacing: 20, + mainAxisSpacing: 20, ), - trailing: const Icon(Icons.chevron_right), - onTap: () async { - await ref - .read(strategyProvider.notifier) - .openStrategy(strategy.publicId); - if (!context.mounted) return; - await Navigator.push( - context, - MaterialPageRoute( - builder: (_) => const StrategyView(), - ), - ); - }, + delegate: SliverChildBuilderDelegate( + (context, index) { + return CloudStrategyTile( + strategy: strategies[index], + ); + }, + childCount: strategies.length, + ), + ), + ) + else + const SliverFillRemaining( + hasScrollBody: false, + child: Center( + child: Text('No cloud strategies in this folder'), ), ), ], @@ -434,19 +428,20 @@ class _LocalFolderContent extends ConsumerWidget { if (search.isNotEmpty) { strategies = strategies - .where((s) => - s.name.toLowerCase().contains(search)) + .where( + (s) => s.name.toLowerCase().contains(search)) .toList(growable: false); } Comparator comparator = switch (filter.sortBy) { - SortBy.alphabetical => (a, b) => - a.name.toLowerCase().compareTo(b.name.toLowerCase()), - SortBy.dateCreated => - (a, b) => a.createdAt.compareTo(b.createdAt), - SortBy.dateUpdated => - (a, b) => a.lastEdited.compareTo(b.lastEdited), + SortBy.alphabetical => (a, b) => a.name + .toLowerCase() + .compareTo(b.name.toLowerCase()), + SortBy.dateCreated => (a, b) => + a.createdAt.compareTo(b.createdAt), + SortBy.dateUpdated => (a, b) => + a.lastEdited.compareTo(b.lastEdited), }; final direction = filter.sortOrder == SortOrder.ascending ? 1 : -1; @@ -540,9 +535,8 @@ class _FolderToolbar extends ConsumerWidget { child: Text(StrategyFilterProvider.sortByLabels[value]!), ), ], - onChanged: (value) => ref - .read(strategyFilterProvider.notifier) - .setSortBy(value!), + onChanged: (value) => + ref.read(strategyFilterProvider.notifier).setSortBy(value!), ), const SizedBox(width: 8), ShadSelect( @@ -580,8 +574,3 @@ class _FolderToolbar extends ConsumerWidget { ); } } - - - - - From 6f14cad2a33a9cacf2f3711b0d90f80371504ec9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Mar 2026 00:26:36 +0000 Subject: [PATCH 4/6] Sync cloud edits immediately Co-authored-by: Dara Adedeji --- lib/providers/strategy_provider.dart | 271 +++++++++++++-------------- 1 file changed, 134 insertions(+), 137 deletions(-) diff --git a/lib/providers/strategy_provider.dart b/lib/providers/strategy_provider.dart index 023747dd..30571020 100644 --- a/lib/providers/strategy_provider.dart +++ b/lib/providers/strategy_provider.dart @@ -821,9 +821,12 @@ class StrategyProvider extends Notifier { _saveTimer?.cancel(); if (_isCloudMode()) { - _saveTimer = Timer(Settings.autoSaveOffset, () async { - await _queueCurrentPageOps(flushImmediately: false); - await ref.read(strategyOpQueueProvider.notifier).flushNow(); + final strategyId = state.id; + Future.microtask(() async { + if (_skipQueueingDuringHydration) { + return; + } + await _performSave(strategyId); }); return; } @@ -838,8 +841,7 @@ class StrategyProvider extends Notifier { Future forceSaveNow(String id) async { _saveTimer?.cancel(); if (_isCloudMode()) { - await _queueCurrentPageOps(flushImmediately: false); - await ref.read(strategyOpQueueProvider.notifier).flushNow(); + await _performSave(id); return; } await _performSave(id); @@ -854,23 +856,18 @@ class StrategyProvider extends Notifier { _saveInProgress = true; try { - ref.read(autoSaveProvider.notifier).ping(); // UI: Saving... - if (_isCloudMode()) { - await _queueCurrentPageOps(flushImmediately: false); - await ref.read(strategyOpQueueProvider.notifier).flushNow(); - } else { - await saveToHive(id); - } + do { + _pendingSave = false; + ref.read(autoSaveProvider.notifier).ping(); // UI: Saving... + if (_isCloudMode()) { + await _queueCurrentPageOps(flushImmediately: false); + await ref.read(strategyOpQueueProvider.notifier).flushNow(); + } else { + await saveToHive(id); + } + } while (_pendingSave); } finally { _saveInProgress = false; - if (_pendingSave) { - _pendingSave = false; - // Small debounce to coalesce rapid edits during the previous save - _saveTimer?.cancel(); - // _saveTimer = Timer(const Duration(milliseconds: 500), () { - // _performSave(id); - // }); - } } } @@ -1365,10 +1362,10 @@ class StrategyProvider extends Notifier { ordered.insert(targetIndex, moved); try { - await ConvexClient.instance.mutation(name: "pages:reorder", args: { - "strategyPublicId": state.id, - "orderedPagePublicIds": ordered.map((p) => p.publicId).toList(), - }); + await ConvexClient.instance.mutation(name: "pages:reorder", args: { + "strategyPublicId": state.id, + "orderedPagePublicIds": ordered.map((p) => p.publicId).toList(), + }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:pages_reorder', @@ -1549,14 +1546,14 @@ class StrategyProvider extends Notifier { final pageID = const Uuid().v4(); final nextIndex = pages.length; try { - await ConvexClient.instance.mutation(name: "pages:add", args: { - "strategyPublicId": state.id, - "pagePublicId": pageID, - "name": name ?? "Page ${pages.length + 1}", - "sortIndex": nextIndex, - "isAttack": pages.isNotEmpty ? pages.last.isAttack : true, - "settings": ref.read(strategySettingsProvider.notifier).toJson(), - }); + await ConvexClient.instance.mutation(name: "pages:add", args: { + "strategyPublicId": state.id, + "pagePublicId": pageID, + "name": name ?? "Page ${pages.length + 1}", + "sortIndex": nextIndex, + "isAttack": pages.isNotEmpty ? pages.last.isAttack : true, + "settings": ref.read(strategySettingsProvider.notifier).toJson(), + }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:pages_add', @@ -1930,21 +1927,21 @@ class StrategyProvider extends Notifier { final defaultThemeProfileId = ref.read(mapThemeProfilesProvider).defaultProfileIdForNewStrategies; try { - await ref.read(convexStrategyRepositoryProvider).createStrategy( - publicId: newID, - name: name, - mapData: Maps.mapNames[MapValue.ascent] ?? "ascent", - folderPublicId: ref.read(folderProvider), - themeProfileId: defaultThemeProfileId, - ); - await ConvexClient.instance.mutation(name: "pages:add", args: { - "strategyPublicId": newID, - "pagePublicId": pageID, - "name": "Page 1", - "sortIndex": 0, - "isAttack": true, - "settings": ref.read(strategySettingsProvider.notifier).toJson(), - }); + await ref.read(convexStrategyRepositoryProvider).createStrategy( + publicId: newID, + name: name, + mapData: Maps.mapNames[MapValue.ascent] ?? "ascent", + folderPublicId: ref.read(folderProvider), + themeProfileId: defaultThemeProfileId, + ); + await ConvexClient.instance.mutation(name: "pages:add", args: { + "strategyPublicId": newID, + "pagePublicId": pageID, + "name": "Page 1", + "sortIndex": 0, + "isAttack": true, + "settings": ref.read(strategySettingsProvider.notifier).toJson(), + }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:create_new', @@ -2192,10 +2189,10 @@ class StrategyProvider extends Notifier { Future renameStrategy(String strategyID, String newName) async { if (_isCloudMode()) { try { - await ConvexClient.instance.mutation(name: "strategies:update", args: { - "strategyPublicId": strategyID, - "name": newName, - }); + await ConvexClient.instance.mutation(name: "strategies:update", args: { + "strategyPublicId": strategyID, + "name": newName, + }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:rename', @@ -2223,95 +2220,95 @@ class StrategyProvider extends Notifier { Future duplicateStrategy(String strategyID) async { if (_isCloudMode()) { try { - final snapshot = await ref - .read(convexStrategyRepositoryProvider) - .fetchSnapshot(strategyID); - final newStrategyID = const Uuid().v4(); - await ref.read(convexStrategyRepositoryProvider).createStrategy( - publicId: newStrategyID, - name: "${snapshot.header.name} (Copy)", - mapData: snapshot.header.mapData, - folderPublicId: ref.read(folderProvider), - themeProfileId: snapshot.header.themeProfileId, - themeOverridePalette: snapshot.header.themeOverridePalette, - ); + final snapshot = await ref + .read(convexStrategyRepositoryProvider) + .fetchSnapshot(strategyID); + final newStrategyID = const Uuid().v4(); + await ref.read(convexStrategyRepositoryProvider).createStrategy( + publicId: newStrategyID, + name: "${snapshot.header.name} (Copy)", + mapData: snapshot.header.mapData, + folderPublicId: ref.read(folderProvider), + themeProfileId: snapshot.header.themeProfileId, + themeOverridePalette: snapshot.header.themeOverridePalette, + ); - final pages = [...snapshot.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final pages = [...snapshot.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + + final pageIdMap = {}; + for (final page in pages) { + final newPageId = const Uuid().v4(); + pageIdMap[page.publicId] = newPageId; + await ConvexClient.instance.mutation(name: "pages:add", args: { + "strategyPublicId": newStrategyID, + "pagePublicId": newPageId, + "name": page.name, + "sortIndex": page.sortIndex, + "isAttack": page.isAttack, + if (page.settings != null) "settings": page.settings, + }); + } - final pageIdMap = {}; - for (final page in pages) { - final newPageId = const Uuid().v4(); - pageIdMap[page.publicId] = newPageId; - await ConvexClient.instance.mutation(name: "pages:add", args: { - "strategyPublicId": newStrategyID, - "pagePublicId": newPageId, - "name": page.name, - "sortIndex": page.sortIndex, - "isAttack": page.isAttack, - if (page.settings != null) "settings": page.settings, - }); - } + final ops = []; + for (final page in pages) { + final newPageId = pageIdMap[page.publicId]; + if (newPageId == null) continue; + + final elements = snapshot.elementsByPage[page.publicId] ?? const []; + for (final element in elements) { + if (element.deleted) continue; + final payloadMap = element.decodedPayload(); + payloadMap.putIfAbsent("elementType", () => element.elementType); + final newElementId = const Uuid().v4(); + payloadMap["id"] = newElementId; + ops.add(StrategyOp( + opId: const Uuid().v4(), + kind: StrategyOpKind.add, + entityType: StrategyOpEntityType.element, + entityPublicId: newElementId, + pagePublicId: newPageId, + payload: jsonEncode(payloadMap), + sortIndex: element.sortIndex, + )); + } - final ops = []; - for (final page in pages) { - final newPageId = pageIdMap[page.publicId]; - if (newPageId == null) continue; - - final elements = snapshot.elementsByPage[page.publicId] ?? const []; - for (final element in elements) { - if (element.deleted) continue; - final payloadMap = element.decodedPayload(); - payloadMap.putIfAbsent("elementType", () => element.elementType); - final newElementId = const Uuid().v4(); - payloadMap["id"] = newElementId; - ops.add(StrategyOp( - opId: const Uuid().v4(), - kind: StrategyOpKind.add, - entityType: StrategyOpEntityType.element, - entityPublicId: newElementId, - pagePublicId: newPageId, - payload: jsonEncode(payloadMap), - sortIndex: element.sortIndex, - )); + final lineups = snapshot.lineupsByPage[page.publicId] ?? const []; + for (final lineup in lineups) { + if (lineup.deleted) continue; + final newLineupId = const Uuid().v4(); + String lineupPayload = lineup.payload; + try { + final decoded = jsonDecode(lineup.payload); + if (decoded is Map) { + final payload = Map.from(decoded) + ..["id"] = newLineupId; + lineupPayload = jsonEncode(payload); + } else if (decoded is Map) { + final payload = Map.from(decoded) + ..["id"] = newLineupId; + lineupPayload = jsonEncode(payload); + } + } catch (_) {} + ops.add(StrategyOp( + opId: const Uuid().v4(), + kind: StrategyOpKind.add, + entityType: StrategyOpEntityType.lineup, + entityPublicId: newLineupId, + pagePublicId: newPageId, + payload: lineupPayload, + sortIndex: lineup.sortIndex, + )); + } } - final lineups = snapshot.lineupsByPage[page.publicId] ?? const []; - for (final lineup in lineups) { - if (lineup.deleted) continue; - final newLineupId = const Uuid().v4(); - String lineupPayload = lineup.payload; - try { - final decoded = jsonDecode(lineup.payload); - if (decoded is Map) { - final payload = Map.from(decoded) - ..["id"] = newLineupId; - lineupPayload = jsonEncode(payload); - } else if (decoded is Map) { - final payload = Map.from(decoded) - ..["id"] = newLineupId; - lineupPayload = jsonEncode(payload); - } - } catch (_) {} - ops.add(StrategyOp( - opId: const Uuid().v4(), - kind: StrategyOpKind.add, - entityType: StrategyOpEntityType.lineup, - entityPublicId: newLineupId, - pagePublicId: newPageId, - payload: lineupPayload, - sortIndex: lineup.sortIndex, - )); + if (ops.isNotEmpty) { + await ref.read(convexStrategyRepositoryProvider).applyBatch( + strategyPublicId: newStrategyID, + clientId: const Uuid().v4(), + ops: ops, + ); } - } - - if (ops.isNotEmpty) { - await ref.read(convexStrategyRepositoryProvider).applyBatch( - strategyPublicId: newStrategyID, - clientId: const Uuid().v4(), - ops: ops, - ); - } } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:duplicate', @@ -2354,9 +2351,9 @@ class StrategyProvider extends Notifier { Future deleteStrategy(String strategyID) async { if (_isCloudMode()) { try { - await ConvexClient.instance.mutation(name: "strategies:delete", args: { - "strategyPublicId": strategyID, - }); + await ConvexClient.instance.mutation(name: "strategies:delete", args: { + "strategyPublicId": strategyID, + }); } catch (error, stackTrace) { final handled = await _reportCloudUnauthenticated( source: 'strategy:delete', From 88f4b2cac50f6ef4316f3a05b07742ee94d2ec9d Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Fri, 20 Mar 2026 04:46:18 -0400 Subject: [PATCH 5/6] Add Convex integration and update project documentation - Updated AGENTS.md to include Convex backend usage guidelines and installation instructions for agent skills. - Created CLAUDE.md to document Convex integration specifics. - Added package-lock.json and skills-lock.json to manage dependencies and skills for Convex. - Introduced VSCodeCounter files for project analysis and metrics tracking. --- .VSCodeCounter/2026-03-20_03-03-11/details.md | 362 +++++++++++ .../2026-03-20_03-03-11/diff-details.md | 15 + .VSCodeCounter/2026-03-20_03-03-11/diff.csv | 2 + .VSCodeCounter/2026-03-20_03-03-11/diff.md | 19 + .VSCodeCounter/2026-03-20_03-03-11/diff.txt | 22 + .../2026-03-20_03-03-11/results.csv | 349 +++++++++++ .../2026-03-20_03-03-11/results.json | 1 + .VSCodeCounter/2026-03-20_03-03-11/results.md | 117 ++++ .../2026-03-20_03-03-11/results.txt | 467 ++++++++++++++ .../skills/convex-create-component/SKILL.md | 411 ++++++++++++ .../agents/openai.yaml | 10 + .../convex-create-component/assets/icon.svg | 3 + .../references/hybrid-components.md | 37 ++ .../references/local-components.md | 38 ++ .../references/packaged-components.md | 51 ++ .../skills/convex-migration-helper/SKILL.md | 524 ++++++++++++++++ .../agents/openai.yaml | 10 + .../convex-migration-helper/assets/icon.svg | 3 + .../skills/convex-performance-audit/SKILL.md | 143 +++++ .../agents/openai.yaml | 10 + .../convex-performance-audit/assets/icon.svg | 3 + .../references/function-budget.md | 232 +++++++ .../references/hot-path-rules.md | 359 +++++++++++ .../references/occ-conflicts.md | 126 ++++ .../references/subscription-cost.md | 252 ++++++++ .agent/skills/convex-quickstart/SKILL.md | 337 ++++++++++ .../convex-quickstart/agents/openai.yaml | 10 + .../skills/convex-quickstart/assets/icon.svg | 4 + .agent/skills/convex-setup-auth/SKILL.md | 113 ++++ .../convex-setup-auth/agents/openai.yaml | 10 + .../skills/convex-setup-auth/assets/icon.svg | 3 + .../convex-setup-auth/references/auth0.md | 116 ++++ .../convex-setup-auth/references/clerk.md | 113 ++++ .../references/convex-auth.md | 143 +++++ .../references/workos-authkit.md | 114 ++++ .../skills/convex-create-component/SKILL.md | 411 ++++++++++++ .../agents/openai.yaml | 10 + .../convex-create-component/assets/icon.svg | 3 + .../references/hybrid-components.md | 37 ++ .../references/local-components.md | 38 ++ .../references/packaged-components.md | 51 ++ .../skills/convex-migration-helper/SKILL.md | 524 ++++++++++++++++ .../agents/openai.yaml | 10 + .../convex-migration-helper/assets/icon.svg | 3 + .../skills/convex-performance-audit/SKILL.md | 143 +++++ .../agents/openai.yaml | 10 + .../convex-performance-audit/assets/icon.svg | 3 + .../references/function-budget.md | 232 +++++++ .../references/hot-path-rules.md | 359 +++++++++++ .../references/occ-conflicts.md | 126 ++++ .../references/subscription-cost.md | 252 ++++++++ .agents/skills/convex-quickstart/SKILL.md | 337 ++++++++++ .../convex-quickstart/agents/openai.yaml | 10 + .../skills/convex-quickstart/assets/icon.svg | 4 + .agents/skills/convex-setup-auth/SKILL.md | 113 ++++ .../convex-setup-auth/agents/openai.yaml | 10 + .../skills/convex-setup-auth/assets/icon.svg | 3 + .../convex-setup-auth/references/auth0.md | 116 ++++ .../convex-setup-auth/references/clerk.md | 113 ++++ .../references/convex-auth.md | 143 +++++ .../references/workos-authkit.md | 114 ++++ .../skills/convex-create-component/SKILL.md | 411 ++++++++++++ .../agents/openai.yaml | 10 + .../convex-create-component/assets/icon.svg | 3 + .../references/hybrid-components.md | 37 ++ .../references/local-components.md | 38 ++ .../references/packaged-components.md | 51 ++ .../skills/convex-migration-helper/SKILL.md | 524 ++++++++++++++++ .../agents/openai.yaml | 10 + .../convex-migration-helper/assets/icon.svg | 3 + .../skills/convex-performance-audit/SKILL.md | 143 +++++ .../agents/openai.yaml | 10 + .../convex-performance-audit/assets/icon.svg | 3 + .../references/function-budget.md | 232 +++++++ .../references/hot-path-rules.md | 359 +++++++++++ .../references/occ-conflicts.md | 126 ++++ .../references/subscription-cost.md | 252 ++++++++ .claude/skills/convex-quickstart/SKILL.md | 337 ++++++++++ .../convex-quickstart/agents/openai.yaml | 10 + .../skills/convex-quickstart/assets/icon.svg | 4 + .claude/skills/convex-setup-auth/SKILL.md | 113 ++++ .../convex-setup-auth/agents/openai.yaml | 10 + .../skills/convex-setup-auth/assets/icon.svg | 3 + .../convex-setup-auth/references/auth0.md | 116 ++++ .../convex-setup-auth/references/clerk.md | 113 ++++ .../references/convex-auth.md | 143 +++++ .../references/workos-authkit.md | 114 ++++ .../skills/convex-create-component/SKILL.md | 411 ++++++++++++ .../agents/openai.yaml | 10 + .../convex-create-component/assets/icon.svg | 3 + .../references/hybrid-components.md | 37 ++ .../references/local-components.md | 38 ++ .../references/packaged-components.md | 51 ++ .../skills/convex-migration-helper/SKILL.md | 524 ++++++++++++++++ .../agents/openai.yaml | 10 + .../convex-migration-helper/assets/icon.svg | 3 + .../skills/convex-performance-audit/SKILL.md | 143 +++++ .../agents/openai.yaml | 10 + .../convex-performance-audit/assets/icon.svg | 3 + .../references/function-budget.md | 232 +++++++ .../references/hot-path-rules.md | 359 +++++++++++ .../references/occ-conflicts.md | 126 ++++ .../references/subscription-cost.md | 252 ++++++++ .windsurf/skills/convex-quickstart/SKILL.md | 337 ++++++++++ .../convex-quickstart/agents/openai.yaml | 10 + .../skills/convex-quickstart/assets/icon.svg | 4 + .windsurf/skills/convex-setup-auth/SKILL.md | 113 ++++ .../convex-setup-auth/agents/openai.yaml | 10 + .../skills/convex-setup-auth/assets/icon.svg | 3 + .../convex-setup-auth/references/auth0.md | 116 ++++ .../convex-setup-auth/references/clerk.md | 113 ++++ .../references/convex-auth.md | 143 +++++ .../references/workos-authkit.md | 114 ++++ AGENTS.md | 8 + CLAUDE.md | 7 + convex/_generated/ai/ai-files.state.json | 13 + convex/_generated/ai/guidelines.md | 303 +++++++++ convex/folders.ts | 186 +++++- convex/schema.ts | 3 + convex/strategies.ts | 22 +- lib/collab/collab_models.dart | 12 + lib/collab/convex_strategy_repository.dart | 24 + .../collab/remote_library_provider.dart | 34 + lib/providers/folder_provider.dart | 63 +- lib/providers/strategy_provider.dart | 366 +++++++++-- lib/widgets/cloud_library_widgets.dart | 380 ------------ lib/widgets/current_path_bar.dart | 122 ++-- lib/widgets/folder_content.dart | 450 -------------- lib/widgets/folder_edit_dialog.dart | 42 +- lib/widgets/folder_navigator.dart | 552 ++++++++++------- lib/widgets/folder_pill.dart | 314 +++++----- lib/widgets/library_models.dart | 64 ++ lib/widgets/pages_bar.dart | 583 ++++++++++++++++-- lib/widgets/strategy_tile/strategy_tile.dart | 230 +++---- .../strategy_tile/strategy_tile_sections.dart | 133 ++-- package-lock.json | 583 ++++++++++++++++++ skills-lock.json | 30 + skills/convex-create-component/SKILL.md | 411 ++++++++++++ .../agents/openai.yaml | 10 + .../convex-create-component/assets/icon.svg | 3 + .../references/hybrid-components.md | 37 ++ .../references/local-components.md | 38 ++ .../references/packaged-components.md | 51 ++ skills/convex-migration-helper/SKILL.md | 524 ++++++++++++++++ .../agents/openai.yaml | 10 + .../convex-migration-helper/assets/icon.svg | 3 + skills/convex-performance-audit/SKILL.md | 143 +++++ .../agents/openai.yaml | 10 + .../convex-performance-audit/assets/icon.svg | 3 + .../references/function-budget.md | 232 +++++++ .../references/hot-path-rules.md | 359 +++++++++++ .../references/occ-conflicts.md | 126 ++++ .../references/subscription-cost.md | 252 ++++++++ skills/convex-quickstart/SKILL.md | 337 ++++++++++ skills/convex-quickstart/agents/openai.yaml | 10 + skills/convex-quickstart/assets/icon.svg | 4 + skills/convex-setup-auth/SKILL.md | 113 ++++ skills/convex-setup-auth/agents/openai.yaml | 10 + skills/convex-setup-auth/assets/icon.svg | 3 + skills/convex-setup-auth/references/auth0.md | 116 ++++ skills/convex-setup-auth/references/clerk.md | 113 ++++ .../references/convex-auth.md | 143 +++++ .../references/workos-authkit.md | 114 ++++ tool/_probe.dart | 34 + 164 files changed, 20205 insertions(+), 1582 deletions(-) create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/details.md create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/diff-details.md create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/diff.csv create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/diff.md create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/diff.txt create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/results.csv create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/results.json create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/results.md create mode 100644 .VSCodeCounter/2026-03-20_03-03-11/results.txt create mode 100644 .agent/skills/convex-create-component/SKILL.md create mode 100644 .agent/skills/convex-create-component/agents/openai.yaml create mode 100644 .agent/skills/convex-create-component/assets/icon.svg create mode 100644 .agent/skills/convex-create-component/references/hybrid-components.md create mode 100644 .agent/skills/convex-create-component/references/local-components.md create mode 100644 .agent/skills/convex-create-component/references/packaged-components.md create mode 100644 .agent/skills/convex-migration-helper/SKILL.md create mode 100644 .agent/skills/convex-migration-helper/agents/openai.yaml create mode 100644 .agent/skills/convex-migration-helper/assets/icon.svg create mode 100644 .agent/skills/convex-performance-audit/SKILL.md create mode 100644 .agent/skills/convex-performance-audit/agents/openai.yaml create mode 100644 .agent/skills/convex-performance-audit/assets/icon.svg create mode 100644 .agent/skills/convex-performance-audit/references/function-budget.md create mode 100644 .agent/skills/convex-performance-audit/references/hot-path-rules.md create mode 100644 .agent/skills/convex-performance-audit/references/occ-conflicts.md create mode 100644 .agent/skills/convex-performance-audit/references/subscription-cost.md create mode 100644 .agent/skills/convex-quickstart/SKILL.md create mode 100644 .agent/skills/convex-quickstart/agents/openai.yaml create mode 100644 .agent/skills/convex-quickstart/assets/icon.svg create mode 100644 .agent/skills/convex-setup-auth/SKILL.md create mode 100644 .agent/skills/convex-setup-auth/agents/openai.yaml create mode 100644 .agent/skills/convex-setup-auth/assets/icon.svg create mode 100644 .agent/skills/convex-setup-auth/references/auth0.md create mode 100644 .agent/skills/convex-setup-auth/references/clerk.md create mode 100644 .agent/skills/convex-setup-auth/references/convex-auth.md create mode 100644 .agent/skills/convex-setup-auth/references/workos-authkit.md create mode 100644 .agents/skills/convex-create-component/SKILL.md create mode 100644 .agents/skills/convex-create-component/agents/openai.yaml create mode 100644 .agents/skills/convex-create-component/assets/icon.svg create mode 100644 .agents/skills/convex-create-component/references/hybrid-components.md create mode 100644 .agents/skills/convex-create-component/references/local-components.md create mode 100644 .agents/skills/convex-create-component/references/packaged-components.md create mode 100644 .agents/skills/convex-migration-helper/SKILL.md create mode 100644 .agents/skills/convex-migration-helper/agents/openai.yaml create mode 100644 .agents/skills/convex-migration-helper/assets/icon.svg create mode 100644 .agents/skills/convex-performance-audit/SKILL.md create mode 100644 .agents/skills/convex-performance-audit/agents/openai.yaml create mode 100644 .agents/skills/convex-performance-audit/assets/icon.svg create mode 100644 .agents/skills/convex-performance-audit/references/function-budget.md create mode 100644 .agents/skills/convex-performance-audit/references/hot-path-rules.md create mode 100644 .agents/skills/convex-performance-audit/references/occ-conflicts.md create mode 100644 .agents/skills/convex-performance-audit/references/subscription-cost.md create mode 100644 .agents/skills/convex-quickstart/SKILL.md create mode 100644 .agents/skills/convex-quickstart/agents/openai.yaml create mode 100644 .agents/skills/convex-quickstart/assets/icon.svg create mode 100644 .agents/skills/convex-setup-auth/SKILL.md create mode 100644 .agents/skills/convex-setup-auth/agents/openai.yaml create mode 100644 .agents/skills/convex-setup-auth/assets/icon.svg create mode 100644 .agents/skills/convex-setup-auth/references/auth0.md create mode 100644 .agents/skills/convex-setup-auth/references/clerk.md create mode 100644 .agents/skills/convex-setup-auth/references/convex-auth.md create mode 100644 .agents/skills/convex-setup-auth/references/workos-authkit.md create mode 100644 .claude/skills/convex-create-component/SKILL.md create mode 100644 .claude/skills/convex-create-component/agents/openai.yaml create mode 100644 .claude/skills/convex-create-component/assets/icon.svg create mode 100644 .claude/skills/convex-create-component/references/hybrid-components.md create mode 100644 .claude/skills/convex-create-component/references/local-components.md create mode 100644 .claude/skills/convex-create-component/references/packaged-components.md create mode 100644 .claude/skills/convex-migration-helper/SKILL.md create mode 100644 .claude/skills/convex-migration-helper/agents/openai.yaml create mode 100644 .claude/skills/convex-migration-helper/assets/icon.svg create mode 100644 .claude/skills/convex-performance-audit/SKILL.md create mode 100644 .claude/skills/convex-performance-audit/agents/openai.yaml create mode 100644 .claude/skills/convex-performance-audit/assets/icon.svg create mode 100644 .claude/skills/convex-performance-audit/references/function-budget.md create mode 100644 .claude/skills/convex-performance-audit/references/hot-path-rules.md create mode 100644 .claude/skills/convex-performance-audit/references/occ-conflicts.md create mode 100644 .claude/skills/convex-performance-audit/references/subscription-cost.md create mode 100644 .claude/skills/convex-quickstart/SKILL.md create mode 100644 .claude/skills/convex-quickstart/agents/openai.yaml create mode 100644 .claude/skills/convex-quickstart/assets/icon.svg create mode 100644 .claude/skills/convex-setup-auth/SKILL.md create mode 100644 .claude/skills/convex-setup-auth/agents/openai.yaml create mode 100644 .claude/skills/convex-setup-auth/assets/icon.svg create mode 100644 .claude/skills/convex-setup-auth/references/auth0.md create mode 100644 .claude/skills/convex-setup-auth/references/clerk.md create mode 100644 .claude/skills/convex-setup-auth/references/convex-auth.md create mode 100644 .claude/skills/convex-setup-auth/references/workos-authkit.md create mode 100644 .windsurf/skills/convex-create-component/SKILL.md create mode 100644 .windsurf/skills/convex-create-component/agents/openai.yaml create mode 100644 .windsurf/skills/convex-create-component/assets/icon.svg create mode 100644 .windsurf/skills/convex-create-component/references/hybrid-components.md create mode 100644 .windsurf/skills/convex-create-component/references/local-components.md create mode 100644 .windsurf/skills/convex-create-component/references/packaged-components.md create mode 100644 .windsurf/skills/convex-migration-helper/SKILL.md create mode 100644 .windsurf/skills/convex-migration-helper/agents/openai.yaml create mode 100644 .windsurf/skills/convex-migration-helper/assets/icon.svg create mode 100644 .windsurf/skills/convex-performance-audit/SKILL.md create mode 100644 .windsurf/skills/convex-performance-audit/agents/openai.yaml create mode 100644 .windsurf/skills/convex-performance-audit/assets/icon.svg create mode 100644 .windsurf/skills/convex-performance-audit/references/function-budget.md create mode 100644 .windsurf/skills/convex-performance-audit/references/hot-path-rules.md create mode 100644 .windsurf/skills/convex-performance-audit/references/occ-conflicts.md create mode 100644 .windsurf/skills/convex-performance-audit/references/subscription-cost.md create mode 100644 .windsurf/skills/convex-quickstart/SKILL.md create mode 100644 .windsurf/skills/convex-quickstart/agents/openai.yaml create mode 100644 .windsurf/skills/convex-quickstart/assets/icon.svg create mode 100644 .windsurf/skills/convex-setup-auth/SKILL.md create mode 100644 .windsurf/skills/convex-setup-auth/agents/openai.yaml create mode 100644 .windsurf/skills/convex-setup-auth/assets/icon.svg create mode 100644 .windsurf/skills/convex-setup-auth/references/auth0.md create mode 100644 .windsurf/skills/convex-setup-auth/references/clerk.md create mode 100644 .windsurf/skills/convex-setup-auth/references/convex-auth.md create mode 100644 .windsurf/skills/convex-setup-auth/references/workos-authkit.md create mode 100644 CLAUDE.md create mode 100644 convex/_generated/ai/ai-files.state.json create mode 100644 convex/_generated/ai/guidelines.md delete mode 100644 lib/widgets/cloud_library_widgets.dart delete mode 100644 lib/widgets/folder_content.dart create mode 100644 lib/widgets/library_models.dart create mode 100644 package-lock.json create mode 100644 skills-lock.json create mode 100644 skills/convex-create-component/SKILL.md create mode 100644 skills/convex-create-component/agents/openai.yaml create mode 100644 skills/convex-create-component/assets/icon.svg create mode 100644 skills/convex-create-component/references/hybrid-components.md create mode 100644 skills/convex-create-component/references/local-components.md create mode 100644 skills/convex-create-component/references/packaged-components.md create mode 100644 skills/convex-migration-helper/SKILL.md create mode 100644 skills/convex-migration-helper/agents/openai.yaml create mode 100644 skills/convex-migration-helper/assets/icon.svg create mode 100644 skills/convex-performance-audit/SKILL.md create mode 100644 skills/convex-performance-audit/agents/openai.yaml create mode 100644 skills/convex-performance-audit/assets/icon.svg create mode 100644 skills/convex-performance-audit/references/function-budget.md create mode 100644 skills/convex-performance-audit/references/hot-path-rules.md create mode 100644 skills/convex-performance-audit/references/occ-conflicts.md create mode 100644 skills/convex-performance-audit/references/subscription-cost.md create mode 100644 skills/convex-quickstart/SKILL.md create mode 100644 skills/convex-quickstart/agents/openai.yaml create mode 100644 skills/convex-quickstart/assets/icon.svg create mode 100644 skills/convex-setup-auth/SKILL.md create mode 100644 skills/convex-setup-auth/agents/openai.yaml create mode 100644 skills/convex-setup-auth/assets/icon.svg create mode 100644 skills/convex-setup-auth/references/auth0.md create mode 100644 skills/convex-setup-auth/references/clerk.md create mode 100644 skills/convex-setup-auth/references/convex-auth.md create mode 100644 skills/convex-setup-auth/references/workos-authkit.md create mode 100644 tool/_probe.dart diff --git a/.VSCodeCounter/2026-03-20_03-03-11/details.md b/.VSCodeCounter/2026-03-20_03-03-11/details.md new file mode 100644 index 00000000..3e5ee937 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/details.md @@ -0,0 +1,362 @@ +# Details + +Date : 2026-03-20 03:03:11 + +Directory e:\\Projects\\icarus + +Total : 347 files, 37981 codes, 2032 comments, 4665 blanks, all 44678 lines + +[Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md) + +## Files +| filename | language | code | comment | blank | total | +| :--- | :--- | ---: | ---: | ---: | ---: | +| [.cursor/rules/code-gen-rules.mdc](/.cursor/rules/code-gen-rules.mdc) | Markdown | 10 | 0 | 4 | 14 | +| [.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc](/.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc) | Markdown | 87 | 0 | 25 | 112 | +| [.cursor/skills/frontend-design/SKILL.md](/.cursor/skills/frontend-design/SKILL.md) | Markdown | 30 | 0 | 13 | 43 | +| [.zed/debug.json](/.zed/debug.json) | JSON | 9 | 0 | 1 | 10 | +| [.zed/tasks.json](/.zed/tasks.json) | JSON with Comments | 51 | 147 | 4 | 202 | +| [AGENTS.md](/AGENTS.md) | Markdown | 15 | 0 | 7 | 22 | +| [LICENSE.md](/LICENSE.md) | Markdown | 10 | 0 | 5 | 15 | +| [README.md](/README.md) | Markdown | 42 | 0 | 14 | 56 | +| [analysis_options.yaml](/analysis_options.yaml) | YAML | 6 | 22 | 4 | 32 | +| [android/app/build.gradle](/android/app/build.gradle) | Groovy | 44 | 6 | 9 | 59 | +| [android/app/src/debug/AndroidManifest.xml](/android/app/src/debug/AndroidManifest.xml) | XML | 3 | 4 | 1 | 8 | +| [android/app/src/main/AndroidManifest.xml](/android/app/src/main/AndroidManifest.xml) | XML | 34 | 11 | 1 | 46 | +| [android/app/src/main/res/drawable-v21/launch_background.xml](/android/app/src/main/res/drawable-v21/launch_background.xml) | XML | 4 | 7 | 2 | 13 | +| [android/app/src/main/res/drawable/launch_background.xml](/android/app/src/main/res/drawable/launch_background.xml) | XML | 4 | 7 | 2 | 13 | +| [android/app/src/main/res/values-night/styles.xml](/android/app/src/main/res/values-night/styles.xml) | XML | 9 | 9 | 1 | 19 | +| [android/app/src/main/res/values/styles.xml](/android/app/src/main/res/values/styles.xml) | XML | 9 | 9 | 1 | 19 | +| [android/app/src/profile/AndroidManifest.xml](/android/app/src/profile/AndroidManifest.xml) | XML | 3 | 4 | 1 | 8 | +| [android/build.gradle](/android/build.gradle) | Groovy | 16 | 0 | 3 | 19 | +| [android/gradle.properties](/android/gradle.properties) | Properties | 3 | 0 | 1 | 4 | +| [android/gradle/wrapper/gradle-wrapper.properties](/android/gradle/wrapper/gradle-wrapper.properties) | Properties | 5 | 0 | 1 | 6 | +| [android/settings.gradle](/android/settings.gradle) | Groovy | 21 | 0 | 5 | 26 | +| [assets/folder_tile.svg](/assets/folder_tile.svg) | XML | 4 | 0 | 1 | 5 | +| [assets/fonts/config.json](/assets/fonts/config.json) | JSON | 122 | 0 | 0 | 122 | +| [assets/maps/abyss_call_outs.svg](/assets/maps/abyss_call_outs.svg) | XML | 65 | 0 | 1 | 66 | +| [assets/maps/abyss_call_outs_defense.svg](/assets/maps/abyss_call_outs_defense.svg) | XML | 65 | 0 | 1 | 66 | +| [assets/maps/abyss_map.svg](/assets/maps/abyss_map.svg) | XML | 22 | 0 | 1 | 23 | +| [assets/maps/abyss_map_defense.svg](/assets/maps/abyss_map_defense.svg) | XML | 22 | 0 | 1 | 23 | +| [assets/maps/abyss_spawn_walls.svg](/assets/maps/abyss_spawn_walls.svg) | XML | 11 | 0 | 1 | 12 | +| [assets/maps/abyss_ult_orbs.svg](/assets/maps/abyss_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/ascent_call_outs.svg](/assets/maps/ascent_call_outs.svg) | XML | 62 | 0 | 1 | 63 | +| [assets/maps/ascent_call_outs_defense.svg](/assets/maps/ascent_call_outs_defense.svg) | XML | 62 | 0 | 1 | 63 | +| [assets/maps/ascent_map.svg](/assets/maps/ascent_map.svg) | XML | 20 | 0 | 1 | 21 | +| [assets/maps/ascent_map_defense.svg](/assets/maps/ascent_map_defense.svg) | XML | 20 | 0 | 1 | 21 | +| [assets/maps/ascent_map_spawn_wall.svg](/assets/maps/ascent_map_spawn_wall.svg) | XML | 12 | 0 | 1 | 13 | +| [assets/maps/ascent_spawn_walls.svg](/assets/maps/ascent_spawn_walls.svg) | XML | 12 | 0 | 1 | 13 | +| [assets/maps/ascent_ult_orbs.svg](/assets/maps/ascent_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/bind_call_outs.svg](/assets/maps/bind_call_outs.svg) | XML | 68 | 0 | 1 | 69 | +| [assets/maps/bind_call_outs_defense.svg](/assets/maps/bind_call_outs_defense.svg) | XML | 68 | 0 | 1 | 69 | +| [assets/maps/bind_map.svg](/assets/maps/bind_map.svg) | XML | 25 | 0 | 1 | 26 | +| [assets/maps/bind_map_defense.svg](/assets/maps/bind_map_defense.svg) | XML | 25 | 0 | 1 | 26 | +| [assets/maps/bind_spawn_walls.svg](/assets/maps/bind_spawn_walls.svg) | XML | 12 | 0 | 1 | 13 | +| [assets/maps/bind_ult_orbs.svg](/assets/maps/bind_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/breeze_call_outs.svg](/assets/maps/breeze_call_outs.svg) | XML | 65 | 0 | 1 | 66 | +| [assets/maps/breeze_call_outs_defense.svg](/assets/maps/breeze_call_outs_defense.svg) | XML | 65 | 0 | 1 | 66 | +| [assets/maps/breeze_map.svg](/assets/maps/breeze_map.svg) | XML | 13 | 0 | 1 | 14 | +| [assets/maps/breeze_map_defense.svg](/assets/maps/breeze_map_defense.svg) | XML | 13 | 0 | 1 | 14 | +| [assets/maps/breeze_spawn_walls.svg](/assets/maps/breeze_spawn_walls.svg) | XML | 12 | 0 | 1 | 13 | +| [assets/maps/breeze_ult_orbs.svg](/assets/maps/breeze_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/corrode_call_outs.svg](/assets/maps/corrode_call_outs.svg) | XML | 59 | 0 | 1 | 60 | +| [assets/maps/corrode_call_outs_defense.svg](/assets/maps/corrode_call_outs_defense.svg) | XML | 59 | 0 | 1 | 60 | +| [assets/maps/corrode_map.svg](/assets/maps/corrode_map.svg) | XML | 15 | 0 | 1 | 16 | +| [assets/maps/corrode_map_defense.svg](/assets/maps/corrode_map_defense.svg) | XML | 15 | 0 | 1 | 16 | +| [assets/maps/corrode_spawn_walls.svg](/assets/maps/corrode_spawn_walls.svg) | XML | 11 | 0 | 1 | 12 | +| [assets/maps/corrode_ult_orbs.svg](/assets/maps/corrode_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/fracture_call_outs.svg](/assets/maps/fracture_call_outs.svg) | XML | 62 | 0 | 1 | 63 | +| [assets/maps/fracture_call_outs_defense.svg](/assets/maps/fracture_call_outs_defense.svg) | XML | 62 | 0 | 1 | 63 | +| [assets/maps/fracture_map.svg](/assets/maps/fracture_map.svg) | XML | 27 | 0 | 1 | 28 | +| [assets/maps/fracture_map_defense.svg](/assets/maps/fracture_map_defense.svg) | XML | 27 | 0 | 1 | 28 | +| [assets/maps/fracture_spawn_walls.svg](/assets/maps/fracture_spawn_walls.svg) | XML | 13 | 0 | 1 | 14 | +| [assets/maps/fracture_ult_orbs.svg](/assets/maps/fracture_ult_orbs.svg) | XML | 10 | 0 | 1 | 11 | +| [assets/maps/haven_call_outs.svg](/assets/maps/haven_call_outs.svg) | XML | 56 | 0 | 1 | 57 | +| [assets/maps/haven_call_outs_defense.svg](/assets/maps/haven_call_outs_defense.svg) | XML | 56 | 0 | 1 | 57 | +| [assets/maps/haven_map.svg](/assets/maps/haven_map.svg) | XML | 17 | 0 | 1 | 18 | +| [assets/maps/haven_map_defense.svg](/assets/maps/haven_map_defense.svg) | XML | 17 | 0 | 1 | 18 | +| [assets/maps/haven_spawn_walls.svg](/assets/maps/haven_spawn_walls.svg) | XML | 11 | 0 | 1 | 12 | +| [assets/maps/haven_ult_orbs.svg](/assets/maps/haven_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/icebox_call_outs.svg](/assets/maps/icebox_call_outs.svg) | XML | 71 | 0 | 1 | 72 | +| [assets/maps/icebox_call_outs_defense.svg](/assets/maps/icebox_call_outs_defense.svg) | XML | 71 | 0 | 1 | 72 | +| [assets/maps/icebox_map.svg](/assets/maps/icebox_map.svg) | XML | 27 | 0 | 1 | 28 | +| [assets/maps/icebox_map_defense.svg](/assets/maps/icebox_map_defense.svg) | XML | 27 | 0 | 1 | 28 | +| [assets/maps/icebox_spawn_walls.svg](/assets/maps/icebox_spawn_walls.svg) | XML | 14 | 0 | 1 | 15 | +| [assets/maps/icebox_ult_orbs.svg](/assets/maps/icebox_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/lotus_call_outs.svg](/assets/maps/lotus_call_outs.svg) | XML | 71 | 0 | 1 | 72 | +| [assets/maps/lotus_call_outs_defense.svg](/assets/maps/lotus_call_outs_defense.svg) | XML | 71 | 0 | 1 | 72 | +| [assets/maps/lotus_map.svg](/assets/maps/lotus_map.svg) | XML | 23 | 0 | 1 | 24 | +| [assets/maps/lotus_map_defense.svg](/assets/maps/lotus_map_defense.svg) | XML | 23 | 0 | 1 | 24 | +| [assets/maps/lotus_spawn_walls.svg](/assets/maps/lotus_spawn_walls.svg) | XML | 9 | 0 | 1 | 10 | +| [assets/maps/lotus_ult_orbs.svg](/assets/maps/lotus_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/pearl_call_outs.svg](/assets/maps/pearl_call_outs.svg) | XML | 74 | 0 | 1 | 75 | +| [assets/maps/pearl_call_outs_defense.svg](/assets/maps/pearl_call_outs_defense.svg) | XML | 74 | 0 | 1 | 75 | +| [assets/maps/pearl_map.svg](/assets/maps/pearl_map.svg) | XML | 32 | 0 | 1 | 33 | +| [assets/maps/pearl_map_defense.svg](/assets/maps/pearl_map_defense.svg) | XML | 32 | 0 | 1 | 33 | +| [assets/maps/pearl_spawn_walls.svg](/assets/maps/pearl_spawn_walls.svg) | XML | 10 | 0 | 1 | 11 | +| [assets/maps/pearl_ult_orbs.svg](/assets/maps/pearl_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/split_call_outs.svg](/assets/maps/split_call_outs.svg) | XML | 68 | 0 | 1 | 69 | +| [assets/maps/split_call_outs_defense.svg](/assets/maps/split_call_outs_defense.svg) | XML | 68 | 0 | 1 | 69 | +| [assets/maps/split_map.svg](/assets/maps/split_map.svg) | XML | 31 | 0 | 1 | 32 | +| [assets/maps/split_map_defense.svg](/assets/maps/split_map_defense.svg) | XML | 31 | 0 | 1 | 32 | +| [assets/maps/split_spawn_walls.svg](/assets/maps/split_spawn_walls.svg) | XML | 11 | 0 | 1 | 12 | +| [assets/maps/split_ult_orbs.svg](/assets/maps/split_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/maps/sunsent_map.svg](/assets/maps/sunsent_map.svg) | XML | 26 | 0 | 1 | 27 | +| [assets/maps/sunsent_map_defense.svg](/assets/maps/sunsent_map_defense.svg) | XML | 26 | 0 | 1 | 27 | +| [assets/maps/sunset_call_outs.svg](/assets/maps/sunset_call_outs.svg) | XML | 47 | 0 | 1 | 48 | +| [assets/maps/sunset_call_outs_defense.svg](/assets/maps/sunset_call_outs_defense.svg) | XML | 47 | 0 | 1 | 48 | +| [assets/maps/sunset_map.svg](/assets/maps/sunset_map.svg) | XML | 30 | 0 | 1 | 31 | +| [assets/maps/sunset_map_defense.svg](/assets/maps/sunset_map_defense.svg) | XML | 30 | 0 | 1 | 31 | +| [assets/maps/sunset_spawn_walls.svg](/assets/maps/sunset_spawn_walls.svg) | XML | 12 | 0 | 1 | 13 | +| [assets/maps/sunset_ult_orbs.svg](/assets/maps/sunset_ult_orbs.svg) | XML | 6 | 0 | 1 | 7 | +| [assets/spike.svg](/assets/spike.svg) | XML | 6 | 0 | 1 | 7 | +| [build_script.dart](/build_script.dart) | Dart | 34 | 5 | 14 | 53 | +| [bun.lock](/bun.lock) | JSON with Comments | 55 | 0 | 35 | 90 | +| [convex/_generated/api.d.ts](/convex/_generated/api.d.ts) | TypeScript | 44 | 25 | 7 | 76 | +| [convex/_generated/api.js](/convex/_generated/api.js) | JavaScript | 4 | 17 | 3 | 24 | +| [convex/_generated/dataModel.d.ts](/convex/_generated/dataModel.d.ts) | TypeScript | 16 | 39 | 6 | 61 | +| [convex/_generated/server.d.ts](/convex/_generated/server.d.ts) | TypeScript | 24 | 106 | 14 | 144 | +| [convex/_generated/server.js](/convex/_generated/server.js) | JavaScript | 16 | 69 | 9 | 94 | +| [convex/auth.config.ts](/convex/auth.config.ts) | TypeScript | 12 | 0 | 2 | 14 | +| [convex/elements.ts](/convex/elements.ts) | TypeScript | 36 | 0 | 5 | 41 | +| [convex/folders.ts](/convex/folders.ts) | TypeScript | 152 | 0 | 26 | 178 | +| [convex/health.ts](/convex/health.ts) | TypeScript | 7 | 1 | 1 | 9 | +| [convex/images.ts](/convex/images.ts) | TypeScript | 125 | 0 | 17 | 142 | +| [convex/invites.ts](/convex/invites.ts) | TypeScript | 167 | 0 | 26 | 193 | +| [convex/lib/auth.ts](/convex/lib/auth.ts) | TypeScript | 60 | 0 | 15 | 75 | +| [convex/lib/entities.ts](/convex/lib/entities.ts) | TypeScript | 74 | 0 | 18 | 92 | +| [convex/lib/errors.ts](/convex/lib/errors.ts) | TypeScript | 10 | 0 | 2 | 12 | +| [convex/lib/opTypes.ts](/convex/lib/opTypes.ts) | TypeScript | 25 | 0 | 4 | 29 | +| [convex/lineups.ts](/convex/lineups.ts) | TypeScript | 35 | 0 | 5 | 40 | +| [convex/ops.ts](/convex/ops.ts) | TypeScript | 475 | 1 | 29 | 505 | +| [convex/pages.ts](/convex/pages.ts) | TypeScript | 222 | 0 | 36 | 258 | +| [convex/schema.ts](/convex/schema.ts) | TypeScript | 135 | 1 | 4 | 140 | +| [convex/strategies.ts](/convex/strategies.ts) | TypeScript | 248 | 0 | 41 | 289 | +| [convex/users.ts](/convex/users.ts) | TypeScript | 58 | 0 | 10 | 68 | +| [devtools_options.yaml](/devtools_options.yaml) | YAML | 4 | 0 | 0 | 4 | +| [docs/version.json](/docs/version.json) | JSON | 11 | 0 | 0 | 11 | +| [docs/windows_store_update_testing.md](/docs/windows_store_update_testing.md) | Markdown | 25 | 0 | 10 | 35 | +| [flutter_convex_overview.md](/flutter_convex_overview.md) | Markdown | 379 | 0 | 114 | 493 | +| [index.ts](/index.ts) | TypeScript | 1 | 0 | 0 | 1 | +| [ios/RunnerTests/RunnerTests.swift](/ios/RunnerTests/RunnerTests.swift) | Swift | 7 | 2 | 4 | 13 | +| [ios/Runner/AppDelegate.swift](/ios/Runner/AppDelegate.swift) | Swift | 12 | 0 | 2 | 14 | +| [ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json](/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json) | JSON | 122 | 0 | 1 | 123 | +| [ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json](/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json) | JSON | 23 | 0 | 1 | 24 | +| [ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md](/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md) | Markdown | 3 | 0 | 2 | 5 | +| [ios/Runner/Base.lproj/LaunchScreen.storyboard](/ios/Runner/Base.lproj/LaunchScreen.storyboard) | XML | 36 | 1 | 1 | 38 | +| [ios/Runner/Base.lproj/Main.storyboard](/ios/Runner/Base.lproj/Main.storyboard) | XML | 25 | 1 | 1 | 27 | +| [ios/Runner/Runner-Bridging-Header.h](/ios/Runner/Runner-Bridging-Header.h) | C++ | 1 | 0 | 1 | 2 | +| [lib/collab/collab_models.dart](/lib/collab/collab_models.dart) | Dart | 331 | 0 | 38 | 369 | +| [lib/collab/convex_payload.dart](/lib/collab/convex_payload.dart) | Dart | 31 | 0 | 5 | 36 | +| [lib/collab/convex_strategy_repository.dart](/lib/collab/convex_strategy_repository.dart) | Dart | 223 | 0 | 30 | 253 | +| [lib/const/abilities.dart](/lib/const/abilities.dart) | Dart | 371 | 3 | 43 | 417 | +| [lib/const/agents.dart](/lib/const/agents.dart) | Dart | 787 | 27 | 103 | 917 | +| [lib/const/app_navigator.dart](/lib/const/app_navigator.dart) | Dart | 2 | 2 | 2 | 6 | +| [lib/const/bounding_box.dart](/lib/const/bounding_box.dart) | Dart | 26 | 0 | 9 | 35 | +| [lib/const/bounding_box.g.dart](/lib/const/bounding_box.g.dart) | Dart | 12 | 4 | 5 | 21 | +| [lib/const/color_option.dart](/lib/const/color_option.dart) | Dart | 6 | 0 | 3 | 9 | +| [lib/const/coordinate_system.dart](/lib/const/coordinate_system.dart) | Dart | 77 | 7 | 22 | 106 | +| [lib/const/custom_icons.dart](/lib/const/custom_icons.dart) | Dart | 22 | 0 | 4 | 26 | +| [lib/const/default_placement.dart](/lib/const/default_placement.dart) | Dart | 27 | 0 | 4 | 31 | +| [lib/const/drawing_element.dart](/lib/const/drawing_element.dart) | Dart | 235 | 6 | 47 | 288 | +| [lib/const/drawing_element.g.dart](/lib/const/drawing_element.g.dart) | Dart | 39 | 4 | 7 | 50 | +| [lib/const/hive_boxes.dart](/lib/const/hive_boxes.dart) | Dart | 7 | 0 | 1 | 8 | +| [lib/const/image_scale_policy.dart](/lib/const/image_scale_policy.dart) | Dart | 8 | 0 | 2 | 10 | +| [lib/const/json_converters.dart](/lib/const/json_converters.dart) | Dart | 126 | 7 | 24 | 157 | +| [lib/const/line_provider.dart](/lib/const/line_provider.dart) | Dart | 280 | 13 | 54 | 347 | +| [lib/const/line_provider.g.dart](/lib/const/line_provider.g.dart) | Dart | 29 | 4 | 7 | 40 | +| [lib/const/maps.dart](/lib/const/maps.dart) | Dart | 60 | 0 | 5 | 65 | +| [lib/const/placed_classes.dart](/lib/const/placed_classes.dart) | Dart | 566 | 19 | 119 | 704 | +| [lib/const/placed_classes.g.dart](/lib/const/placed_classes.g.dart) | Dart | 171 | 4 | 18 | 193 | +| [lib/const/routes.dart](/lib/const/routes.dart) | Dart | 5 | 0 | 1 | 6 | +| [lib/const/second_instance_args.dart](/lib/const/second_instance_args.dart) | Dart | 7 | 3 | 3 | 13 | +| [lib/const/settings.dart](/lib/const/settings.dart) | Dart | 160 | 16 | 19 | 195 | +| [lib/const/shortcut_info.dart](/lib/const/shortcut_info.dart) | Dart | 85 | 6 | 19 | 110 | +| [lib/const/transition_data.dart](/lib/const/transition_data.dart) | Dart | 138 | 6 | 25 | 169 | +| [lib/const/traversal_speed.dart](/lib/const/traversal_speed.dart) | Dart | 16 | 1 | 3 | 20 | +| [lib/const/update_checker.dart](/lib/const/update_checker.dart) | Dart | 249 | 0 | 30 | 279 | +| [lib/const/utilities.dart](/lib/const/utilities.dart) | Dart | 423 | 19 | 48 | 490 | +| [lib/const/youtube_handler.dart](/lib/const/youtube_handler.dart) | Dart | 24 | 1 | 3 | 28 | +| [lib/hive/hive_adapters.dart](/lib/hive/hive_adapters.dart) | Dart | 48 | 1 | 4 | 53 | +| [lib/hive/hive_adapters.g.dart](/lib/hive/hive_adapters.g.dart) | Dart | 1,340 | 4 | 138 | 1,482 | +| [lib/hive/hive_adapters.g.yaml](/lib/hive/hive_adapters.g.yaml) | YAML | 492 | 3 | 1 | 496 | +| [lib/hive/hive_registrar.g.dart](/lib/hive/hive_registrar.g.dart) | Dart | 67 | 3 | 4 | 74 | +| [lib/home_view.dart](/lib/home_view.dart) | Dart | 13 | 0 | 4 | 17 | +| [lib/interactive_map.dart](/lib/interactive_map.dart) | Dart | 343 | 5 | 18 | 366 | +| [lib/main.dart](/lib/main.dart) | Dart | 272 | 10 | 46 | 328 | +| [lib/migrations/ability_scale_migration.dart](/lib/migrations/ability_scale_migration.dart) | Dart | 269 | 1 | 39 | 309 | +| [lib/providers/ability_bar_provider.dart](/lib/providers/ability_bar_provider.dart) | Dart | 13 | 0 | 4 | 17 | +| [lib/providers/ability_provider.dart](/lib/providers/ability_provider.dart) | Dart | 156 | 16 | 55 | 227 | +| [lib/providers/action_provider.dart](/lib/providers/action_provider.dart) | Dart | 151 | 12 | 29 | 192 | +| [lib/providers/agent_filter_provider.dart](/lib/providers/agent_filter_provider.dart) | Dart | 117 | 0 | 17 | 134 | +| [lib/providers/agent_provider.dart](/lib/providers/agent_provider.dart) | Dart | 155 | 4 | 47 | 206 | +| [lib/providers/auth_provider.dart](/lib/providers/auth_provider.dart) | Dart | 789 | 1 | 90 | 880 | +| [lib/providers/auto_save_notifier.dart](/lib/providers/auto_save_notifier.dart) | Dart | 12 | 0 | 4 | 16 | +| [lib/providers/collab/cloud_collab_provider.dart](/lib/providers/collab/cloud_collab_provider.dart) | Dart | 55 | 1 | 10 | 66 | +| [lib/providers/collab/cloud_migration_provider.dart](/lib/providers/collab/cloud_migration_provider.dart) | Dart | 222 | 0 | 26 | 248 | +| [lib/providers/collab/remote_library_provider.dart](/lib/providers/collab/remote_library_provider.dart) | Dart | 82 | 0 | 10 | 92 | +| [lib/providers/collab/remote_strategy_snapshot_provider.dart](/lib/providers/collab/remote_strategy_snapshot_provider.dart) | Dart | 232 | 1 | 35 | 268 | +| [lib/providers/collab/strategy_conflict_provider.dart](/lib/providers/collab/strategy_conflict_provider.dart) | Dart | 21 | 0 | 6 | 27 | +| [lib/providers/collab/strategy_op_queue_provider.dart](/lib/providers/collab/strategy_op_queue_provider.dart) | Dart | 226 | 0 | 40 | 266 | +| [lib/providers/drawing_provider.dart](/lib/providers/drawing_provider.dart) | Dart | 501 | 50 | 111 | 662 | +| [lib/providers/favorite_agents_provider.dart](/lib/providers/favorite_agents_provider.dart) | Dart | 40 | 1 | 9 | 50 | +| [lib/providers/folder_provider.dart](/lib/providers/folder_provider.dart) | Dart | 274 | 0 | 34 | 308 | +| [lib/providers/image_provider.dart](/lib/providers/image_provider.dart) | Dart | 374 | 60 | 96 | 530 | +| [lib/providers/image_widget_size_provider.dart](/lib/providers/image_widget_size_provider.dart) | Dart | 21 | 0 | 7 | 28 | +| [lib/providers/in_app_debug_provider.dart](/lib/providers/in_app_debug_provider.dart) | Dart | 18 | 0 | 6 | 24 | +| [lib/providers/interaction_state_provider.dart](/lib/providers/interaction_state_provider.dart) | Dart | 41 | 1 | 9 | 51 | +| [lib/providers/map_provider.dart](/lib/providers/map_provider.dart) | Dart | 85 | 1 | 20 | 106 | +| [lib/providers/map_theme_provider.dart](/lib/providers/map_theme_provider.dart) | Dart | 421 | 0 | 60 | 481 | +| [lib/providers/pen_provider.dart](/lib/providers/pen_provider.dart) | Dart | 156 | 0 | 20 | 176 | +| [lib/providers/placement_center_provider.dart](/lib/providers/placement_center_provider.dart) | Dart | 13 | 0 | 5 | 18 | +| [lib/providers/screen_zoom_provider.dart](/lib/providers/screen_zoom_provider.dart) | Dart | 22 | 0 | 6 | 28 | +| [lib/providers/screenshot_provider.dart](/lib/providers/screenshot_provider.dart) | Dart | 13 | 0 | 4 | 17 | +| [lib/providers/strategy_filter_provider.dart](/lib/providers/strategy_filter_provider.dart) | Dart | 66 | 0 | 14 | 80 | +| [lib/providers/strategy_page.dart](/lib/providers/strategy_page.dart) | Dart | 152 | 0 | 15 | 167 | +| [lib/providers/strategy_provider.dart](/lib/providers/strategy_provider.dart) | Dart | 2,101 | 79 | 314 | 2,494 | +| [lib/providers/strategy_settings_provider.dart](/lib/providers/strategy_settings_provider.dart) | Dart | 64 | 0 | 16 | 80 | +| [lib/providers/strategy_settings_provider.g.dart](/lib/providers/strategy_settings_provider.g.dart) | Dart | 12 | 4 | 5 | 21 | +| [lib/providers/team_provider.dart](/lib/providers/team_provider.dart) | Dart | 11 | 0 | 4 | 15 | +| [lib/providers/text_provider.dart](/lib/providers/text_provider.dart) | Dart | 142 | 2 | 47 | 191 | +| [lib/providers/text_widget_height_provider.dart](/lib/providers/text_widget_height_provider.dart) | Dart | 21 | 0 | 7 | 28 | +| [lib/providers/transition_provider.dart](/lib/providers/transition_provider.dart) | Dart | 151 | 0 | 16 | 167 | +| [lib/providers/update_status_provider.dart](/lib/providers/update_status_provider.dart) | Dart | 5 | 0 | 2 | 7 | +| [lib/providers/utility_provider.dart](/lib/providers/utility_provider.dart) | Dart | 139 | 2 | 39 | 180 | +| [lib/screenshot/screenshot_view.dart](/lib/screenshot/screenshot_view.dart) | Dart | 147 | 2 | 12 | 161 | +| [lib/services/clipboard_service.dart](/lib/services/clipboard_service.dart) | Dart | 55 | 4 | 10 | 69 | +| [lib/services/deep_link_registrar.dart](/lib/services/deep_link_registrar.dart) | Dart | 54 | 0 | 11 | 65 | +| [lib/sidebar.dart](/lib/sidebar.dart) | Dart | 206 | 4 | 7 | 217 | +| [lib/strategy_view.dart](/lib/strategy_view.dart) | Dart | 161 | 8 | 13 | 182 | +| [lib/widgets/bg_dot_painter.dart](/lib/widgets/bg_dot_painter.dart) | Dart | 53 | 5 | 15 | 73 | +| [lib/widgets/cloud_library_widgets.dart](/lib/widgets/cloud_library_widgets.dart) | Dart | 355 | 0 | 26 | 381 | +| [lib/widgets/color_picker_button.dart](/lib/widgets/color_picker_button.dart) | Dart | 66 | 1 | 5 | 72 | +| [lib/widgets/current_line_up_painter.dart](/lib/widgets/current_line_up_painter.dart) | Dart | 87 | 2 | 12 | 101 | +| [lib/widgets/current_path_bar.dart](/lib/widgets/current_path_bar.dart) | Dart | 84 | 4 | 11 | 99 | +| [lib/widgets/cursor_circle.dart](/lib/widgets/cursor_circle.dart) | Dart | 68 | 2 | 10 | 80 | +| [lib/widgets/custom_border_container.dart](/lib/widgets/custom_border_container.dart) | Dart | 66 | 2 | 5 | 73 | +| [lib/widgets/custom_button.dart](/lib/widgets/custom_button.dart) | Dart | 117 | 2 | 9 | 128 | +| [lib/widgets/custom_expansion_tile.dart](/lib/widgets/custom_expansion_tile.dart) | Dart | 167 | 23 | 35 | 225 | +| [lib/widgets/custom_folder_painter.dart](/lib/widgets/custom_folder_painter.dart) | Dart | 68 | 24 | 16 | 108 | +| [lib/widgets/custom_menu_builder.dart](/lib/widgets/custom_menu_builder.dart) | Dart | 0 | 0 | 1 | 1 | +| [lib/widgets/custom_search_field.dart](/lib/widgets/custom_search_field.dart) | Dart | 167 | 21 | 17 | 205 | +| [lib/widgets/custom_segmented_tabs.dart](/lib/widgets/custom_segmented_tabs.dart) | Dart | 267 | 13 | 39 | 319 | +| [lib/widgets/custom_text_field.dart](/lib/widgets/custom_text_field.dart) | Dart | 47 | 0 | 3 | 50 | +| [lib/widgets/delete_area.dart](/lib/widgets/delete_area.dart) | Dart | 100 | 1 | 4 | 105 | +| [lib/widgets/delete_capture.dart](/lib/widgets/delete_capture.dart) | Dart | 61 | 0 | 3 | 64 | +| [lib/widgets/demo_dialog.dart](/lib/widgets/demo_dialog.dart) | Dart | 39 | 0 | 3 | 42 | +| [lib/widgets/demo_tag.dart](/lib/widgets/demo_tag.dart) | Dart | 64 | 0 | 6 | 70 | +| [lib/widgets/dialogs/auth/auth_dialog.dart](/lib/widgets/dialogs/auth/auth_dialog.dart) | Dart | 189 | 0 | 20 | 209 | +| [lib/widgets/dialogs/confirm_alert_dialog.dart](/lib/widgets/dialogs/confirm_alert_dialog.dart) | Dart | 70 | 1 | 6 | 77 | +| [lib/widgets/dialogs/create_lineup_dialog.dart](/lib/widgets/dialogs/create_lineup_dialog.dart) | Dart | 162 | 12 | 25 | 199 | +| [lib/widgets/dialogs/in_app_debug_dialog.dart](/lib/widgets/dialogs/in_app_debug_dialog.dart) | Dart | 84 | 0 | 4 | 88 | +| [lib/widgets/dialogs/strategy/create_strategy_dialog.dart](/lib/widgets/dialogs/strategy/create_strategy_dialog.dart) | Dart | 83 | 8 | 7 | 98 | +| [lib/widgets/dialogs/strategy/delete_strategy_alert_dialog.dart](/lib/widgets/dialogs/strategy/delete_strategy_alert_dialog.dart) | Dart | 71 | 2 | 5 | 78 | +| [lib/widgets/dialogs/strategy/line_up_media_page.dart](/lib/widgets/dialogs/strategy/line_up_media_page.dart) | Dart | 247 | 5 | 18 | 270 | +| [lib/widgets/dialogs/strategy/rename_strategy_dialog.dart](/lib/widgets/dialogs/strategy/rename_strategy_dialog.dart) | Dart | 87 | 11 | 9 | 107 | +| [lib/widgets/dialogs/upload_image_dialog.dart](/lib/widgets/dialogs/upload_image_dialog.dart) | Dart | 421 | 3 | 33 | 457 | +| [lib/widgets/dialogs/web_view_dialog.dart](/lib/widgets/dialogs/web_view_dialog.dart) | Dart | 29 | 0 | 3 | 32 | +| [lib/widgets/dot_painter.dart](/lib/widgets/dot_painter.dart) | Dart | 52 | 49 | 22 | 123 | +| [lib/widgets/draggable_widgets/ability/ability_widget.dart](/lib/widgets/draggable_widgets/ability/ability_widget.dart) | Dart | 71 | 4 | 7 | 82 | +| [lib/widgets/draggable_widgets/ability/center_square_widget.dart](/lib/widgets/draggable_widgets/ability/center_square_widget.dart) | Dart | 67 | 0 | 3 | 70 | +| [lib/widgets/draggable_widgets/ability/custom_circle_widget.dart](/lib/widgets/draggable_widgets/ability/custom_circle_widget.dart) | Dart | 115 | 10 | 13 | 138 | +| [lib/widgets/draggable_widgets/ability/custom_square_widget.dart](/lib/widgets/draggable_widgets/ability/custom_square_widget.dart) | Dart | 113 | 13 | 8 | 134 | +| [lib/widgets/draggable_widgets/ability/placed_ability_widget.dart](/lib/widgets/draggable_widgets/ability/placed_ability_widget.dart) | Dart | 281 | 15 | 33 | 329 | +| [lib/widgets/draggable_widgets/ability/resizable_square_widget.dart](/lib/widgets/draggable_widgets/ability/resizable_square_widget.dart) | Dart | 103 | 1 | 11 | 115 | +| [lib/widgets/draggable_widgets/ability/rotatable_image_widget.dart](/lib/widgets/draggable_widgets/ability/rotatable_image_widget.dart) | Dart | 48 | 0 | 4 | 52 | +| [lib/widgets/draggable_widgets/ability/rotatable_widget.dart](/lib/widgets/draggable_widgets/ability/rotatable_widget.dart) | Dart | 91 | 33 | 10 | 134 | +| [lib/widgets/draggable_widgets/agents/agent_feedback_widget.dart](/lib/widgets/draggable_widgets/agents/agent_feedback_widget.dart) | Dart | 37 | 0 | 2 | 39 | +| [lib/widgets/draggable_widgets/agents/agent_icon_widget.dart](/lib/widgets/draggable_widgets/agents/agent_icon_widget.dart) | Dart | 41 | 0 | 5 | 46 | +| [lib/widgets/draggable_widgets/agents/agent_widget.dart](/lib/widgets/draggable_widgets/agents/agent_widget.dart) | Dart | 191 | 11 | 29 | 231 | +| [lib/widgets/draggable_widgets/image/image_widget.dart](/lib/widgets/draggable_widgets/image/image_widget.dart) | Dart | 259 | 4 | 18 | 281 | +| [lib/widgets/draggable_widgets/image/placed_image_builder.dart](/lib/widgets/draggable_widgets/image/placed_image_builder.dart) | Dart | 176 | 0 | 15 | 191 | +| [lib/widgets/draggable_widgets/image/scalable_widget.dart](/lib/widgets/draggable_widgets/image/scalable_widget.dart) | Dart | 45 | 3 | 5 | 53 | +| [lib/widgets/draggable_widgets/placed_widget_builder.dart](/lib/widgets/draggable_widgets/placed_widget_builder.dart) | Dart | 564 | 10 | 60 | 634 | +| [lib/widgets/draggable_widgets/text/placed_text_builder.dart](/lib/widgets/draggable_widgets/text/placed_text_builder.dart) | Dart | 159 | 0 | 9 | 168 | +| [lib/widgets/draggable_widgets/text/text_scale_controller.dart](/lib/widgets/draggable_widgets/text/text_scale_controller.dart) | Dart | 56 | 0 | 5 | 61 | +| [lib/widgets/draggable_widgets/text/text_widget.dart](/lib/widgets/draggable_widgets/text/text_widget.dart) | Dart | 120 | 5 | 12 | 137 | +| [lib/widgets/draggable_widgets/utilities/custom_circle_utility_widget.dart](/lib/widgets/draggable_widgets/utilities/custom_circle_utility_widget.dart) | Dart | 110 | 0 | 8 | 118 | +| [lib/widgets/draggable_widgets/utilities/custom_rectangle_utility_widget.dart](/lib/widgets/draggable_widgets/utilities/custom_rectangle_utility_widget.dart) | Dart | 118 | 0 | 8 | 126 | +| [lib/widgets/draggable_widgets/utilities/image_utility_widget.dart](/lib/widgets/draggable_widgets/utilities/image_utility_widget.dart) | Dart | 38 | 0 | 4 | 42 | +| [lib/widgets/draggable_widgets/utilities/placed_view_cone_widget.dart](/lib/widgets/draggable_widgets/utilities/placed_view_cone_widget.dart) | Dart | 173 | 14 | 28 | 215 | +| [lib/widgets/draggable_widgets/utilities/utility_widget_builder.dart](/lib/widgets/draggable_widgets/utilities/utility_widget_builder.dart) | Dart | 69 | 1 | 4 | 74 | +| [lib/widgets/draggable_widgets/utilities/view_cone_widget.dart](/lib/widgets/draggable_widgets/utilities/view_cone_widget.dart) | Dart | 148 | 18 | 27 | 193 | +| [lib/widgets/draggable_widgets/zoom_transform.dart](/lib/widgets/draggable_widgets/zoom_transform.dart) | Dart | 18 | 0 | 2 | 20 | +| [lib/widgets/drawing_painter.dart](/lib/widgets/drawing_painter.dart) | Dart | 510 | 25 | 59 | 594 | +| [lib/widgets/folder_content.dart](/lib/widgets/folder_content.dart) | Dart | 415 | 10 | 26 | 451 | +| [lib/widgets/folder_edit_dialog.dart](/lib/widgets/folder_edit_dialog.dart) | Dart | 248 | 5 | 7 | 260 | +| [lib/widgets/folder_navigator.dart](/lib/widgets/folder_navigator.dart) | Dart | 524 | 6 | 47 | 577 | +| [lib/widgets/folder_pill.dart](/lib/widgets/folder_pill.dart) | Dart | 275 | 0 | 13 | 288 | +| [lib/widgets/folder_tile.dart](/lib/widgets/folder_tile.dart) | Dart | 0 | 314 | 16 | 330 | +| [lib/widgets/global_shortcuts.dart](/lib/widgets/global_shortcuts.dart) | Dart | 140 | 1 | 15 | 156 | +| [lib/widgets/ica_drop_target.dart](/lib/widgets/ica_drop_target.dart) | Dart | 73 | 1 | 4 | 78 | +| [lib/widgets/image_drop_target.dart](/lib/widgets/image_drop_target.dart) | Dart | 84 | 0 | 5 | 89 | +| [lib/widgets/image_paste_shortcut.dart](/lib/widgets/image_paste_shortcut.dart) | Dart | 0 | 0 | 1 | 1 | +| [lib/widgets/inner_container.dart](/lib/widgets/inner_container.dart) | Dart | 9 | 0 | 2 | 11 | +| [lib/widgets/interaction_state_display.dart](/lib/widgets/interaction_state_display.dart) | Dart | 400 | 2 | 24 | 426 | +| [lib/widgets/line_up_line_painter.dart](/lib/widgets/line_up_line_painter.dart) | Dart | 137 | 4 | 19 | 160 | +| [lib/widgets/line_up_media_carousel.dart](/lib/widgets/line_up_media_carousel.dart) | Dart | 247 | 6 | 21 | 274 | +| [lib/widgets/line_up_placer.dart](/lib/widgets/line_up_placer.dart) | Dart | 235 | 3 | 18 | 256 | +| [lib/widgets/line_up_widget.dart](/lib/widgets/line_up_widget.dart) | Dart | 76 | 0 | 9 | 85 | +| [lib/widgets/map_selector.dart](/lib/widgets/map_selector.dart) | Dart | 204 | 8 | 11 | 223 | +| [lib/widgets/map_theme_settings_section.dart](/lib/widgets/map_theme_settings_section.dart) | Dart | 764 | 5 | 56 | 825 | +| [lib/widgets/map_tile.dart](/lib/widgets/map_tile.dart) | Dart | 86 | 0 | 5 | 91 | +| [lib/widgets/mouse_watch.dart](/lib/widgets/mouse_watch.dart) | Dart | 141 | 6 | 11 | 158 | +| [lib/widgets/numeric_drag_input.dart](/lib/widgets/numeric_drag_input.dart) | Dart | 296 | 11 | 31 | 338 | +| [lib/widgets/page_transition_overlay.dart](/lib/widgets/page_transition_overlay.dart) | Dart | 463 | 3 | 31 | 497 | +| [lib/widgets/pages_bar.dart](/lib/widgets/pages_bar.dart) | Dart | 115 | 0 | 16 | 131 | +| [lib/widgets/save_and_load_button.dart](/lib/widgets/save_and_load_button.dart) | Dart | 191 | 1 | 13 | 205 | +| [lib/widgets/selectable_icon_button.dart](/lib/widgets/selectable_icon_button.dart) | Dart | 64 | 0 | 5 | 69 | +| [lib/widgets/settings_tab.dart](/lib/widgets/settings_tab.dart) | Dart | 237 | 0 | 5 | 242 | +| [lib/widgets/sidebar_widgets/ability_bar.dart](/lib/widgets/sidebar_widgets/ability_bar.dart) | Dart | 124 | 3 | 10 | 137 | +| [lib/widgets/sidebar_widgets/agent_dragable.dart](/lib/widgets/sidebar_widgets/agent_dragable.dart) | Dart | 239 | 2 | 15 | 256 | +| [lib/widgets/sidebar_widgets/agent_filter.dart](/lib/widgets/sidebar_widgets/agent_filter.dart) | Dart | 32 | 0 | 4 | 36 | +| [lib/widgets/sidebar_widgets/bottom_tray.dart](/lib/widgets/sidebar_widgets/bottom_tray.dart) | Dart | 0 | 13 | 4 | 17 | +| [lib/widgets/sidebar_widgets/color_buttons.dart](/lib/widgets/sidebar_widgets/color_buttons.dart) | Dart | 71 | 61 | 10 | 142 | +| [lib/widgets/sidebar_widgets/custom_shape_tools.dart](/lib/widgets/sidebar_widgets/custom_shape_tools.dart) | Dart | 300 | 5 | 16 | 321 | +| [lib/widgets/sidebar_widgets/delete_options.dart](/lib/widgets/sidebar_widgets/delete_options.dart) | Dart | 118 | 0 | 3 | 121 | +| [lib/widgets/sidebar_widgets/drawing_tools.dart](/lib/widgets/sidebar_widgets/drawing_tools.dart) | Dart | 224 | 1 | 5 | 230 | +| [lib/widgets/sidebar_widgets/image_selector.dart](/lib/widgets/sidebar_widgets/image_selector.dart) | Dart | 0 | 0 | 2 | 2 | +| [lib/widgets/sidebar_widgets/role_picker.dart](/lib/widgets/sidebar_widgets/role_picker.dart) | Dart | 61 | 0 | 4 | 65 | +| [lib/widgets/sidebar_widgets/team_picker.dart](/lib/widgets/sidebar_widgets/team_picker.dart) | Dart | 77 | 1 | 9 | 87 | +| [lib/widgets/sidebar_widgets/text_tools.dart](/lib/widgets/sidebar_widgets/text_tools.dart) | Dart | 145 | 0 | 12 | 157 | +| [lib/widgets/sidebar_widgets/tool_grid.dart](/lib/widgets/sidebar_widgets/tool_grid.dart) | Dart | 373 | 8 | 18 | 399 | +| [lib/widgets/sidebar_widgets/vision_cone_tools.dart](/lib/widgets/sidebar_widgets/vision_cone_tools.dart) | Dart | 152 | 0 | 7 | 159 | +| [lib/widgets/strategy_save_icon_button.dart](/lib/widgets/strategy_save_icon_button.dart) | Dart | 117 | 37 | 22 | 176 | +| [lib/widgets/strategy_tile/strategy_tile.dart](/lib/widgets/strategy_tile/strategy_tile.dart) | Dart | 216 | 0 | 20 | 236 | +| [lib/widgets/strategy_tile/strategy_tile_sections.dart](/lib/widgets/strategy_tile/strategy_tile_sections.dart) | Dart | 254 | 0 | 25 | 279 | +| [lib/widgets/youtube_view.dart](/lib/widgets/youtube_view.dart) | Dart | 51 | 30 | 11 | 92 | +| [linux/flutter/generated_plugin_registrant.cc](/linux/flutter/generated_plugin_registrant.cc) | C++ | 31 | 4 | 5 | 40 | +| [linux/flutter/generated_plugin_registrant.h](/linux/flutter/generated_plugin_registrant.h) | C++ | 5 | 5 | 6 | 16 | +| [linux/main.cc](/linux/main.cc) | C++ | 5 | 0 | 2 | 7 | +| [linux/my_application.cc](/linux/my_application.cc) | C++ | 82 | 17 | 26 | 125 | +| [linux/my_application.h](/linux/my_application.h) | C++ | 7 | 7 | 5 | 19 | +| [macos/Flutter/GeneratedPluginRegistrant.swift](/macos/Flutter/GeneratedPluginRegistrant.swift) | Swift | 26 | 3 | 4 | 33 | +| [macos/RunnerTests/RunnerTests.swift](/macos/RunnerTests/RunnerTests.swift) | Swift | 7 | 2 | 4 | 13 | +| [macos/Runner/AppDelegate.swift](/macos/Runner/AppDelegate.swift) | Swift | 11 | 0 | 3 | 14 | +| [macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json](/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json) | JSON | 68 | 0 | 1 | 69 | +| [macos/Runner/Base.lproj/MainMenu.xib](/macos/Runner/Base.lproj/MainMenu.xib) | XML | 343 | 0 | 1 | 344 | +| [macos/Runner/MainFlutterWindow.swift](/macos/Runner/MainFlutterWindow.swift) | Swift | 12 | 0 | 4 | 16 | +| [package.json](/package.json) | JSON | 15 | 0 | 1 | 16 | +| [pubspec.yaml](/pubspec.yaml) | YAML | 98 | 6 | 10 | 114 | +| [scripts/bump_version.ps1](/scripts/bump_version.ps1) | PowerShell | 133 | 31 | 30 | 194 | +| [test/STRATEGY_INTEGRITY_MAINTENANCE.md](/test/STRATEGY_INTEGRITY_MAINTENANCE.md) | Markdown | 39 | 0 | 24 | 63 | +| [test/collab_sync_models_test.dart](/test/collab_sync_models_test.dart) | Dart | 99 | 0 | 15 | 114 | +| [test/strategy_import_version_guard_test.dart](/test/strategy_import_version_guard_test.dart) | Dart | 58 | 0 | 11 | 69 | +| [test/strategy_integrity_test.dart](/test/strategy_integrity_test.dart) | Dart | 367 | 8 | 49 | 424 | +| [test/update_checker_test.dart](/test/update_checker_test.dart) | Dart | 130 | 0 | 22 | 152 | +| [tool/_probe.dart](/tool/_probe.dart) | Dart | 33 | 0 | 2 | 35 | +| [tsconfig.json](/tsconfig.json) | JSON with Comments | 22 | 4 | 4 | 30 | +| [web/index.html](/web/index.html) | HTML | 19 | 15 | 5 | 39 | +| [web/manifest.json](/web/manifest.json) | JSON | 35 | 0 | 1 | 36 | +| [windows/flutter/generated_plugin_registrant.cc](/windows/flutter/generated_plugin_registrant.cc) | C++ | 27 | 4 | 5 | 36 | +| [windows/flutter/generated_plugin_registrant.h](/windows/flutter/generated_plugin_registrant.h) | C++ | 5 | 5 | 6 | 16 | +| [windows/runner/flutter_window.cpp](/windows/runner/flutter_window.cpp) | C++ | 109 | 8 | 25 | 142 | +| [windows/runner/flutter_window.h](/windows/runner/flutter_window.h) | C++ | 25 | 5 | 10 | 40 | +| [windows/runner/main.cpp](/windows/runner/main.cpp) | C++ | 90 | 12 | 23 | 125 | +| [windows/runner/resource.h](/windows/runner/resource.h) | C++ | 9 | 6 | 2 | 17 | +| [windows/runner/utils.cpp](/windows/runner/utils.cpp) | C++ | 54 | 2 | 10 | 66 | +| [windows/runner/utils.h](/windows/runner/utils.h) | C++ | 8 | 6 | 6 | 20 | +| [windows/runner/win32_window.cpp](/windows/runner/win32_window.cpp) | C++ | 199 | 20 | 53 | 272 | +| [windows/runner/win32_window.h](/windows/runner/win32_window.h) | C++ | 48 | 31 | 24 | 103 | + +[Summary](results.md) / Details / [Diff Summary](diff.md) / [Diff Details](diff-details.md) \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/diff-details.md b/.VSCodeCounter/2026-03-20_03-03-11/diff-details.md new file mode 100644 index 00000000..93056328 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/diff-details.md @@ -0,0 +1,15 @@ +# Diff Details + +Date : 2026-03-20 03:03:11 + +Directory e:\\Projects\\icarus + +Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines + +[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details + +## Files +| filename | language | code | comment | blank | total | +| :--- | :--- | ---: | ---: | ---: | ---: | + +[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/diff.csv b/.VSCodeCounter/2026-03-20_03-03-11/diff.csv new file mode 100644 index 00000000..b7d8d759 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/diff.csv @@ -0,0 +1,2 @@ +"filename", "language", "", "comment", "blank", "total" +"Total", "-", , 0, 0, 0 \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/diff.md b/.VSCodeCounter/2026-03-20_03-03-11/diff.md new file mode 100644 index 00000000..b3e5db66 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/diff.md @@ -0,0 +1,19 @@ +# Diff Summary + +Date : 2026-03-20 03:03:11 + +Directory e:\\Projects\\icarus + +Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines + +[Summary](results.md) / [Details](details.md) / Diff Summary / [Diff Details](diff-details.md) + +## Languages +| language | files | code | comment | blank | total | +| :--- | ---: | ---: | ---: | ---: | ---: | + +## Directories +| path | files | code | comment | blank | total | +| :--- | ---: | ---: | ---: | ---: | ---: | + +[Summary](results.md) / [Details](details.md) / Diff Summary / [Diff Details](diff-details.md) \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/diff.txt b/.VSCodeCounter/2026-03-20_03-03-11/diff.txt new file mode 100644 index 00000000..f1b709b8 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/diff.txt @@ -0,0 +1,22 @@ +Date : 2026-03-20 03:03:11 +Directory : e:\Projects\icarus +Total : 0 files, 0 codes, 0 comments, 0 blanks, all 0 lines + +Languages ++----------+------------+------------+------------+------------+------------+ +| language | files | code | comment | blank | total | ++----------+------------+------------+------------+------------+------------+ ++----------+------------+------------+------------+------------+------------+ + +Directories ++------+------------+------------+------------+------------+------------+ +| path | files | code | comment | blank | total | ++------+------------+------------+------------+------------+------------+ ++------+------------+------------+------------+------------+------------+ + +Files ++----------+----------+------------+------------+------------+------------+ +| filename | language | code | comment | blank | total | ++----------+----------+------------+------------+------------+------------+ +| Total | | 0 | 0 | 0 | 0 | ++----------+----------+------------+------------+------------+------------+ \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/results.csv b/.VSCodeCounter/2026-03-20_03-03-11/results.csv new file mode 100644 index 00000000..7a178a5a --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/results.csv @@ -0,0 +1,349 @@ +"filename", "language", "Markdown", "Dart", "JSON with Comments", "C++", "JSON", "HTML", "XML", "PowerShell", "YAML", "Swift", "Groovy", "Properties", "TypeScript", "JavaScript", "comment", "blank", "total" +"e:\Projects\icarus\.cursor\rules\code-gen-rules.mdc", "Markdown", 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 14 +"e:\Projects\icarus\.cursor\rules\use-bun-instead-of-node-vite-npm-pnpm.mdc", "Markdown", 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 112 +"e:\Projects\icarus\.cursor\skills\frontend-design\SKILL.md", "Markdown", 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 43 +"e:\Projects\icarus\.zed\debug.json", "JSON", 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 10 +"e:\Projects\icarus\.zed\tasks.json", "JSON with Comments", 0, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 147, 4, 202 +"e:\Projects\icarus\AGENTS.md", "Markdown", 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 22 +"e:\Projects\icarus\LICENSE.md", "Markdown", 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 15 +"e:\Projects\icarus\README.md", "Markdown", 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 56 +"e:\Projects\icarus\analysis_options.yaml", "YAML", 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 22, 4, 32 +"e:\Projects\icarus\android\app\build.gradle", "Groovy", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 6, 9, 59 +"e:\Projects\icarus\android\app\src\debug\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 1, 8 +"e:\Projects\icarus\android\app\src\main\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 11, 1, 46 +"e:\Projects\icarus\android\app\src\main\res\drawable-v21\launch_background.xml", "XML", 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 7, 2, 13 +"e:\Projects\icarus\android\app\src\main\res\drawable\launch_background.xml", "XML", 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 7, 2, 13 +"e:\Projects\icarus\android\app\src\main\res\values-night\styles.xml", "XML", 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 9, 1, 19 +"e:\Projects\icarus\android\app\src\main\res\values\styles.xml", "XML", 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 9, 1, 19 +"e:\Projects\icarus\android\app\src\profile\AndroidManifest.xml", "XML", 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 1, 8 +"e:\Projects\icarus\android\build.gradle", "Groovy", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 3, 19 +"e:\Projects\icarus\android\gradle.properties", "Properties", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 4 +"e:\Projects\icarus\android\gradle\wrapper\gradle-wrapper.properties", "Properties", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 6 +"e:\Projects\icarus\android\settings.gradle", "Groovy", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 5, 26 +"e:\Projects\icarus\assets\folder_tile.svg", "XML", 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5 +"e:\Projects\icarus\assets\fonts\config.json", "JSON", 0, 0, 0, 0, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122 +"e:\Projects\icarus\assets\maps\abyss_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 0, 0, 0, 0, 0, 1, 66 +"e:\Projects\icarus\assets\maps\abyss_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 0, 0, 0, 0, 0, 1, 66 +"e:\Projects\icarus\assets\maps\abyss_map.svg", "XML", 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 1, 23 +"e:\Projects\icarus\assets\maps\abyss_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 1, 23 +"e:\Projects\icarus\assets\maps\abyss_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 1, 12 +"e:\Projects\icarus\assets\maps\abyss_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\ascent_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 1, 63 +"e:\Projects\icarus\assets\maps\ascent_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 1, 63 +"e:\Projects\icarus\assets\maps\ascent_map.svg", "XML", 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 1, 21 +"e:\Projects\icarus\assets\maps\ascent_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 1, 21 +"e:\Projects\icarus\assets\maps\ascent_map_spawn_wall.svg", "XML", 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13 +"e:\Projects\icarus\assets\maps\ascent_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13 +"e:\Projects\icarus\assets\maps\ascent_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\bind_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69 +"e:\Projects\icarus\assets\maps\bind_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69 +"e:\Projects\icarus\assets\maps\bind_map.svg", "XML", 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 1, 26 +"e:\Projects\icarus\assets\maps\bind_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 1, 26 +"e:\Projects\icarus\assets\maps\bind_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13 +"e:\Projects\icarus\assets\maps\bind_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\breeze_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 0, 0, 0, 0, 0, 1, 66 +"e:\Projects\icarus\assets\maps\breeze_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 0, 0, 0, 0, 0, 1, 66 +"e:\Projects\icarus\assets\maps\breeze_map.svg", "XML", 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 14 +"e:\Projects\icarus\assets\maps\breeze_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 14 +"e:\Projects\icarus\assets\maps\breeze_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13 +"e:\Projects\icarus\assets\maps\breeze_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\corrode_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 59, 0, 0, 0, 0, 0, 0, 0, 0, 1, 60 +"e:\Projects\icarus\assets\maps\corrode_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 59, 0, 0, 0, 0, 0, 0, 0, 0, 1, 60 +"e:\Projects\icarus\assets\maps\corrode_map.svg", "XML", 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16 +"e:\Projects\icarus\assets\maps\corrode_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16 +"e:\Projects\icarus\assets\maps\corrode_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 1, 12 +"e:\Projects\icarus\assets\maps\corrode_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\fracture_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 1, 63 +"e:\Projects\icarus\assets\maps\fracture_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 1, 63 +"e:\Projects\icarus\assets\maps\fracture_map.svg", "XML", 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 1, 28 +"e:\Projects\icarus\assets\maps\fracture_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 1, 28 +"e:\Projects\icarus\assets\maps\fracture_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 14 +"e:\Projects\icarus\assets\maps\fracture_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 11 +"e:\Projects\icarus\assets\maps\haven_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 1, 57 +"e:\Projects\icarus\assets\maps\haven_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 1, 57 +"e:\Projects\icarus\assets\maps\haven_map.svg", "XML", 0, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 1, 18 +"e:\Projects\icarus\assets\maps\haven_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 1, 18 +"e:\Projects\icarus\assets\maps\haven_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 1, 12 +"e:\Projects\icarus\assets\maps\haven_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\icebox_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 1, 72 +"e:\Projects\icarus\assets\maps\icebox_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 1, 72 +"e:\Projects\icarus\assets\maps\icebox_map.svg", "XML", 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 1, 28 +"e:\Projects\icarus\assets\maps\icebox_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 1, 28 +"e:\Projects\icarus\assets\maps\icebox_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 1, 15 +"e:\Projects\icarus\assets\maps\icebox_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\lotus_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 1, 72 +"e:\Projects\icarus\assets\maps\lotus_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 1, 72 +"e:\Projects\icarus\assets\maps\lotus_map.svg", "XML", 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 1, 24 +"e:\Projects\icarus\assets\maps\lotus_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 1, 24 +"e:\Projects\icarus\assets\maps\lotus_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 1, 10 +"e:\Projects\icarus\assets\maps\lotus_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\pearl_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 1, 75 +"e:\Projects\icarus\assets\maps\pearl_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 1, 75 +"e:\Projects\icarus\assets\maps\pearl_map.svg", "XML", 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 1, 33 +"e:\Projects\icarus\assets\maps\pearl_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 1, 33 +"e:\Projects\icarus\assets\maps\pearl_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 11 +"e:\Projects\icarus\assets\maps\pearl_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\split_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69 +"e:\Projects\icarus\assets\maps\split_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69 +"e:\Projects\icarus\assets\maps\split_map.svg", "XML", 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 1, 32 +"e:\Projects\icarus\assets\maps\split_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 1, 32 +"e:\Projects\icarus\assets\maps\split_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 1, 12 +"e:\Projects\icarus\assets\maps\split_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\maps\sunsent_map.svg", "XML", 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 1, 27 +"e:\Projects\icarus\assets\maps\sunsent_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 1, 27 +"e:\Projects\icarus\assets\maps\sunset_call_outs.svg", "XML", 0, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 1, 48 +"e:\Projects\icarus\assets\maps\sunset_call_outs_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 1, 48 +"e:\Projects\icarus\assets\maps\sunset_map.svg", "XML", 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 1, 31 +"e:\Projects\icarus\assets\maps\sunset_map_defense.svg", "XML", 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 1, 31 +"e:\Projects\icarus\assets\maps\sunset_spawn_walls.svg", "XML", 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13 +"e:\Projects\icarus\assets\maps\sunset_ult_orbs.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\assets\spike.svg", "XML", 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7 +"e:\Projects\icarus\build_script.dart", "Dart", 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 14, 53 +"e:\Projects\icarus\bun.lock", "JSON with Comments", 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 90 +"e:\Projects\icarus\convex\_generated\api.d.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 25, 7, 76 +"e:\Projects\icarus\convex\_generated\api.js", "JavaScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 17, 3, 24 +"e:\Projects\icarus\convex\_generated\dataModel.d.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 39, 6, 61 +"e:\Projects\icarus\convex\_generated\server.d.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 106, 14, 144 +"e:\Projects\icarus\convex\_generated\server.js", "JavaScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 69, 9, 94 +"e:\Projects\icarus\convex\auth.config.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 2, 14 +"e:\Projects\icarus\convex\elements.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 5, 41 +"e:\Projects\icarus\convex\folders.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 152, 0, 0, 26, 178 +"e:\Projects\icarus\convex\health.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 1, 1, 9 +"e:\Projects\icarus\convex\images.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 0, 0, 17, 142 +"e:\Projects\icarus\convex\invites.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 167, 0, 0, 26, 193 +"e:\Projects\icarus\convex\lib\auth.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 15, 75 +"e:\Projects\icarus\convex\lib\entities.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 0, 0, 18, 92 +"e:\Projects\icarus\convex\lib\errors.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 2, 12 +"e:\Projects\icarus\convex\lib\opTypes.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 4, 29 +"e:\Projects\icarus\convex\lineups.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 0, 0, 5, 40 +"e:\Projects\icarus\convex\ops.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 475, 0, 1, 29, 505 +"e:\Projects\icarus\convex\pages.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 222, 0, 0, 36, 258 +"e:\Projects\icarus\convex\schema.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135, 0, 1, 4, 140 +"e:\Projects\icarus\convex\strategies.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 0, 0, 41, 289 +"e:\Projects\icarus\convex\users.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 0, 0, 10, 68 +"e:\Projects\icarus\devtools_options.yaml", "YAML", 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4 +"e:\Projects\icarus\docs\version.json", "JSON", 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11 +"e:\Projects\icarus\docs\windows_store_update_testing.md", "Markdown", 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 35 +"e:\Projects\icarus\flutter_convex_overview.md", "Markdown", 379, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 114, 493 +"e:\Projects\icarus\index.ts", "TypeScript", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 +"e:\Projects\icarus\ios\RunnerTests\RunnerTests.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 2, 4, 13 +"e:\Projects\icarus\ios\Runner\AppDelegate.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 2, 14 +"e:\Projects\icarus\ios\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json", "JSON", 0, 0, 0, 0, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 123 +"e:\Projects\icarus\ios\Runner\Assets.xcassets\LaunchImage.imageset\Contents.json", "JSON", 0, 0, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 24 +"e:\Projects\icarus\ios\Runner\Assets.xcassets\LaunchImage.imageset\README.md", "Markdown", 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5 +"e:\Projects\icarus\ios\Runner\Base.lproj\LaunchScreen.storyboard", "XML", 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 1, 1, 38 +"e:\Projects\icarus\ios\Runner\Base.lproj\Main.storyboard", "XML", 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 1, 1, 27 +"e:\Projects\icarus\ios\Runner\Runner-Bridging-Header.h", "C++", 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2 +"e:\Projects\icarus\lib\collab\collab_models.dart", "Dart", 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 369 +"e:\Projects\icarus\lib\collab\convex_payload.dart", "Dart", 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 36 +"e:\Projects\icarus\lib\collab\convex_strategy_repository.dart", "Dart", 0, 223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 253 +"e:\Projects\icarus\lib\const\abilities.dart", "Dart", 0, 371, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 43, 417 +"e:\Projects\icarus\lib\const\agents.dart", "Dart", 0, 787, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 103, 917 +"e:\Projects\icarus\lib\const\app_navigator.dart", "Dart", 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6 +"e:\Projects\icarus\lib\const\bounding_box.dart", "Dart", 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 35 +"e:\Projects\icarus\lib\const\bounding_box.g.dart", "Dart", 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 21 +"e:\Projects\icarus\lib\const\color_option.dart", "Dart", 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 9 +"e:\Projects\icarus\lib\const\coordinate_system.dart", "Dart", 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 22, 106 +"e:\Projects\icarus\lib\const\custom_icons.dart", "Dart", 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 26 +"e:\Projects\icarus\lib\const\default_placement.dart", "Dart", 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 31 +"e:\Projects\icarus\lib\const\drawing_element.dart", "Dart", 0, 235, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 47, 288 +"e:\Projects\icarus\lib\const\drawing_element.g.dart", "Dart", 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 50 +"e:\Projects\icarus\lib\const\hive_boxes.dart", "Dart", 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 8 +"e:\Projects\icarus\lib\const\image_scale_policy.dart", "Dart", 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 10 +"e:\Projects\icarus\lib\const\json_converters.dart", "Dart", 0, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 24, 157 +"e:\Projects\icarus\lib\const\line_provider.dart", "Dart", 0, 280, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 54, 347 +"e:\Projects\icarus\lib\const\line_provider.g.dart", "Dart", 0, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 40 +"e:\Projects\icarus\lib\const\maps.dart", "Dart", 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 65 +"e:\Projects\icarus\lib\const\placed_classes.dart", "Dart", 0, 566, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 119, 704 +"e:\Projects\icarus\lib\const\placed_classes.g.dart", "Dart", 0, 171, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 18, 193 +"e:\Projects\icarus\lib\const\routes.dart", "Dart", 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6 +"e:\Projects\icarus\lib\const\second_instance_args.dart", "Dart", 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 13 +"e:\Projects\icarus\lib\const\settings.dart", "Dart", 0, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 19, 195 +"e:\Projects\icarus\lib\const\shortcut_info.dart", "Dart", 0, 85, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 19, 110 +"e:\Projects\icarus\lib\const\transition_data.dart", "Dart", 0, 138, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 25, 169 +"e:\Projects\icarus\lib\const\traversal_speed.dart", "Dart", 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 20 +"e:\Projects\icarus\lib\const\update_checker.dart", "Dart", 0, 249, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 279 +"e:\Projects\icarus\lib\const\utilities.dart", "Dart", 0, 423, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 48, 490 +"e:\Projects\icarus\lib\const\youtube_handler.dart", "Dart", 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 28 +"e:\Projects\icarus\lib\hive\hive_adapters.dart", "Dart", 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 53 +"e:\Projects\icarus\lib\hive\hive_adapters.g.dart", "Dart", 0, 1340, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 138, 1482 +"e:\Projects\icarus\lib\hive\hive_adapters.g.yaml", "YAML", 0, 0, 0, 0, 0, 0, 0, 0, 492, 0, 0, 0, 0, 0, 3, 1, 496 +"e:\Projects\icarus\lib\hive\hive_registrar.g.dart", "Dart", 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 74 +"e:\Projects\icarus\lib\home_view.dart", "Dart", 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 17 +"e:\Projects\icarus\lib\interactive_map.dart", "Dart", 0, 343, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 18, 366 +"e:\Projects\icarus\lib\main.dart", "Dart", 0, 272, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 46, 328 +"e:\Projects\icarus\lib\migrations\ability_scale_migration.dart", "Dart", 0, 269, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 39, 309 +"e:\Projects\icarus\lib\providers\ability_bar_provider.dart", "Dart", 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 17 +"e:\Projects\icarus\lib\providers\ability_provider.dart", "Dart", 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 55, 227 +"e:\Projects\icarus\lib\providers\action_provider.dart", "Dart", 0, 151, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 29, 192 +"e:\Projects\icarus\lib\providers\agent_filter_provider.dart", "Dart", 0, 117, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 134 +"e:\Projects\icarus\lib\providers\agent_provider.dart", "Dart", 0, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 47, 206 +"e:\Projects\icarus\lib\providers\auth_provider.dart", "Dart", 0, 789, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 90, 880 +"e:\Projects\icarus\lib\providers\auto_save_notifier.dart", "Dart", 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 16 +"e:\Projects\icarus\lib\providers\collab\cloud_collab_provider.dart", "Dart", 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 10, 66 +"e:\Projects\icarus\lib\providers\collab\cloud_migration_provider.dart", "Dart", 0, 222, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 248 +"e:\Projects\icarus\lib\providers\collab\remote_library_provider.dart", "Dart", 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 92 +"e:\Projects\icarus\lib\providers\collab\remote_strategy_snapshot_provider.dart", "Dart", 0, 232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 35, 268 +"e:\Projects\icarus\lib\providers\collab\strategy_conflict_provider.dart", "Dart", 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 27 +"e:\Projects\icarus\lib\providers\collab\strategy_op_queue_provider.dart", "Dart", 0, 226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 266 +"e:\Projects\icarus\lib\providers\drawing_provider.dart", "Dart", 0, 501, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 111, 662 +"e:\Projects\icarus\lib\providers\favorite_agents_provider.dart", "Dart", 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 9, 50 +"e:\Projects\icarus\lib\providers\folder_provider.dart", "Dart", 0, 274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 308 +"e:\Projects\icarus\lib\providers\image_provider.dart", "Dart", 0, 374, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 96, 530 +"e:\Projects\icarus\lib\providers\image_widget_size_provider.dart", "Dart", 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 28 +"e:\Projects\icarus\lib\providers\in_app_debug_provider.dart", "Dart", 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 24 +"e:\Projects\icarus\lib\providers\interaction_state_provider.dart", "Dart", 0, 41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 9, 51 +"e:\Projects\icarus\lib\providers\map_provider.dart", "Dart", 0, 85, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 20, 106 +"e:\Projects\icarus\lib\providers\map_theme_provider.dart", "Dart", 0, 421, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 481 +"e:\Projects\icarus\lib\providers\pen_provider.dart", "Dart", 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 176 +"e:\Projects\icarus\lib\providers\placement_center_provider.dart", "Dart", 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 18 +"e:\Projects\icarus\lib\providers\screen_zoom_provider.dart", "Dart", 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 28 +"e:\Projects\icarus\lib\providers\screenshot_provider.dart", "Dart", 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 17 +"e:\Projects\icarus\lib\providers\strategy_filter_provider.dart", "Dart", 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 80 +"e:\Projects\icarus\lib\providers\strategy_page.dart", "Dart", 0, 152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 167 +"e:\Projects\icarus\lib\providers\strategy_provider.dart", "Dart", 0, 2101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 79, 314, 2494 +"e:\Projects\icarus\lib\providers\strategy_settings_provider.dart", "Dart", 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 80 +"e:\Projects\icarus\lib\providers\strategy_settings_provider.g.dart", "Dart", 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 21 +"e:\Projects\icarus\lib\providers\team_provider.dart", "Dart", 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 15 +"e:\Projects\icarus\lib\providers\text_provider.dart", "Dart", 0, 142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 47, 191 +"e:\Projects\icarus\lib\providers\text_widget_height_provider.dart", "Dart", 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 28 +"e:\Projects\icarus\lib\providers\transition_provider.dart", "Dart", 0, 151, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 167 +"e:\Projects\icarus\lib\providers\update_status_provider.dart", "Dart", 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 7 +"e:\Projects\icarus\lib\providers\utility_provider.dart", "Dart", 0, 139, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 39, 180 +"e:\Projects\icarus\lib\screenshot\screenshot_view.dart", "Dart", 0, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 12, 161 +"e:\Projects\icarus\lib\services\clipboard_service.dart", "Dart", 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 10, 69 +"e:\Projects\icarus\lib\services\deep_link_registrar.dart", "Dart", 0, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 65 +"e:\Projects\icarus\lib\sidebar.dart", "Dart", 0, 206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 217 +"e:\Projects\icarus\lib\strategy_view.dart", "Dart", 0, 161, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 13, 182 +"e:\Projects\icarus\lib\widgets\bg_dot_painter.dart", "Dart", 0, 53, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 15, 73 +"e:\Projects\icarus\lib\widgets\cloud_library_widgets.dart", "Dart", 0, 355, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 381 +"e:\Projects\icarus\lib\widgets\color_picker_button.dart", "Dart", 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 72 +"e:\Projects\icarus\lib\widgets\current_line_up_painter.dart", "Dart", 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 12, 101 +"e:\Projects\icarus\lib\widgets\current_path_bar.dart", "Dart", 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 11, 99 +"e:\Projects\icarus\lib\widgets\cursor_circle.dart", "Dart", 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 10, 80 +"e:\Projects\icarus\lib\widgets\custom_border_container.dart", "Dart", 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 73 +"e:\Projects\icarus\lib\widgets\custom_button.dart", "Dart", 0, 117, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 9, 128 +"e:\Projects\icarus\lib\widgets\custom_expansion_tile.dart", "Dart", 0, 167, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 35, 225 +"e:\Projects\icarus\lib\widgets\custom_folder_painter.dart", "Dart", 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 16, 108 +"e:\Projects\icarus\lib\widgets\custom_menu_builder.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 +"e:\Projects\icarus\lib\widgets\custom_search_field.dart", "Dart", 0, 167, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 17, 205 +"e:\Projects\icarus\lib\widgets\custom_segmented_tabs.dart", "Dart", 0, 267, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 39, 319 +"e:\Projects\icarus\lib\widgets\custom_text_field.dart", "Dart", 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 50 +"e:\Projects\icarus\lib\widgets\delete_area.dart", "Dart", 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 105 +"e:\Projects\icarus\lib\widgets\delete_capture.dart", "Dart", 0, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 64 +"e:\Projects\icarus\lib\widgets\demo_dialog.dart", "Dart", 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 42 +"e:\Projects\icarus\lib\widgets\demo_tag.dart", "Dart", 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 70 +"e:\Projects\icarus\lib\widgets\dialogs\auth\auth_dialog.dart", "Dart", 0, 189, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 209 +"e:\Projects\icarus\lib\widgets\dialogs\confirm_alert_dialog.dart", "Dart", 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 77 +"e:\Projects\icarus\lib\widgets\dialogs\create_lineup_dialog.dart", "Dart", 0, 162, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 25, 199 +"e:\Projects\icarus\lib\widgets\dialogs\in_app_debug_dialog.dart", "Dart", 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 88 +"e:\Projects\icarus\lib\widgets\dialogs\strategy\create_strategy_dialog.dart", "Dart", 0, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 7, 98 +"e:\Projects\icarus\lib\widgets\dialogs\strategy\delete_strategy_alert_dialog.dart", "Dart", 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 78 +"e:\Projects\icarus\lib\widgets\dialogs\strategy\line_up_media_page.dart", "Dart", 0, 247, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 18, 270 +"e:\Projects\icarus\lib\widgets\dialogs\strategy\rename_strategy_dialog.dart", "Dart", 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 107 +"e:\Projects\icarus\lib\widgets\dialogs\upload_image_dialog.dart", "Dart", 0, 421, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 33, 457 +"e:\Projects\icarus\lib\widgets\dialogs\web_view_dialog.dart", "Dart", 0, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 32 +"e:\Projects\icarus\lib\widgets\dot_painter.dart", "Dart", 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 22, 123 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\ability_widget.dart", "Dart", 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 82 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\center_square_widget.dart", "Dart", 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 70 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\custom_circle_widget.dart", "Dart", 0, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 13, 138 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\custom_square_widget.dart", "Dart", 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 8, 134 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\placed_ability_widget.dart", "Dart", 0, 281, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 33, 329 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\resizable_square_widget.dart", "Dart", 0, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 11, 115 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\rotatable_image_widget.dart", "Dart", 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 52 +"e:\Projects\icarus\lib\widgets\draggable_widgets\ability\rotatable_widget.dart", "Dart", 0, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 10, 134 +"e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_feedback_widget.dart", "Dart", 0, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 39 +"e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_icon_widget.dart", "Dart", 0, 41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 46 +"e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_widget.dart", "Dart", 0, 191, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 29, 231 +"e:\Projects\icarus\lib\widgets\draggable_widgets\image\image_widget.dart", "Dart", 0, 259, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 18, 281 +"e:\Projects\icarus\lib\widgets\draggable_widgets\image\placed_image_builder.dart", "Dart", 0, 176, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 191 +"e:\Projects\icarus\lib\widgets\draggable_widgets\image\scalable_widget.dart", "Dart", 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 53 +"e:\Projects\icarus\lib\widgets\draggable_widgets\placed_widget_builder.dart", "Dart", 0, 564, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 60, 634 +"e:\Projects\icarus\lib\widgets\draggable_widgets\text\placed_text_builder.dart", "Dart", 0, 159, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 168 +"e:\Projects\icarus\lib\widgets\draggable_widgets\text\text_scale_controller.dart", "Dart", 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 61 +"e:\Projects\icarus\lib\widgets\draggable_widgets\text\text_widget.dart", "Dart", 0, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 12, 137 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\custom_circle_utility_widget.dart", "Dart", 0, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 118 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\custom_rectangle_utility_widget.dart", "Dart", 0, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 126 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\image_utility_widget.dart", "Dart", 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 42 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\placed_view_cone_widget.dart", "Dart", 0, 173, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 28, 215 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\utility_widget_builder.dart", "Dart", 0, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 74 +"e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\view_cone_widget.dart", "Dart", 0, 148, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 27, 193 +"e:\Projects\icarus\lib\widgets\draggable_widgets\zoom_transform.dart", "Dart", 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 20 +"e:\Projects\icarus\lib\widgets\drawing_painter.dart", "Dart", 0, 510, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 59, 594 +"e:\Projects\icarus\lib\widgets\folder_content.dart", "Dart", 0, 415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 26, 451 +"e:\Projects\icarus\lib\widgets\folder_edit_dialog.dart", "Dart", 0, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 260 +"e:\Projects\icarus\lib\widgets\folder_navigator.dart", "Dart", 0, 524, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 47, 577 +"e:\Projects\icarus\lib\widgets\folder_pill.dart", "Dart", 0, 275, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 288 +"e:\Projects\icarus\lib\widgets\folder_tile.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 314, 16, 330 +"e:\Projects\icarus\lib\widgets\global_shortcuts.dart", "Dart", 0, 140, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 15, 156 +"e:\Projects\icarus\lib\widgets\ica_drop_target.dart", "Dart", 0, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 78 +"e:\Projects\icarus\lib\widgets\image_drop_target.dart", "Dart", 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 89 +"e:\Projects\icarus\lib\widgets\image_paste_shortcut.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 +"e:\Projects\icarus\lib\widgets\inner_container.dart", "Dart", 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 11 +"e:\Projects\icarus\lib\widgets\interaction_state_display.dart", "Dart", 0, 400, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 24, 426 +"e:\Projects\icarus\lib\widgets\line_up_line_painter.dart", "Dart", 0, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 19, 160 +"e:\Projects\icarus\lib\widgets\line_up_media_carousel.dart", "Dart", 0, 247, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 21, 274 +"e:\Projects\icarus\lib\widgets\line_up_placer.dart", "Dart", 0, 235, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 18, 256 +"e:\Projects\icarus\lib\widgets\line_up_widget.dart", "Dart", 0, 76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 85 +"e:\Projects\icarus\lib\widgets\map_selector.dart", "Dart", 0, 204, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 11, 223 +"e:\Projects\icarus\lib\widgets\map_theme_settings_section.dart", "Dart", 0, 764, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 56, 825 +"e:\Projects\icarus\lib\widgets\map_tile.dart", "Dart", 0, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 91 +"e:\Projects\icarus\lib\widgets\mouse_watch.dart", "Dart", 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 11, 158 +"e:\Projects\icarus\lib\widgets\numeric_drag_input.dart", "Dart", 0, 296, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 31, 338 +"e:\Projects\icarus\lib\widgets\page_transition_overlay.dart", "Dart", 0, 463, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 31, 497 +"e:\Projects\icarus\lib\widgets\pages_bar.dart", "Dart", 0, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 131 +"e:\Projects\icarus\lib\widgets\save_and_load_button.dart", "Dart", 0, 191, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 13, 205 +"e:\Projects\icarus\lib\widgets\selectable_icon_button.dart", "Dart", 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 69 +"e:\Projects\icarus\lib\widgets\settings_tab.dart", "Dart", 0, 237, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 242 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\ability_bar.dart", "Dart", 0, 124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 10, 137 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\agent_dragable.dart", "Dart", 0, 239, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 15, 256 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\agent_filter.dart", "Dart", 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 36 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\bottom_tray.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 4, 17 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\color_buttons.dart", "Dart", 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 61, 10, 142 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\custom_shape_tools.dart", "Dart", 0, 300, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 16, 321 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\delete_options.dart", "Dart", 0, 118, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 121 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\drawing_tools.dart", "Dart", 0, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 230 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\image_selector.dart", "Dart", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\role_picker.dart", "Dart", 0, 61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 65 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\team_picker.dart", "Dart", 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 9, 87 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\text_tools.dart", "Dart", 0, 145, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 157 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\tool_grid.dart", "Dart", 0, 373, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 18, 399 +"e:\Projects\icarus\lib\widgets\sidebar_widgets\vision_cone_tools.dart", "Dart", 0, 152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 159 +"e:\Projects\icarus\lib\widgets\strategy_save_icon_button.dart", "Dart", 0, 117, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 22, 176 +"e:\Projects\icarus\lib\widgets\strategy_tile\strategy_tile.dart", "Dart", 0, 216, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 236 +"e:\Projects\icarus\lib\widgets\strategy_tile\strategy_tile_sections.dart", "Dart", 0, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 279 +"e:\Projects\icarus\lib\widgets\youtube_view.dart", "Dart", 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 11, 92 +"e:\Projects\icarus\linux\flutter\generated_plugin_registrant.cc", "C++", 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 40 +"e:\Projects\icarus\linux\flutter\generated_plugin_registrant.h", "C++", 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 16 +"e:\Projects\icarus\linux\main.cc", "C++", 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 7 +"e:\Projects\icarus\linux\my_application.cc", "C++", 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 26, 125 +"e:\Projects\icarus\linux\my_application.h", "C++", 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 5, 19 +"e:\Projects\icarus\macos\Flutter\GeneratedPluginRegistrant.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 3, 4, 33 +"e:\Projects\icarus\macos\RunnerTests\RunnerTests.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 2, 4, 13 +"e:\Projects\icarus\macos\Runner\AppDelegate.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 3, 14 +"e:\Projects\icarus\macos\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json", "JSON", 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 69 +"e:\Projects\icarus\macos\Runner\Base.lproj\MainMenu.xib", "XML", 0, 0, 0, 0, 0, 0, 343, 0, 0, 0, 0, 0, 0, 0, 0, 1, 344 +"e:\Projects\icarus\macos\Runner\MainFlutterWindow.swift", "Swift", 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 4, 16 +"e:\Projects\icarus\package.json", "JSON", 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 16 +"e:\Projects\icarus\pubspec.yaml", "YAML", 0, 0, 0, 0, 0, 0, 0, 0, 98, 0, 0, 0, 0, 0, 6, 10, 114 +"e:\Projects\icarus\scripts\bump_version.ps1", "PowerShell", 0, 0, 0, 0, 0, 0, 0, 133, 0, 0, 0, 0, 0, 0, 31, 30, 194 +"e:\Projects\icarus\test\STRATEGY_INTEGRITY_MAINTENANCE.md", "Markdown", 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 63 +"e:\Projects\icarus\test\collab_sync_models_test.dart", "Dart", 0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 114 +"e:\Projects\icarus\test\strategy_import_version_guard_test.dart", "Dart", 0, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 69 +"e:\Projects\icarus\test\strategy_integrity_test.dart", "Dart", 0, 367, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 49, 424 +"e:\Projects\icarus\test\update_checker_test.dart", "Dart", 0, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 152 +"e:\Projects\icarus\tool\_probe.dart", "Dart", 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 35 +"e:\Projects\icarus\tsconfig.json", "JSON with Comments", 0, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 30 +"e:\Projects\icarus\web\index.html", "HTML", 0, 0, 0, 0, 0, 19, 0, 0, 0, 0, 0, 0, 0, 0, 15, 5, 39 +"e:\Projects\icarus\web\manifest.json", "JSON", 0, 0, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 36 +"e:\Projects\icarus\windows\flutter\generated_plugin_registrant.cc", "C++", 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 36 +"e:\Projects\icarus\windows\flutter\generated_plugin_registrant.h", "C++", 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 16 +"e:\Projects\icarus\windows\runner\flutter_window.cpp", "C++", 0, 0, 0, 109, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 25, 142 +"e:\Projects\icarus\windows\runner\flutter_window.h", "C++", 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 40 +"e:\Projects\icarus\windows\runner\main.cpp", "C++", 0, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 23, 125 +"e:\Projects\icarus\windows\runner\resource.h", "C++", 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 17 +"e:\Projects\icarus\windows\runner\utils.cpp", "C++", 0, 0, 0, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 10, 66 +"e:\Projects\icarus\windows\runner\utils.h", "C++", 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 20 +"e:\Projects\icarus\windows\runner\win32_window.cpp", "C++", 0, 0, 0, 199, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 53, 272 +"e:\Projects\icarus\windows\runner\win32_window.h", "C++", 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 24, 103 +"Total", "-", 640, 30383, 128, 705, 405, 19, 2858, 133, 600, 75, 81, 8, 1926, 20, 2032, 4665, 44678 \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/results.json b/.VSCodeCounter/2026-03-20_03-03-11/results.json new file mode 100644 index 00000000..6afe8dcc --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/results.json @@ -0,0 +1 @@ +{"file:///e%3A/Projects/icarus/.cursor/skills/frontend-design/SKILL.md":{"language":"Markdown","code":30,"comment":0,"blank":13},"file:///e%3A/Projects/icarus/build_script.dart":{"language":"Dart","code":34,"comment":5,"blank":14},"file:///e%3A/Projects/icarus/bun.lock":{"language":"JSON with Comments","code":55,"comment":0,"blank":35},"file:///e%3A/Projects/icarus/LICENSE.md":{"language":"Markdown","code":10,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/windows/runner/win32_window.h":{"language":"C++","code":48,"comment":31,"blank":24},"file:///e%3A/Projects/icarus/windows/runner/win32_window.cpp":{"language":"C++","code":199,"comment":20,"blank":53},"file:///e%3A/Projects/icarus/windows/runner/utils.h":{"language":"C++","code":8,"comment":6,"blank":6},"file:///e%3A/Projects/icarus/windows/runner/utils.cpp":{"language":"C++","code":54,"comment":2,"blank":10},"file:///e%3A/Projects/icarus/web/manifest.json":{"language":"JSON","code":35,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/windows/runner/resource.h":{"language":"C++","code":9,"comment":6,"blank":2},"file:///e%3A/Projects/icarus/windows/runner/flutter_window.h":{"language":"C++","code":25,"comment":5,"blank":10},"file:///e%3A/Projects/icarus/windows/runner/main.cpp":{"language":"C++","code":90,"comment":12,"blank":23},"file:///e%3A/Projects/icarus/.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc":{"language":"Markdown","code":87,"comment":0,"blank":25},"file:///e%3A/Projects/icarus/.cursor/rules/code-gen-rules.mdc":{"language":"Markdown","code":10,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/web/index.html":{"language":"HTML","code":19,"comment":15,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/youtube_view.dart":{"language":"Dart","code":51,"comment":30,"blank":11},"file:///e%3A/Projects/icarus/windows/runner/flutter_window.cpp":{"language":"C++","code":109,"comment":8,"blank":25},"file:///e%3A/Projects/icarus/lib/widgets/strategy_save_icon_button.dart":{"language":"Dart","code":117,"comment":37,"blank":22},"file:///e%3A/Projects/icarus/lib/widgets/strategy_tile/strategy_tile.dart":{"language":"Dart","code":216,"comment":0,"blank":20},"file:///e%3A/Projects/icarus/tool/_probe.dart":{"language":"Dart","code":33,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/widgets/strategy_tile/strategy_tile_sections.dart":{"language":"Dart","code":254,"comment":0,"blank":25},"file:///e%3A/Projects/icarus/tsconfig.json":{"language":"JSON with Comments","code":22,"comment":4,"blank":4},"file:///e%3A/Projects/icarus/windows/flutter/generated_plugin_registrant.h":{"language":"C++","code":5,"comment":5,"blank":6},"file:///e%3A/Projects/icarus/windows/flutter/generated_plugin_registrant.cc":{"language":"C++","code":27,"comment":4,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/team_picker.dart":{"language":"Dart","code":77,"comment":1,"blank":9},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/vision_cone_tools.dart":{"language":"Dart","code":152,"comment":0,"blank":7},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/image_selector.dart":{"language":"Dart","code":0,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/tool_grid.dart":{"language":"Dart","code":373,"comment":8,"blank":18},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/text_tools.dart":{"language":"Dart","code":145,"comment":0,"blank":12},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/role_picker.dart":{"language":"Dart","code":61,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/delete_options.dart":{"language":"Dart","code":118,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/bottom_tray.dart":{"language":"Dart","code":0,"comment":13,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/custom_shape_tools.dart":{"language":"Dart","code":300,"comment":5,"blank":16},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/drawing_tools.dart":{"language":"Dart","code":224,"comment":1,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/color_buttons.dart":{"language":"Dart","code":71,"comment":61,"blank":10},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/agent_filter.dart":{"language":"Dart","code":32,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/agent_dragable.dart":{"language":"Dart","code":239,"comment":2,"blank":15},"file:///e%3A/Projects/icarus/lib/widgets/sidebar_widgets/ability_bar.dart":{"language":"Dart","code":124,"comment":3,"blank":10},"file:///e%3A/Projects/icarus/lib/widgets/settings_tab.dart":{"language":"Dart","code":237,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/selectable_icon_button.dart":{"language":"Dart","code":64,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/page_transition_overlay.dart":{"language":"Dart","code":463,"comment":3,"blank":31},"file:///e%3A/Projects/icarus/lib/widgets/numeric_drag_input.dart":{"language":"Dart","code":296,"comment":11,"blank":31},"file:///e%3A/Projects/icarus/lib/widgets/pages_bar.dart":{"language":"Dart","code":115,"comment":0,"blank":16},"file:///e%3A/Projects/icarus/lib/widgets/save_and_load_button.dart":{"language":"Dart","code":191,"comment":1,"blank":13},"file:///e%3A/Projects/icarus/lib/widgets/map_tile.dart":{"language":"Dart","code":86,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/mouse_watch.dart":{"language":"Dart","code":141,"comment":6,"blank":11},"file:///e%3A/Projects/icarus/lib/widgets/map_theme_settings_section.dart":{"language":"Dart","code":764,"comment":5,"blank":56},"file:///e%3A/Projects/icarus/lib/widgets/map_selector.dart":{"language":"Dart","code":204,"comment":8,"blank":11},"file:///e%3A/Projects/icarus/lib/widgets/line_up_widget.dart":{"language":"Dart","code":76,"comment":0,"blank":9},"file:///e%3A/Projects/icarus/lib/widgets/line_up_placer.dart":{"language":"Dart","code":235,"comment":3,"blank":18},"file:///e%3A/Projects/icarus/lib/widgets/line_up_line_painter.dart":{"language":"Dart","code":137,"comment":4,"blank":19},"file:///e%3A/Projects/icarus/lib/widgets/interaction_state_display.dart":{"language":"Dart","code":400,"comment":2,"blank":24},"file:///e%3A/Projects/icarus/lib/widgets/line_up_media_carousel.dart":{"language":"Dart","code":247,"comment":6,"blank":21},"file:///e%3A/Projects/icarus/lib/widgets/image_paste_shortcut.dart":{"language":"Dart","code":0,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/inner_container.dart":{"language":"Dart","code":9,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/widgets/image_drop_target.dart":{"language":"Dart","code":84,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/ica_drop_target.dart":{"language":"Dart","code":73,"comment":1,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/global_shortcuts.dart":{"language":"Dart","code":140,"comment":1,"blank":15},"file:///e%3A/Projects/icarus/lib/widgets/folder_navigator.dart":{"language":"Dart","code":524,"comment":6,"blank":47},"file:///e%3A/Projects/icarus/lib/widgets/folder_pill.dart":{"language":"Dart","code":275,"comment":0,"blank":13},"file:///e%3A/Projects/icarus/lib/widgets/folder_edit_dialog.dart":{"language":"Dart","code":248,"comment":5,"blank":7},"file:///e%3A/Projects/icarus/lib/widgets/folder_tile.dart":{"language":"Dart","code":0,"comment":314,"blank":16},"file:///e%3A/Projects/icarus/lib/widgets/drawing_painter.dart":{"language":"Dart","code":510,"comment":25,"blank":59},"file:///e%3A/Projects/icarus/lib/widgets/folder_content.dart":{"language":"Dart","code":415,"comment":10,"blank":26},"file:///e%3A/Projects/icarus/test/STRATEGY_INTEGRITY_MAINTENANCE.md":{"language":"Markdown","code":39,"comment":0,"blank":24},"file:///e%3A/Projects/icarus/test/update_checker_test.dart":{"language":"Dart","code":130,"comment":0,"blank":22},"file:///e%3A/Projects/icarus/test/strategy_integrity_test.dart":{"language":"Dart","code":367,"comment":8,"blank":49},"file:///e%3A/Projects/icarus/test/strategy_import_version_guard_test.dart":{"language":"Dart","code":58,"comment":0,"blank":11},"file:///e%3A/Projects/icarus/test/collab_sync_models_test.dart":{"language":"Dart","code":99,"comment":0,"blank":15},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/zoom_transform.dart":{"language":"Dart","code":18,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/view_cone_widget.dart":{"language":"Dart","code":148,"comment":18,"blank":27},"file:///e%3A/Projects/icarus/assets/spike.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/utility_widget_builder.dart":{"language":"Dart","code":69,"comment":1,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/placed_view_cone_widget.dart":{"language":"Dart","code":173,"comment":14,"blank":28},"file:///e%3A/Projects/icarus/scripts/bump_version.ps1":{"language":"PowerShell","code":133,"comment":31,"blank":30},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/image_utility_widget.dart":{"language":"Dart","code":38,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/text/text_widget.dart":{"language":"Dart","code":120,"comment":5,"blank":12},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/text/text_scale_controller.dart":{"language":"Dart","code":56,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/custom_rectangle_utility_widget.dart":{"language":"Dart","code":118,"comment":0,"blank":8},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/utilities/custom_circle_utility_widget.dart":{"language":"Dart","code":110,"comment":0,"blank":8},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/text/placed_text_builder.dart":{"language":"Dart","code":159,"comment":0,"blank":9},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/image/scalable_widget.dart":{"language":"Dart","code":45,"comment":3,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/placed_widget_builder.dart":{"language":"Dart","code":564,"comment":10,"blank":60},"file:///e%3A/Projects/icarus/README.md":{"language":"Markdown","code":42,"comment":0,"blank":14},"file:///e%3A/Projects/icarus/package.json":{"language":"JSON","code":15,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/image/placed_image_builder.dart":{"language":"Dart","code":176,"comment":0,"blank":15},"file:///e%3A/Projects/icarus/pubspec.yaml":{"language":"YAML","code":98,"comment":6,"blank":10},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/image/image_widget.dart":{"language":"Dart","code":259,"comment":4,"blank":18},"file:///e%3A/Projects/icarus/assets/maps/sunset_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunset_spawn_walls.svg":{"language":"XML","code":12,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunset_map_defense.svg":{"language":"XML","code":30,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunset_map.svg":{"language":"XML","code":30,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunset_call_outs_defense.svg":{"language":"XML","code":47,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunset_call_outs.svg":{"language":"XML","code":47,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunsent_map_defense.svg":{"language":"XML","code":26,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/sunsent_map.svg":{"language":"XML","code":26,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_map_defense.svg":{"language":"XML","code":31,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_spawn_walls.svg":{"language":"XML","code":11,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_call_outs.svg":{"language":"XML","code":68,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_map.svg":{"language":"XML","code":31,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/split_call_outs_defense.svg":{"language":"XML","code":68,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_spawn_walls.svg":{"language":"XML","code":10,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_map.svg":{"language":"XML","code":32,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_map_defense.svg":{"language":"XML","code":32,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_call_outs_defense.svg":{"language":"XML","code":74,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_spawn_walls.svg":{"language":"XML","code":9,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/pearl_call_outs.svg":{"language":"XML","code":74,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_map_defense.svg":{"language":"XML","code":23,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_map.svg":{"language":"XML","code":23,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_call_outs_defense.svg":{"language":"XML","code":71,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_map.svg":{"language":"XML","code":27,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/lotus_call_outs.svg":{"language":"XML","code":71,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_spawn_walls.svg":{"language":"XML","code":14,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_map_defense.svg":{"language":"XML","code":27,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_call_outs_defense.svg":{"language":"XML","code":71,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/icebox_call_outs.svg":{"language":"XML","code":71,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_spawn_walls.svg":{"language":"XML","code":11,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_map_defense.svg":{"language":"XML","code":17,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_map.svg":{"language":"XML","code":17,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_call_outs_defense.svg":{"language":"XML","code":56,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/haven_call_outs.svg":{"language":"XML","code":56,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_ult_orbs.svg":{"language":"XML","code":10,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_spawn_walls.svg":{"language":"XML","code":13,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_map.svg":{"language":"XML","code":27,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_map_defense.svg":{"language":"XML","code":27,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_call_outs_defense.svg":{"language":"XML","code":62,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_spawn_walls.svg":{"language":"XML","code":11,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/fracture_call_outs.svg":{"language":"XML","code":62,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_map_defense.svg":{"language":"XML","code":15,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_map.svg":{"language":"XML","code":15,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_call_outs.svg":{"language":"XML","code":59,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_map.svg":{"language":"XML","code":13,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_map_defense.svg":{"language":"XML","code":13,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_spawn_walls.svg":{"language":"XML","code":12,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/corrode_call_outs_defense.svg":{"language":"XML","code":59,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_call_outs_defense.svg":{"language":"XML","code":65,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_spawn_walls.svg":{"language":"XML","code":12,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/breeze_call_outs.svg":{"language":"XML","code":65,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_map_defense.svg":{"language":"XML","code":25,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_call_outs_defense.svg":{"language":"XML","code":68,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_map.svg":{"language":"XML","code":25,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_map_spawn_wall.svg":{"language":"XML","code":12,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/bind_call_outs.svg":{"language":"XML","code":68,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_spawn_walls.svg":{"language":"XML","code":12,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_map_defense.svg":{"language":"XML","code":20,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_call_outs_defense.svg":{"language":"XML","code":62,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_call_outs.svg":{"language":"XML","code":62,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/ascent_map.svg":{"language":"XML","code":20,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/abyss_ult_orbs.svg":{"language":"XML","code":6,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/abyss_map_defense.svg":{"language":"XML","code":22,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/abyss_spawn_walls.svg":{"language":"XML","code":11,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/abyss_map.svg":{"language":"XML","code":22,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/assets/maps/abyss_call_outs_defense.svg":{"language":"XML","code":65,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/agents/agent_widget.dart":{"language":"Dart","code":191,"comment":11,"blank":29},"file:///e%3A/Projects/icarus/assets/maps/abyss_call_outs.svg":{"language":"XML","code":65,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/agents/agent_icon_widget.dart":{"language":"Dart","code":41,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/agents/agent_feedback_widget.dart":{"language":"Dart","code":37,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/rotatable_image_widget.dart":{"language":"Dart","code":48,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/rotatable_widget.dart":{"language":"Dart","code":91,"comment":33,"blank":10},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/resizable_square_widget.dart":{"language":"Dart","code":103,"comment":1,"blank":11},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/placed_ability_widget.dart":{"language":"Dart","code":281,"comment":15,"blank":33},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/custom_square_widget.dart":{"language":"Dart","code":113,"comment":13,"blank":8},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/ability_widget.dart":{"language":"Dart","code":71,"comment":4,"blank":7},"file:///e%3A/Projects/icarus/assets/fonts/config.json":{"language":"JSON","code":122,"comment":0,"blank":0},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/custom_circle_widget.dart":{"language":"Dart","code":115,"comment":10,"blank":13},"file:///e%3A/Projects/icarus/lib/widgets/draggable_widgets/ability/center_square_widget.dart":{"language":"Dart","code":67,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/assets/folder_tile.svg":{"language":"XML","code":4,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/dot_painter.dart":{"language":"Dart","code":52,"comment":49,"blank":22},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/web_view_dialog.dart":{"language":"Dart","code":29,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/strategy/rename_strategy_dialog.dart":{"language":"Dart","code":87,"comment":11,"blank":9},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/upload_image_dialog.dart":{"language":"Dart","code":421,"comment":3,"blank":33},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/strategy/line_up_media_page.dart":{"language":"Dart","code":247,"comment":5,"blank":18},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/strategy/create_strategy_dialog.dart":{"language":"Dart","code":83,"comment":8,"blank":7},"file:///e%3A/Projects/icarus/macos/Flutter/GeneratedPluginRegistrant.swift":{"language":"Swift","code":26,"comment":3,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/strategy/delete_strategy_alert_dialog.dart":{"language":"Dart","code":71,"comment":2,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/in_app_debug_dialog.dart":{"language":"Dart","code":84,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/create_lineup_dialog.dart":{"language":"Dart","code":162,"comment":12,"blank":25},"file:///e%3A/Projects/icarus/linux/my_application.h":{"language":"C++","code":7,"comment":7,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/confirm_alert_dialog.dart":{"language":"Dart","code":70,"comment":1,"blank":6},"file:///e%3A/Projects/icarus/linux/main.cc":{"language":"C++","code":5,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/linux/my_application.cc":{"language":"C++","code":82,"comment":17,"blank":26},"file:///e%3A/Projects/icarus/lib/widgets/dialogs/auth/auth_dialog.dart":{"language":"Dart","code":189,"comment":0,"blank":20},"file:///e%3A/Projects/icarus/lib/widgets/demo_tag.dart":{"language":"Dart","code":64,"comment":0,"blank":6},"file:///e%3A/Projects/icarus/lib/widgets/demo_dialog.dart":{"language":"Dart","code":39,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/widgets/delete_capture.dart":{"language":"Dart","code":61,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/widgets/delete_area.dart":{"language":"Dart","code":100,"comment":1,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/custom_text_field.dart":{"language":"Dart","code":47,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/widgets/custom_folder_painter.dart":{"language":"Dart","code":68,"comment":24,"blank":16},"file:///e%3A/Projects/icarus/lib/widgets/custom_menu_builder.dart":{"language":"Dart","code":0,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/widgets/custom_search_field.dart":{"language":"Dart","code":167,"comment":21,"blank":17},"file:///e%3A/Projects/icarus/lib/widgets/custom_expansion_tile.dart":{"language":"Dart","code":167,"comment":23,"blank":35},"file:///e%3A/Projects/icarus/lib/widgets/custom_segmented_tabs.dart":{"language":"Dart","code":267,"comment":13,"blank":39},"file:///e%3A/Projects/icarus/macos/RunnerTests/RunnerTests.swift":{"language":"Swift","code":7,"comment":2,"blank":4},"file:///e%3A/Projects/icarus/lib/widgets/custom_border_container.dart":{"language":"Dart","code":66,"comment":2,"blank":5},"file:///e%3A/Projects/icarus/lib/widgets/cursor_circle.dart":{"language":"Dart","code":68,"comment":2,"blank":10},"file:///e%3A/Projects/icarus/lib/widgets/custom_button.dart":{"language":"Dart","code":117,"comment":2,"blank":9},"file:///e%3A/Projects/icarus/lib/widgets/current_path_bar.dart":{"language":"Dart","code":84,"comment":4,"blank":11},"file:///e%3A/Projects/icarus/lib/widgets/current_line_up_painter.dart":{"language":"Dart","code":87,"comment":2,"blank":12},"file:///e%3A/Projects/icarus/lib/widgets/cloud_library_widgets.dart":{"language":"Dart","code":355,"comment":0,"blank":26},"file:///e%3A/Projects/icarus/lib/widgets/color_picker_button.dart":{"language":"Dart","code":66,"comment":1,"blank":5},"file:///e%3A/Projects/icarus/lib/strategy_view.dart":{"language":"Dart","code":161,"comment":8,"blank":13},"file:///e%3A/Projects/icarus/lib/widgets/bg_dot_painter.dart":{"language":"Dart","code":53,"comment":5,"blank":15},"file:///e%3A/Projects/icarus/lib/services/deep_link_registrar.dart":{"language":"Dart","code":54,"comment":0,"blank":11},"file:///e%3A/Projects/icarus/lib/sidebar.dart":{"language":"Dart","code":206,"comment":4,"blank":7},"file:///e%3A/Projects/icarus/lib/services/clipboard_service.dart":{"language":"Dart","code":55,"comment":4,"blank":10},"file:///e%3A/Projects/icarus/linux/flutter/generated_plugin_registrant.h":{"language":"C++","code":5,"comment":5,"blank":6},"file:///e%3A/Projects/icarus/lib/screenshot/screenshot_view.dart":{"language":"Dart","code":147,"comment":2,"blank":12},"file:///e%3A/Projects/icarus/lib/providers/utility_provider.dart":{"language":"Dart","code":139,"comment":2,"blank":39},"file:///e%3A/Projects/icarus/linux/flutter/generated_plugin_registrant.cc":{"language":"C++","code":31,"comment":4,"blank":5},"file:///e%3A/Projects/icarus/lib/providers/update_status_provider.dart":{"language":"Dart","code":5,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/providers/text_widget_height_provider.dart":{"language":"Dart","code":21,"comment":0,"blank":7},"file:///e%3A/Projects/icarus/lib/providers/text_provider.dart":{"language":"Dart","code":142,"comment":2,"blank":47},"file:///e%3A/Projects/icarus/lib/providers/team_provider.dart":{"language":"Dart","code":11,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/providers/transition_provider.dart":{"language":"Dart","code":151,"comment":0,"blank":16},"file:///e%3A/Projects/icarus/lib/providers/strategy_settings_provider.dart":{"language":"Dart","code":64,"comment":0,"blank":16},"file:///e%3A/Projects/icarus/lib/providers/screen_zoom_provider.dart":{"language":"Dart","code":22,"comment":0,"blank":6},"file:///e%3A/Projects/icarus/lib/providers/strategy_filter_provider.dart":{"language":"Dart","code":66,"comment":0,"blank":14},"file:///e%3A/Projects/icarus/lib/providers/strategy_settings_provider.g.dart":{"language":"Dart","code":12,"comment":4,"blank":5},"file:///e%3A/Projects/icarus/lib/providers/placement_center_provider.dart":{"language":"Dart","code":13,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/providers/screenshot_provider.dart":{"language":"Dart","code":13,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/providers/strategy_provider.dart":{"language":"Dart","code":2101,"comment":79,"blank":314},"file:///e%3A/Projects/icarus/lib/providers/pen_provider.dart":{"language":"Dart","code":156,"comment":0,"blank":20},"file:///e%3A/Projects/icarus/lib/providers/strategy_page.dart":{"language":"Dart","code":152,"comment":0,"blank":15},"file:///e%3A/Projects/icarus/lib/providers/map_theme_provider.dart":{"language":"Dart","code":421,"comment":0,"blank":60},"file:///e%3A/Projects/icarus/lib/providers/in_app_debug_provider.dart":{"language":"Dart","code":18,"comment":0,"blank":6},"file:///e%3A/Projects/icarus/lib/providers/map_provider.dart":{"language":"Dart","code":85,"comment":1,"blank":20},"file:///e%3A/Projects/icarus/lib/providers/image_widget_size_provider.dart":{"language":"Dart","code":21,"comment":0,"blank":7},"file:///e%3A/Projects/icarus/lib/providers/interaction_state_provider.dart":{"language":"Dart","code":41,"comment":1,"blank":9},"file:///e%3A/Projects/icarus/lib/providers/folder_provider.dart":{"language":"Dart","code":274,"comment":0,"blank":34},"file:///e%3A/Projects/icarus/lib/providers/image_provider.dart":{"language":"Dart","code":374,"comment":60,"blank":96},"file:///e%3A/Projects/icarus/lib/providers/drawing_provider.dart":{"language":"Dart","code":501,"comment":50,"blank":111},"file:///e%3A/Projects/icarus/lib/providers/favorite_agents_provider.dart":{"language":"Dart","code":40,"comment":1,"blank":9},"file:///e%3A/Projects/icarus/lib/providers/collab/strategy_op_queue_provider.dart":{"language":"Dart","code":226,"comment":0,"blank":40},"file:///e%3A/Projects/icarus/lib/providers/collab/strategy_conflict_provider.dart":{"language":"Dart","code":21,"comment":0,"blank":6},"file:///e%3A/Projects/icarus/lib/providers/collab/remote_strategy_snapshot_provider.dart":{"language":"Dart","code":232,"comment":1,"blank":35},"file:///e%3A/Projects/icarus/lib/providers/collab/cloud_migration_provider.dart":{"language":"Dart","code":222,"comment":0,"blank":26},"file:///e%3A/Projects/icarus/lib/providers/auto_save_notifier.dart":{"language":"Dart","code":12,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/providers/collab/remote_library_provider.dart":{"language":"Dart","code":82,"comment":0,"blank":10},"file:///e%3A/Projects/icarus/lib/providers/collab/cloud_collab_provider.dart":{"language":"Dart","code":55,"comment":1,"blank":10},"file:///e%3A/Projects/icarus/lib/providers/agent_provider.dart":{"language":"Dart","code":155,"comment":4,"blank":47},"file:///e%3A/Projects/icarus/lib/providers/auth_provider.dart":{"language":"Dart","code":789,"comment":1,"blank":90},"file:///e%3A/Projects/icarus/lib/providers/agent_filter_provider.dart":{"language":"Dart","code":117,"comment":0,"blank":17},"file:///e%3A/Projects/icarus/lib/providers/action_provider.dart":{"language":"Dart","code":151,"comment":12,"blank":29},"file:///e%3A/Projects/icarus/macos/Runner/MainFlutterWindow.swift":{"language":"Swift","code":12,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/providers/ability_bar_provider.dart":{"language":"Dart","code":13,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/providers/ability_provider.dart":{"language":"Dart","code":156,"comment":16,"blank":55},"file:///e%3A/Projects/icarus/lib/interactive_map.dart":{"language":"Dart","code":343,"comment":5,"blank":18},"file:///e%3A/Projects/icarus/lib/home_view.dart":{"language":"Dart","code":13,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/main.dart":{"language":"Dart","code":272,"comment":10,"blank":46},"file:///e%3A/Projects/icarus/lib/migrations/ability_scale_migration.dart":{"language":"Dart","code":269,"comment":1,"blank":39},"file:///e%3A/Projects/icarus/lib/hive/hive_registrar.g.dart":{"language":"Dart","code":67,"comment":3,"blank":4},"file:///e%3A/Projects/icarus/lib/hive/hive_adapters.g.yaml":{"language":"YAML","code":492,"comment":3,"blank":1},"file:///e%3A/Projects/icarus/lib/hive/hive_adapters.g.dart":{"language":"Dart","code":1340,"comment":4,"blank":138},"file:///e%3A/Projects/icarus/macos/Runner/Base.lproj/MainMenu.xib":{"language":"XML","code":343,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/const/youtube_handler.dart":{"language":"Dart","code":24,"comment":1,"blank":3},"file:///e%3A/Projects/icarus/lib/hive/hive_adapters.dart":{"language":"Dart","code":48,"comment":1,"blank":4},"file:///e%3A/Projects/icarus/lib/const/traversal_speed.dart":{"language":"Dart","code":16,"comment":1,"blank":3},"file:///e%3A/Projects/icarus/lib/const/utilities.dart":{"language":"Dart","code":423,"comment":19,"blank":48},"file:///e%3A/Projects/icarus/lib/const/update_checker.dart":{"language":"Dart","code":249,"comment":0,"blank":30},"file:///e%3A/Projects/icarus/lib/const/transition_data.dart":{"language":"Dart","code":138,"comment":6,"blank":25},"file:///e%3A/Projects/icarus/lib/const/routes.dart":{"language":"Dart","code":5,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/const/second_instance_args.dart":{"language":"Dart","code":7,"comment":3,"blank":3},"file:///e%3A/Projects/icarus/lib/const/shortcut_info.dart":{"language":"Dart","code":85,"comment":6,"blank":19},"file:///e%3A/Projects/icarus/lib/const/settings.dart":{"language":"Dart","code":160,"comment":16,"blank":19},"file:///e%3A/Projects/icarus/lib/const/maps.dart":{"language":"Dart","code":60,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/const/placed_classes.dart":{"language":"Dart","code":566,"comment":19,"blank":119},"file:///e%3A/Projects/icarus/lib/const/line_provider.g.dart":{"language":"Dart","code":29,"comment":4,"blank":7},"file:///e%3A/Projects/icarus/lib/const/placed_classes.g.dart":{"language":"Dart","code":171,"comment":4,"blank":18},"file:///e%3A/Projects/icarus/lib/const/image_scale_policy.dart":{"language":"Dart","code":8,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/lib/const/json_converters.dart":{"language":"Dart","code":126,"comment":7,"blank":24},"file:///e%3A/Projects/icarus/lib/const/line_provider.dart":{"language":"Dart","code":280,"comment":13,"blank":54},"file:///e%3A/Projects/icarus/lib/const/hive_boxes.dart":{"language":"Dart","code":7,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/const/custom_icons.dart":{"language":"Dart","code":22,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/const/drawing_element.dart":{"language":"Dart","code":235,"comment":6,"blank":47},"file:///e%3A/Projects/icarus/lib/const/drawing_element.g.dart":{"language":"Dart","code":39,"comment":4,"blank":7},"file:///e%3A/Projects/icarus/lib/const/default_placement.dart":{"language":"Dart","code":27,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/lib/const/color_option.dart":{"language":"Dart","code":6,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/lib/const/coordinate_system.dart":{"language":"Dart","code":77,"comment":7,"blank":22},"file:///e%3A/Projects/icarus/lib/const/app_navigator.dart":{"language":"Dart","code":2,"comment":2,"blank":2},"file:///e%3A/Projects/icarus/lib/const/agents.dart":{"language":"Dart","code":787,"comment":27,"blank":103},"file:///e%3A/Projects/icarus/lib/const/bounding_box.dart":{"language":"Dart","code":26,"comment":0,"blank":9},"file:///e%3A/Projects/icarus/lib/const/bounding_box.g.dart":{"language":"Dart","code":12,"comment":4,"blank":5},"file:///e%3A/Projects/icarus/lib/collab/convex_payload.dart":{"language":"Dart","code":31,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/lib/const/abilities.dart":{"language":"Dart","code":371,"comment":3,"blank":43},"file:///e%3A/Projects/icarus/lib/collab/convex_strategy_repository.dart":{"language":"Dart","code":223,"comment":0,"blank":30},"file:///e%3A/Projects/icarus/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json":{"language":"JSON","code":68,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/lib/collab/collab_models.dart":{"language":"Dart","code":331,"comment":0,"blank":38},"file:///e%3A/Projects/icarus/android/settings.gradle":{"language":"Groovy","code":21,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/android/build.gradle":{"language":"Groovy","code":16,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/macos/Runner/AppDelegate.swift":{"language":"Swift","code":11,"comment":0,"blank":3},"file:///e%3A/Projects/icarus/android/gradle.properties":{"language":"Properties","code":3,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/ios/RunnerTests/RunnerTests.swift":{"language":"Swift","code":7,"comment":2,"blank":4},"file:///e%3A/Projects/icarus/android/app/src/profile/AndroidManifest.xml":{"language":"XML","code":3,"comment":4,"blank":1},"file:///e%3A/Projects/icarus/android/gradle/wrapper/gradle-wrapper.properties":{"language":"Properties","code":5,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/ios/Runner/Runner-Bridging-Header.h":{"language":"C++","code":1,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/ios/Runner/Base.lproj/LaunchScreen.storyboard":{"language":"XML","code":36,"comment":1,"blank":1},"file:///e%3A/Projects/icarus/ios/Runner/Base.lproj/Main.storyboard":{"language":"XML","code":25,"comment":1,"blank":1},"file:///e%3A/Projects/icarus/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json":{"language":"JSON","code":23,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/android/app/src/main/res/values-night/styles.xml":{"language":"XML","code":9,"comment":9,"blank":1},"file:///e%3A/Projects/icarus/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md":{"language":"Markdown","code":3,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/android/app/src/main/res/values/styles.xml":{"language":"XML","code":9,"comment":9,"blank":1},"file:///e%3A/Projects/icarus/index.ts":{"language":"TypeScript","code":1,"comment":0,"blank":0},"file:///e%3A/Projects/icarus/ios/Runner/AppDelegate.swift":{"language":"Swift","code":12,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/flutter_convex_overview.md":{"language":"Markdown","code":379,"comment":0,"blank":114},"file:///e%3A/Projects/icarus/devtools_options.yaml":{"language":"YAML","code":4,"comment":0,"blank":0},"file:///e%3A/Projects/icarus/docs/version.json":{"language":"JSON","code":11,"comment":0,"blank":0},"file:///e%3A/Projects/icarus/docs/windows_store_update_testing.md":{"language":"Markdown","code":25,"comment":0,"blank":10},"file:///e%3A/Projects/icarus/convex/_generated/api.js":{"language":"JavaScript","code":4,"comment":17,"blank":3},"file:///e%3A/Projects/icarus/android/app/src/main/res/drawable-v21/launch_background.xml":{"language":"XML","code":4,"comment":7,"blank":2},"file:///e%3A/Projects/icarus/convex/_generated/server.js":{"language":"JavaScript","code":16,"comment":69,"blank":9},"file:///e%3A/Projects/icarus/convex/_generated/dataModel.d.ts":{"language":"TypeScript","code":16,"comment":39,"blank":6},"file:///e%3A/Projects/icarus/convex/_generated/server.d.ts":{"language":"TypeScript","code":24,"comment":106,"blank":14},"file:///e%3A/Projects/icarus/convex/_generated/api.d.ts":{"language":"TypeScript","code":44,"comment":25,"blank":7},"file:///e%3A/Projects/icarus/convex/users.ts":{"language":"TypeScript","code":58,"comment":0,"blank":10},"file:///e%3A/Projects/icarus/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json":{"language":"JSON","code":122,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/convex/pages.ts":{"language":"TypeScript","code":222,"comment":0,"blank":36},"file:///e%3A/Projects/icarus/convex/schema.ts":{"language":"TypeScript","code":135,"comment":1,"blank":4},"file:///e%3A/Projects/icarus/convex/ops.ts":{"language":"TypeScript","code":475,"comment":1,"blank":29},"file:///e%3A/Projects/icarus/convex/lib/errors.ts":{"language":"TypeScript","code":10,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/convex/lib/opTypes.ts":{"language":"TypeScript","code":25,"comment":0,"blank":4},"file:///e%3A/Projects/icarus/convex/strategies.ts":{"language":"TypeScript","code":248,"comment":0,"blank":41},"file:///e%3A/Projects/icarus/convex/lineups.ts":{"language":"TypeScript","code":35,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/android/app/src/main/res/drawable/launch_background.xml":{"language":"XML","code":4,"comment":7,"blank":2},"file:///e%3A/Projects/icarus/convex/lib/entities.ts":{"language":"TypeScript","code":74,"comment":0,"blank":18},"file:///e%3A/Projects/icarus/convex/lib/auth.ts":{"language":"TypeScript","code":60,"comment":0,"blank":15},"file:///e%3A/Projects/icarus/convex/invites.ts":{"language":"TypeScript","code":167,"comment":0,"blank":26},"file:///e%3A/Projects/icarus/convex/health.ts":{"language":"TypeScript","code":7,"comment":1,"blank":1},"file:///e%3A/Projects/icarus/convex/folders.ts":{"language":"TypeScript","code":152,"comment":0,"blank":26},"file:///e%3A/Projects/icarus/convex/auth.config.ts":{"language":"TypeScript","code":12,"comment":0,"blank":2},"file:///e%3A/Projects/icarus/AGENTS.md":{"language":"Markdown","code":15,"comment":0,"blank":7},"file:///e%3A/Projects/icarus/convex/images.ts":{"language":"TypeScript","code":125,"comment":0,"blank":17},"file:///e%3A/Projects/icarus/convex/elements.ts":{"language":"TypeScript","code":36,"comment":0,"blank":5},"file:///e%3A/Projects/icarus/analysis_options.yaml":{"language":"YAML","code":6,"comment":22,"blank":4},"file:///e%3A/Projects/icarus/.zed/debug.json":{"language":"JSON","code":9,"comment":0,"blank":1},"file:///e%3A/Projects/icarus/android/app/src/debug/AndroidManifest.xml":{"language":"XML","code":3,"comment":4,"blank":1},"file:///e%3A/Projects/icarus/android/app/src/main/AndroidManifest.xml":{"language":"XML","code":34,"comment":11,"blank":1},"file:///e%3A/Projects/icarus/android/app/build.gradle":{"language":"Groovy","code":44,"comment":6,"blank":9},"file:///e%3A/Projects/icarus/.zed/tasks.json":{"language":"JSON with Comments","code":51,"comment":147,"blank":4}} \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/results.md b/.VSCodeCounter/2026-03-20_03-03-11/results.md new file mode 100644 index 00000000..6006e532 --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/results.md @@ -0,0 +1,117 @@ +# Summary + +Date : 2026-03-20 03:03:11 + +Directory e:\\Projects\\icarus + +Total : 347 files, 37981 codes, 2032 comments, 4665 blanks, all 44678 lines + +Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md) + +## Languages +| language | files | code | comment | blank | total | +| :--- | ---: | ---: | ---: | ---: | ---: | +| Dart | 184 | 30,383 | 1,347 | 3,730 | 35,460 | +| XML | 87 | 2,858 | 53 | 89 | 3,000 | +| TypeScript | 20 | 1,926 | 173 | 268 | 2,367 | +| C++ | 16 | 705 | 132 | 209 | 1,046 | +| Markdown | 10 | 640 | 0 | 218 | 858 | +| YAML | 4 | 600 | 31 | 15 | 646 | +| JSON | 8 | 405 | 0 | 6 | 411 | +| PowerShell | 1 | 133 | 31 | 30 | 194 | +| JSON with Comments | 3 | 128 | 151 | 43 | 322 | +| Groovy | 3 | 81 | 6 | 17 | 104 | +| Swift | 6 | 75 | 7 | 21 | 103 | +| JavaScript | 2 | 20 | 86 | 12 | 118 | +| HTML | 1 | 19 | 15 | 5 | 39 | +| Properties | 2 | 8 | 0 | 2 | 10 | + +## Directories +| path | files | code | comment | blank | total | +| :--- | ---: | ---: | ---: | ---: | ---: | +| . | 347 | 37,981 | 2,032 | 4,665 | 44,678 | +| . (Files) | 12 | 681 | 37 | 208 | 926 | +| .cursor | 3 | 127 | 0 | 42 | 169 | +| .cursor\\rules | 2 | 97 | 0 | 29 | 126 | +| .cursor\\skills | 1 | 30 | 0 | 13 | 43 | +| .cursor\\skills\\frontend-design | 1 | 30 | 0 | 13 | 43 | +| .zed | 2 | 60 | 147 | 5 | 212 | +| android | 12 | 155 | 57 | 28 | 240 | +| android (Files) | 3 | 40 | 0 | 9 | 49 | +| android\\app | 8 | 110 | 57 | 18 | 185 | +| android\\app (Files) | 1 | 44 | 6 | 9 | 59 | +| android\\app\\src | 7 | 66 | 51 | 9 | 126 | +| android\\app\\src\\debug | 1 | 3 | 4 | 1 | 8 | +| android\\app\\src\\main | 5 | 60 | 43 | 7 | 110 | +| android\\app\\src\\main (Files) | 1 | 34 | 11 | 1 | 46 | +| android\\app\\src\\main\\res | 4 | 26 | 32 | 6 | 64 | +| android\\app\\src\\main\\res\\drawable | 1 | 4 | 7 | 2 | 13 | +| android\\app\\src\\main\\res\\drawable-v21 | 1 | 4 | 7 | 2 | 13 | +| android\\app\\src\\main\\res\\values | 1 | 9 | 9 | 1 | 19 | +| android\\app\\src\\main\\res\\values-night | 1 | 9 | 9 | 1 | 19 | +| android\\app\\src\\profile | 1 | 3 | 4 | 1 | 8 | +| android\\gradle | 1 | 5 | 0 | 1 | 6 | +| android\\gradle\\wrapper | 1 | 5 | 0 | 1 | 6 | +| assets | 78 | 2,510 | 0 | 77 | 2,587 | +| assets (Files) | 2 | 10 | 0 | 2 | 12 | +| assets\\fonts | 1 | 122 | 0 | 0 | 122 | +| assets\\maps | 75 | 2,378 | 0 | 75 | 2,453 | +| convex | 21 | 1,945 | 259 | 280 | 2,484 | +| convex (Files) | 12 | 1,672 | 3 | 202 | 1,877 | +| convex\\_generated | 5 | 104 | 256 | 39 | 399 | +| convex\\lib | 4 | 169 | 0 | 39 | 208 | +| docs | 2 | 36 | 0 | 10 | 46 | +| ios | 8 | 229 | 4 | 13 | 246 | +| ios\\Runner | 7 | 222 | 2 | 9 | 233 | +| ios\\Runner (Files) | 2 | 13 | 0 | 3 | 16 | +| ios\\RunnerTests | 1 | 7 | 2 | 4 | 13 | +| ios\\Runner\\Assets.xcassets | 3 | 148 | 0 | 4 | 152 | +| ios\\Runner\\Assets.xcassets\\AppIcon.appiconset | 1 | 122 | 0 | 1 | 123 | +| ios\\Runner\\Assets.xcassets\\LaunchImage.imageset | 2 | 26 | 0 | 3 | 29 | +| ios\\Runner\\Base.lproj | 2 | 61 | 2 | 2 | 65 | +| lib | 179 | 30,154 | 1,337 | 3,618 | 35,109 | +| lib (Files) | 5 | 995 | 27 | 88 | 1,110 | +| lib\\collab | 3 | 585 | 0 | 73 | 658 | +| lib\\const | 28 | 3,958 | 152 | 630 | 4,740 | +| lib\\hive | 4 | 1,947 | 11 | 147 | 2,105 | +| lib\\migrations | 1 | 269 | 1 | 39 | 309 | +| lib\\providers | 37 | 7,074 | 235 | 1,239 | 8,548 | +| lib\\providers (Files) | 31 | 6,236 | 233 | 1,112 | 7,581 | +| lib\\providers\\collab | 6 | 838 | 2 | 127 | 967 | +| lib\\screenshot | 1 | 147 | 2 | 12 | 161 | +| lib\\services | 2 | 109 | 4 | 21 | 134 | +| lib\\widgets | 98 | 15,070 | 905 | 1,369 | 17,344 | +| lib\\widgets (Files) | 47 | 8,030 | 627 | 745 | 9,402 | +| lib\\widgets\\dialogs | 10 | 1,443 | 42 | 130 | 1,615 | +| lib\\widgets\\dialogs (Files) | 5 | 766 | 16 | 71 | 853 | +| lib\\widgets\\dialogs\\auth | 1 | 189 | 0 | 20 | 209 | +| lib\\widgets\\dialogs\\strategy | 4 | 488 | 26 | 39 | 553 | +| lib\\widgets\\draggable_widgets | 25 | 3,211 | 142 | 330 | 3,683 | +| lib\\widgets\\draggable_widgets (Files) | 2 | 582 | 10 | 62 | 654 | +| lib\\widgets\\draggable_widgets\\ability | 8 | 889 | 76 | 89 | 1,054 | +| lib\\widgets\\draggable_widgets\\agents | 3 | 269 | 11 | 36 | 316 | +| lib\\widgets\\draggable_widgets\\image | 3 | 480 | 7 | 38 | 525 | +| lib\\widgets\\draggable_widgets\\text | 3 | 335 | 5 | 26 | 366 | +| lib\\widgets\\draggable_widgets\\utilities | 6 | 656 | 33 | 79 | 768 | +| lib\\widgets\\sidebar_widgets | 14 | 1,916 | 94 | 119 | 2,129 | +| lib\\widgets\\strategy_tile | 2 | 470 | 0 | 45 | 515 | +| linux | 5 | 130 | 33 | 44 | 207 | +| linux (Files) | 3 | 94 | 24 | 33 | 151 | +| linux\\flutter | 2 | 36 | 9 | 11 | 56 | +| macos | 6 | 467 | 5 | 17 | 489 | +| macos\\Flutter | 1 | 26 | 3 | 4 | 33 | +| macos\\Runner | 4 | 434 | 0 | 9 | 443 | +| macos\\Runner (Files) | 2 | 23 | 0 | 7 | 30 | +| macos\\RunnerTests | 1 | 7 | 2 | 4 | 13 | +| macos\\Runner\\Assets.xcassets | 1 | 68 | 0 | 1 | 69 | +| macos\\Runner\\Assets.xcassets\\AppIcon.appiconset | 1 | 68 | 0 | 1 | 69 | +| macos\\Runner\\Base.lproj | 1 | 343 | 0 | 1 | 344 | +| scripts | 1 | 133 | 31 | 30 | 194 | +| test | 5 | 693 | 8 | 121 | 822 | +| tool | 1 | 33 | 0 | 2 | 35 | +| web | 2 | 54 | 15 | 6 | 75 | +| windows | 10 | 574 | 99 | 164 | 837 | +| windows\\flutter | 2 | 32 | 9 | 11 | 52 | +| windows\\runner | 8 | 542 | 90 | 153 | 785 | + +Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md) \ No newline at end of file diff --git a/.VSCodeCounter/2026-03-20_03-03-11/results.txt b/.VSCodeCounter/2026-03-20_03-03-11/results.txt new file mode 100644 index 00000000..b95b8f7c --- /dev/null +++ b/.VSCodeCounter/2026-03-20_03-03-11/results.txt @@ -0,0 +1,467 @@ +Date : 2026-03-20 03:03:11 +Directory : e:\Projects\icarus +Total : 347 files, 37981 codes, 2032 comments, 4665 blanks, all 44678 lines + +Languages ++--------------------+------------+------------+------------+------------+------------+ +| language | files | code | comment | blank | total | ++--------------------+------------+------------+------------+------------+------------+ +| Dart | 184 | 30,383 | 1,347 | 3,730 | 35,460 | +| XML | 87 | 2,858 | 53 | 89 | 3,000 | +| TypeScript | 20 | 1,926 | 173 | 268 | 2,367 | +| C++ | 16 | 705 | 132 | 209 | 1,046 | +| Markdown | 10 | 640 | 0 | 218 | 858 | +| YAML | 4 | 600 | 31 | 15 | 646 | +| JSON | 8 | 405 | 0 | 6 | 411 | +| PowerShell | 1 | 133 | 31 | 30 | 194 | +| JSON with Comments | 3 | 128 | 151 | 43 | 322 | +| Groovy | 3 | 81 | 6 | 17 | 104 | +| Swift | 6 | 75 | 7 | 21 | 103 | +| JavaScript | 2 | 20 | 86 | 12 | 118 | +| HTML | 1 | 19 | 15 | 5 | 39 | +| Properties | 2 | 8 | 0 | 2 | 10 | ++--------------------+------------+------------+------------+------------+------------+ + +Directories ++-------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+ +| path | files | code | comment | blank | total | ++-------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+ +| . | 347 | 37,981 | 2,032 | 4,665 | 44,678 | +| . (Files) | 12 | 681 | 37 | 208 | 926 | +| .cursor | 3 | 127 | 0 | 42 | 169 | +| .cursor\rules | 2 | 97 | 0 | 29 | 126 | +| .cursor\skills | 1 | 30 | 0 | 13 | 43 | +| .cursor\skills\frontend-design | 1 | 30 | 0 | 13 | 43 | +| .zed | 2 | 60 | 147 | 5 | 212 | +| android | 12 | 155 | 57 | 28 | 240 | +| android (Files) | 3 | 40 | 0 | 9 | 49 | +| android\app | 8 | 110 | 57 | 18 | 185 | +| android\app (Files) | 1 | 44 | 6 | 9 | 59 | +| android\app\src | 7 | 66 | 51 | 9 | 126 | +| android\app\src\debug | 1 | 3 | 4 | 1 | 8 | +| android\app\src\main | 5 | 60 | 43 | 7 | 110 | +| android\app\src\main (Files) | 1 | 34 | 11 | 1 | 46 | +| android\app\src\main\res | 4 | 26 | 32 | 6 | 64 | +| android\app\src\main\res\drawable | 1 | 4 | 7 | 2 | 13 | +| android\app\src\main\res\drawable-v21 | 1 | 4 | 7 | 2 | 13 | +| android\app\src\main\res\values | 1 | 9 | 9 | 1 | 19 | +| android\app\src\main\res\values-night | 1 | 9 | 9 | 1 | 19 | +| android\app\src\profile | 1 | 3 | 4 | 1 | 8 | +| android\gradle | 1 | 5 | 0 | 1 | 6 | +| android\gradle\wrapper | 1 | 5 | 0 | 1 | 6 | +| assets | 78 | 2,510 | 0 | 77 | 2,587 | +| assets (Files) | 2 | 10 | 0 | 2 | 12 | +| assets\fonts | 1 | 122 | 0 | 0 | 122 | +| assets\maps | 75 | 2,378 | 0 | 75 | 2,453 | +| convex | 21 | 1,945 | 259 | 280 | 2,484 | +| convex (Files) | 12 | 1,672 | 3 | 202 | 1,877 | +| convex\_generated | 5 | 104 | 256 | 39 | 399 | +| convex\lib | 4 | 169 | 0 | 39 | 208 | +| docs | 2 | 36 | 0 | 10 | 46 | +| ios | 8 | 229 | 4 | 13 | 246 | +| ios\Runner | 7 | 222 | 2 | 9 | 233 | +| ios\Runner (Files) | 2 | 13 | 0 | 3 | 16 | +| ios\RunnerTests | 1 | 7 | 2 | 4 | 13 | +| ios\Runner\Assets.xcassets | 3 | 148 | 0 | 4 | 152 | +| ios\Runner\Assets.xcassets\AppIcon.appiconset | 1 | 122 | 0 | 1 | 123 | +| ios\Runner\Assets.xcassets\LaunchImage.imageset | 2 | 26 | 0 | 3 | 29 | +| ios\Runner\Base.lproj | 2 | 61 | 2 | 2 | 65 | +| lib | 179 | 30,154 | 1,337 | 3,618 | 35,109 | +| lib (Files) | 5 | 995 | 27 | 88 | 1,110 | +| lib\collab | 3 | 585 | 0 | 73 | 658 | +| lib\const | 28 | 3,958 | 152 | 630 | 4,740 | +| lib\hive | 4 | 1,947 | 11 | 147 | 2,105 | +| lib\migrations | 1 | 269 | 1 | 39 | 309 | +| lib\providers | 37 | 7,074 | 235 | 1,239 | 8,548 | +| lib\providers (Files) | 31 | 6,236 | 233 | 1,112 | 7,581 | +| lib\providers\collab | 6 | 838 | 2 | 127 | 967 | +| lib\screenshot | 1 | 147 | 2 | 12 | 161 | +| lib\services | 2 | 109 | 4 | 21 | 134 | +| lib\widgets | 98 | 15,070 | 905 | 1,369 | 17,344 | +| lib\widgets (Files) | 47 | 8,030 | 627 | 745 | 9,402 | +| lib\widgets\dialogs | 10 | 1,443 | 42 | 130 | 1,615 | +| lib\widgets\dialogs (Files) | 5 | 766 | 16 | 71 | 853 | +| lib\widgets\dialogs\auth | 1 | 189 | 0 | 20 | 209 | +| lib\widgets\dialogs\strategy | 4 | 488 | 26 | 39 | 553 | +| lib\widgets\draggable_widgets | 25 | 3,211 | 142 | 330 | 3,683 | +| lib\widgets\draggable_widgets (Files) | 2 | 582 | 10 | 62 | 654 | +| lib\widgets\draggable_widgets\ability | 8 | 889 | 76 | 89 | 1,054 | +| lib\widgets\draggable_widgets\agents | 3 | 269 | 11 | 36 | 316 | +| lib\widgets\draggable_widgets\image | 3 | 480 | 7 | 38 | 525 | +| lib\widgets\draggable_widgets\text | 3 | 335 | 5 | 26 | 366 | +| lib\widgets\draggable_widgets\utilities | 6 | 656 | 33 | 79 | 768 | +| lib\widgets\sidebar_widgets | 14 | 1,916 | 94 | 119 | 2,129 | +| lib\widgets\strategy_tile | 2 | 470 | 0 | 45 | 515 | +| linux | 5 | 130 | 33 | 44 | 207 | +| linux (Files) | 3 | 94 | 24 | 33 | 151 | +| linux\flutter | 2 | 36 | 9 | 11 | 56 | +| macos | 6 | 467 | 5 | 17 | 489 | +| macos\Flutter | 1 | 26 | 3 | 4 | 33 | +| macos\Runner | 4 | 434 | 0 | 9 | 443 | +| macos\Runner (Files) | 2 | 23 | 0 | 7 | 30 | +| macos\RunnerTests | 1 | 7 | 2 | 4 | 13 | +| macos\Runner\Assets.xcassets | 1 | 68 | 0 | 1 | 69 | +| macos\Runner\Assets.xcassets\AppIcon.appiconset | 1 | 68 | 0 | 1 | 69 | +| macos\Runner\Base.lproj | 1 | 343 | 0 | 1 | 344 | +| scripts | 1 | 133 | 31 | 30 | 194 | +| test | 5 | 693 | 8 | 121 | 822 | +| tool | 1 | 33 | 0 | 2 | 35 | +| web | 2 | 54 | 15 | 6 | 75 | +| windows | 10 | 574 | 99 | 164 | 837 | +| windows\flutter | 2 | 32 | 9 | 11 | 52 | +| windows\runner | 8 | 542 | 90 | 153 | 785 | ++-------------------------------------------------------------------------------------------------+------------+------------+------------+------------+------------+ + +Files ++-------------------------------------------------------------------------------------------------+--------------------+------------+------------+------------+------------+ +| filename | language | code | comment | blank | total | ++-------------------------------------------------------------------------------------------------+--------------------+------------+------------+------------+------------+ +| e:\Projects\icarus\.cursor\rules\code-gen-rules.mdc | Markdown | 10 | 0 | 4 | 14 | +| e:\Projects\icarus\.cursor\rules\use-bun-instead-of-node-vite-npm-pnpm.mdc | Markdown | 87 | 0 | 25 | 112 | +| e:\Projects\icarus\.cursor\skills\frontend-design\SKILL.md | Markdown | 30 | 0 | 13 | 43 | +| e:\Projects\icarus\.zed\debug.json | JSON | 9 | 0 | 1 | 10 | +| e:\Projects\icarus\.zed\tasks.json | JSON with Comments | 51 | 147 | 4 | 202 | +| e:\Projects\icarus\AGENTS.md | Markdown | 15 | 0 | 7 | 22 | +| e:\Projects\icarus\LICENSE.md | Markdown | 10 | 0 | 5 | 15 | +| e:\Projects\icarus\README.md | Markdown | 42 | 0 | 14 | 56 | +| e:\Projects\icarus\analysis_options.yaml | YAML | 6 | 22 | 4 | 32 | +| e:\Projects\icarus\android\app\build.gradle | Groovy | 44 | 6 | 9 | 59 | +| e:\Projects\icarus\android\app\src\debug\AndroidManifest.xml | XML | 3 | 4 | 1 | 8 | +| e:\Projects\icarus\android\app\src\main\AndroidManifest.xml | XML | 34 | 11 | 1 | 46 | +| e:\Projects\icarus\android\app\src\main\res\drawable-v21\launch_background.xml | XML | 4 | 7 | 2 | 13 | +| e:\Projects\icarus\android\app\src\main\res\drawable\launch_background.xml | XML | 4 | 7 | 2 | 13 | +| e:\Projects\icarus\android\app\src\main\res\values-night\styles.xml | XML | 9 | 9 | 1 | 19 | +| e:\Projects\icarus\android\app\src\main\res\values\styles.xml | XML | 9 | 9 | 1 | 19 | +| e:\Projects\icarus\android\app\src\profile\AndroidManifest.xml | XML | 3 | 4 | 1 | 8 | +| e:\Projects\icarus\android\build.gradle | Groovy | 16 | 0 | 3 | 19 | +| e:\Projects\icarus\android\gradle.properties | Properties | 3 | 0 | 1 | 4 | +| e:\Projects\icarus\android\gradle\wrapper\gradle-wrapper.properties | Properties | 5 | 0 | 1 | 6 | +| e:\Projects\icarus\android\settings.gradle | Groovy | 21 | 0 | 5 | 26 | +| e:\Projects\icarus\assets\folder_tile.svg | XML | 4 | 0 | 1 | 5 | +| e:\Projects\icarus\assets\fonts\config.json | JSON | 122 | 0 | 0 | 122 | +| e:\Projects\icarus\assets\maps\abyss_call_outs.svg | XML | 65 | 0 | 1 | 66 | +| e:\Projects\icarus\assets\maps\abyss_call_outs_defense.svg | XML | 65 | 0 | 1 | 66 | +| e:\Projects\icarus\assets\maps\abyss_map.svg | XML | 22 | 0 | 1 | 23 | +| e:\Projects\icarus\assets\maps\abyss_map_defense.svg | XML | 22 | 0 | 1 | 23 | +| e:\Projects\icarus\assets\maps\abyss_spawn_walls.svg | XML | 11 | 0 | 1 | 12 | +| e:\Projects\icarus\assets\maps\abyss_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\ascent_call_outs.svg | XML | 62 | 0 | 1 | 63 | +| e:\Projects\icarus\assets\maps\ascent_call_outs_defense.svg | XML | 62 | 0 | 1 | 63 | +| e:\Projects\icarus\assets\maps\ascent_map.svg | XML | 20 | 0 | 1 | 21 | +| e:\Projects\icarus\assets\maps\ascent_map_defense.svg | XML | 20 | 0 | 1 | 21 | +| e:\Projects\icarus\assets\maps\ascent_map_spawn_wall.svg | XML | 12 | 0 | 1 | 13 | +| e:\Projects\icarus\assets\maps\ascent_spawn_walls.svg | XML | 12 | 0 | 1 | 13 | +| e:\Projects\icarus\assets\maps\ascent_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\bind_call_outs.svg | XML | 68 | 0 | 1 | 69 | +| e:\Projects\icarus\assets\maps\bind_call_outs_defense.svg | XML | 68 | 0 | 1 | 69 | +| e:\Projects\icarus\assets\maps\bind_map.svg | XML | 25 | 0 | 1 | 26 | +| e:\Projects\icarus\assets\maps\bind_map_defense.svg | XML | 25 | 0 | 1 | 26 | +| e:\Projects\icarus\assets\maps\bind_spawn_walls.svg | XML | 12 | 0 | 1 | 13 | +| e:\Projects\icarus\assets\maps\bind_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\breeze_call_outs.svg | XML | 65 | 0 | 1 | 66 | +| e:\Projects\icarus\assets\maps\breeze_call_outs_defense.svg | XML | 65 | 0 | 1 | 66 | +| e:\Projects\icarus\assets\maps\breeze_map.svg | XML | 13 | 0 | 1 | 14 | +| e:\Projects\icarus\assets\maps\breeze_map_defense.svg | XML | 13 | 0 | 1 | 14 | +| e:\Projects\icarus\assets\maps\breeze_spawn_walls.svg | XML | 12 | 0 | 1 | 13 | +| e:\Projects\icarus\assets\maps\breeze_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\corrode_call_outs.svg | XML | 59 | 0 | 1 | 60 | +| e:\Projects\icarus\assets\maps\corrode_call_outs_defense.svg | XML | 59 | 0 | 1 | 60 | +| e:\Projects\icarus\assets\maps\corrode_map.svg | XML | 15 | 0 | 1 | 16 | +| e:\Projects\icarus\assets\maps\corrode_map_defense.svg | XML | 15 | 0 | 1 | 16 | +| e:\Projects\icarus\assets\maps\corrode_spawn_walls.svg | XML | 11 | 0 | 1 | 12 | +| e:\Projects\icarus\assets\maps\corrode_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\fracture_call_outs.svg | XML | 62 | 0 | 1 | 63 | +| e:\Projects\icarus\assets\maps\fracture_call_outs_defense.svg | XML | 62 | 0 | 1 | 63 | +| e:\Projects\icarus\assets\maps\fracture_map.svg | XML | 27 | 0 | 1 | 28 | +| e:\Projects\icarus\assets\maps\fracture_map_defense.svg | XML | 27 | 0 | 1 | 28 | +| e:\Projects\icarus\assets\maps\fracture_spawn_walls.svg | XML | 13 | 0 | 1 | 14 | +| e:\Projects\icarus\assets\maps\fracture_ult_orbs.svg | XML | 10 | 0 | 1 | 11 | +| e:\Projects\icarus\assets\maps\haven_call_outs.svg | XML | 56 | 0 | 1 | 57 | +| e:\Projects\icarus\assets\maps\haven_call_outs_defense.svg | XML | 56 | 0 | 1 | 57 | +| e:\Projects\icarus\assets\maps\haven_map.svg | XML | 17 | 0 | 1 | 18 | +| e:\Projects\icarus\assets\maps\haven_map_defense.svg | XML | 17 | 0 | 1 | 18 | +| e:\Projects\icarus\assets\maps\haven_spawn_walls.svg | XML | 11 | 0 | 1 | 12 | +| e:\Projects\icarus\assets\maps\haven_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\icebox_call_outs.svg | XML | 71 | 0 | 1 | 72 | +| e:\Projects\icarus\assets\maps\icebox_call_outs_defense.svg | XML | 71 | 0 | 1 | 72 | +| e:\Projects\icarus\assets\maps\icebox_map.svg | XML | 27 | 0 | 1 | 28 | +| e:\Projects\icarus\assets\maps\icebox_map_defense.svg | XML | 27 | 0 | 1 | 28 | +| e:\Projects\icarus\assets\maps\icebox_spawn_walls.svg | XML | 14 | 0 | 1 | 15 | +| e:\Projects\icarus\assets\maps\icebox_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\lotus_call_outs.svg | XML | 71 | 0 | 1 | 72 | +| e:\Projects\icarus\assets\maps\lotus_call_outs_defense.svg | XML | 71 | 0 | 1 | 72 | +| e:\Projects\icarus\assets\maps\lotus_map.svg | XML | 23 | 0 | 1 | 24 | +| e:\Projects\icarus\assets\maps\lotus_map_defense.svg | XML | 23 | 0 | 1 | 24 | +| e:\Projects\icarus\assets\maps\lotus_spawn_walls.svg | XML | 9 | 0 | 1 | 10 | +| e:\Projects\icarus\assets\maps\lotus_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\pearl_call_outs.svg | XML | 74 | 0 | 1 | 75 | +| e:\Projects\icarus\assets\maps\pearl_call_outs_defense.svg | XML | 74 | 0 | 1 | 75 | +| e:\Projects\icarus\assets\maps\pearl_map.svg | XML | 32 | 0 | 1 | 33 | +| e:\Projects\icarus\assets\maps\pearl_map_defense.svg | XML | 32 | 0 | 1 | 33 | +| e:\Projects\icarus\assets\maps\pearl_spawn_walls.svg | XML | 10 | 0 | 1 | 11 | +| e:\Projects\icarus\assets\maps\pearl_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\split_call_outs.svg | XML | 68 | 0 | 1 | 69 | +| e:\Projects\icarus\assets\maps\split_call_outs_defense.svg | XML | 68 | 0 | 1 | 69 | +| e:\Projects\icarus\assets\maps\split_map.svg | XML | 31 | 0 | 1 | 32 | +| e:\Projects\icarus\assets\maps\split_map_defense.svg | XML | 31 | 0 | 1 | 32 | +| e:\Projects\icarus\assets\maps\split_spawn_walls.svg | XML | 11 | 0 | 1 | 12 | +| e:\Projects\icarus\assets\maps\split_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\maps\sunsent_map.svg | XML | 26 | 0 | 1 | 27 | +| e:\Projects\icarus\assets\maps\sunsent_map_defense.svg | XML | 26 | 0 | 1 | 27 | +| e:\Projects\icarus\assets\maps\sunset_call_outs.svg | XML | 47 | 0 | 1 | 48 | +| e:\Projects\icarus\assets\maps\sunset_call_outs_defense.svg | XML | 47 | 0 | 1 | 48 | +| e:\Projects\icarus\assets\maps\sunset_map.svg | XML | 30 | 0 | 1 | 31 | +| e:\Projects\icarus\assets\maps\sunset_map_defense.svg | XML | 30 | 0 | 1 | 31 | +| e:\Projects\icarus\assets\maps\sunset_spawn_walls.svg | XML | 12 | 0 | 1 | 13 | +| e:\Projects\icarus\assets\maps\sunset_ult_orbs.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\assets\spike.svg | XML | 6 | 0 | 1 | 7 | +| e:\Projects\icarus\build_script.dart | Dart | 34 | 5 | 14 | 53 | +| e:\Projects\icarus\bun.lock | JSON with Comments | 55 | 0 | 35 | 90 | +| e:\Projects\icarus\convex\_generated\api.d.ts | TypeScript | 44 | 25 | 7 | 76 | +| e:\Projects\icarus\convex\_generated\api.js | JavaScript | 4 | 17 | 3 | 24 | +| e:\Projects\icarus\convex\_generated\dataModel.d.ts | TypeScript | 16 | 39 | 6 | 61 | +| e:\Projects\icarus\convex\_generated\server.d.ts | TypeScript | 24 | 106 | 14 | 144 | +| e:\Projects\icarus\convex\_generated\server.js | JavaScript | 16 | 69 | 9 | 94 | +| e:\Projects\icarus\convex\auth.config.ts | TypeScript | 12 | 0 | 2 | 14 | +| e:\Projects\icarus\convex\elements.ts | TypeScript | 36 | 0 | 5 | 41 | +| e:\Projects\icarus\convex\folders.ts | TypeScript | 152 | 0 | 26 | 178 | +| e:\Projects\icarus\convex\health.ts | TypeScript | 7 | 1 | 1 | 9 | +| e:\Projects\icarus\convex\images.ts | TypeScript | 125 | 0 | 17 | 142 | +| e:\Projects\icarus\convex\invites.ts | TypeScript | 167 | 0 | 26 | 193 | +| e:\Projects\icarus\convex\lib\auth.ts | TypeScript | 60 | 0 | 15 | 75 | +| e:\Projects\icarus\convex\lib\entities.ts | TypeScript | 74 | 0 | 18 | 92 | +| e:\Projects\icarus\convex\lib\errors.ts | TypeScript | 10 | 0 | 2 | 12 | +| e:\Projects\icarus\convex\lib\opTypes.ts | TypeScript | 25 | 0 | 4 | 29 | +| e:\Projects\icarus\convex\lineups.ts | TypeScript | 35 | 0 | 5 | 40 | +| e:\Projects\icarus\convex\ops.ts | TypeScript | 475 | 1 | 29 | 505 | +| e:\Projects\icarus\convex\pages.ts | TypeScript | 222 | 0 | 36 | 258 | +| e:\Projects\icarus\convex\schema.ts | TypeScript | 135 | 1 | 4 | 140 | +| e:\Projects\icarus\convex\strategies.ts | TypeScript | 248 | 0 | 41 | 289 | +| e:\Projects\icarus\convex\users.ts | TypeScript | 58 | 0 | 10 | 68 | +| e:\Projects\icarus\devtools_options.yaml | YAML | 4 | 0 | 0 | 4 | +| e:\Projects\icarus\docs\version.json | JSON | 11 | 0 | 0 | 11 | +| e:\Projects\icarus\docs\windows_store_update_testing.md | Markdown | 25 | 0 | 10 | 35 | +| e:\Projects\icarus\flutter_convex_overview.md | Markdown | 379 | 0 | 114 | 493 | +| e:\Projects\icarus\index.ts | TypeScript | 1 | 0 | 0 | 1 | +| e:\Projects\icarus\ios\RunnerTests\RunnerTests.swift | Swift | 7 | 2 | 4 | 13 | +| e:\Projects\icarus\ios\Runner\AppDelegate.swift | Swift | 12 | 0 | 2 | 14 | +| e:\Projects\icarus\ios\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json | JSON | 122 | 0 | 1 | 123 | +| e:\Projects\icarus\ios\Runner\Assets.xcassets\LaunchImage.imageset\Contents.json | JSON | 23 | 0 | 1 | 24 | +| e:\Projects\icarus\ios\Runner\Assets.xcassets\LaunchImage.imageset\README.md | Markdown | 3 | 0 | 2 | 5 | +| e:\Projects\icarus\ios\Runner\Base.lproj\LaunchScreen.storyboard | XML | 36 | 1 | 1 | 38 | +| e:\Projects\icarus\ios\Runner\Base.lproj\Main.storyboard | XML | 25 | 1 | 1 | 27 | +| e:\Projects\icarus\ios\Runner\Runner-Bridging-Header.h | C++ | 1 | 0 | 1 | 2 | +| e:\Projects\icarus\lib\collab\collab_models.dart | Dart | 331 | 0 | 38 | 369 | +| e:\Projects\icarus\lib\collab\convex_payload.dart | Dart | 31 | 0 | 5 | 36 | +| e:\Projects\icarus\lib\collab\convex_strategy_repository.dart | Dart | 223 | 0 | 30 | 253 | +| e:\Projects\icarus\lib\const\abilities.dart | Dart | 371 | 3 | 43 | 417 | +| e:\Projects\icarus\lib\const\agents.dart | Dart | 787 | 27 | 103 | 917 | +| e:\Projects\icarus\lib\const\app_navigator.dart | Dart | 2 | 2 | 2 | 6 | +| e:\Projects\icarus\lib\const\bounding_box.dart | Dart | 26 | 0 | 9 | 35 | +| e:\Projects\icarus\lib\const\bounding_box.g.dart | Dart | 12 | 4 | 5 | 21 | +| e:\Projects\icarus\lib\const\color_option.dart | Dart | 6 | 0 | 3 | 9 | +| e:\Projects\icarus\lib\const\coordinate_system.dart | Dart | 77 | 7 | 22 | 106 | +| e:\Projects\icarus\lib\const\custom_icons.dart | Dart | 22 | 0 | 4 | 26 | +| e:\Projects\icarus\lib\const\default_placement.dart | Dart | 27 | 0 | 4 | 31 | +| e:\Projects\icarus\lib\const\drawing_element.dart | Dart | 235 | 6 | 47 | 288 | +| e:\Projects\icarus\lib\const\drawing_element.g.dart | Dart | 39 | 4 | 7 | 50 | +| e:\Projects\icarus\lib\const\hive_boxes.dart | Dart | 7 | 0 | 1 | 8 | +| e:\Projects\icarus\lib\const\image_scale_policy.dart | Dart | 8 | 0 | 2 | 10 | +| e:\Projects\icarus\lib\const\json_converters.dart | Dart | 126 | 7 | 24 | 157 | +| e:\Projects\icarus\lib\const\line_provider.dart | Dart | 280 | 13 | 54 | 347 | +| e:\Projects\icarus\lib\const\line_provider.g.dart | Dart | 29 | 4 | 7 | 40 | +| e:\Projects\icarus\lib\const\maps.dart | Dart | 60 | 0 | 5 | 65 | +| e:\Projects\icarus\lib\const\placed_classes.dart | Dart | 566 | 19 | 119 | 704 | +| e:\Projects\icarus\lib\const\placed_classes.g.dart | Dart | 171 | 4 | 18 | 193 | +| e:\Projects\icarus\lib\const\routes.dart | Dart | 5 | 0 | 1 | 6 | +| e:\Projects\icarus\lib\const\second_instance_args.dart | Dart | 7 | 3 | 3 | 13 | +| e:\Projects\icarus\lib\const\settings.dart | Dart | 160 | 16 | 19 | 195 | +| e:\Projects\icarus\lib\const\shortcut_info.dart | Dart | 85 | 6 | 19 | 110 | +| e:\Projects\icarus\lib\const\transition_data.dart | Dart | 138 | 6 | 25 | 169 | +| e:\Projects\icarus\lib\const\traversal_speed.dart | Dart | 16 | 1 | 3 | 20 | +| e:\Projects\icarus\lib\const\update_checker.dart | Dart | 249 | 0 | 30 | 279 | +| e:\Projects\icarus\lib\const\utilities.dart | Dart | 423 | 19 | 48 | 490 | +| e:\Projects\icarus\lib\const\youtube_handler.dart | Dart | 24 | 1 | 3 | 28 | +| e:\Projects\icarus\lib\hive\hive_adapters.dart | Dart | 48 | 1 | 4 | 53 | +| e:\Projects\icarus\lib\hive\hive_adapters.g.dart | Dart | 1,340 | 4 | 138 | 1,482 | +| e:\Projects\icarus\lib\hive\hive_adapters.g.yaml | YAML | 492 | 3 | 1 | 496 | +| e:\Projects\icarus\lib\hive\hive_registrar.g.dart | Dart | 67 | 3 | 4 | 74 | +| e:\Projects\icarus\lib\home_view.dart | Dart | 13 | 0 | 4 | 17 | +| e:\Projects\icarus\lib\interactive_map.dart | Dart | 343 | 5 | 18 | 366 | +| e:\Projects\icarus\lib\main.dart | Dart | 272 | 10 | 46 | 328 | +| e:\Projects\icarus\lib\migrations\ability_scale_migration.dart | Dart | 269 | 1 | 39 | 309 | +| e:\Projects\icarus\lib\providers\ability_bar_provider.dart | Dart | 13 | 0 | 4 | 17 | +| e:\Projects\icarus\lib\providers\ability_provider.dart | Dart | 156 | 16 | 55 | 227 | +| e:\Projects\icarus\lib\providers\action_provider.dart | Dart | 151 | 12 | 29 | 192 | +| e:\Projects\icarus\lib\providers\agent_filter_provider.dart | Dart | 117 | 0 | 17 | 134 | +| e:\Projects\icarus\lib\providers\agent_provider.dart | Dart | 155 | 4 | 47 | 206 | +| e:\Projects\icarus\lib\providers\auth_provider.dart | Dart | 789 | 1 | 90 | 880 | +| e:\Projects\icarus\lib\providers\auto_save_notifier.dart | Dart | 12 | 0 | 4 | 16 | +| e:\Projects\icarus\lib\providers\collab\cloud_collab_provider.dart | Dart | 55 | 1 | 10 | 66 | +| e:\Projects\icarus\lib\providers\collab\cloud_migration_provider.dart | Dart | 222 | 0 | 26 | 248 | +| e:\Projects\icarus\lib\providers\collab\remote_library_provider.dart | Dart | 82 | 0 | 10 | 92 | +| e:\Projects\icarus\lib\providers\collab\remote_strategy_snapshot_provider.dart | Dart | 232 | 1 | 35 | 268 | +| e:\Projects\icarus\lib\providers\collab\strategy_conflict_provider.dart | Dart | 21 | 0 | 6 | 27 | +| e:\Projects\icarus\lib\providers\collab\strategy_op_queue_provider.dart | Dart | 226 | 0 | 40 | 266 | +| e:\Projects\icarus\lib\providers\drawing_provider.dart | Dart | 501 | 50 | 111 | 662 | +| e:\Projects\icarus\lib\providers\favorite_agents_provider.dart | Dart | 40 | 1 | 9 | 50 | +| e:\Projects\icarus\lib\providers\folder_provider.dart | Dart | 274 | 0 | 34 | 308 | +| e:\Projects\icarus\lib\providers\image_provider.dart | Dart | 374 | 60 | 96 | 530 | +| e:\Projects\icarus\lib\providers\image_widget_size_provider.dart | Dart | 21 | 0 | 7 | 28 | +| e:\Projects\icarus\lib\providers\in_app_debug_provider.dart | Dart | 18 | 0 | 6 | 24 | +| e:\Projects\icarus\lib\providers\interaction_state_provider.dart | Dart | 41 | 1 | 9 | 51 | +| e:\Projects\icarus\lib\providers\map_provider.dart | Dart | 85 | 1 | 20 | 106 | +| e:\Projects\icarus\lib\providers\map_theme_provider.dart | Dart | 421 | 0 | 60 | 481 | +| e:\Projects\icarus\lib\providers\pen_provider.dart | Dart | 156 | 0 | 20 | 176 | +| e:\Projects\icarus\lib\providers\placement_center_provider.dart | Dart | 13 | 0 | 5 | 18 | +| e:\Projects\icarus\lib\providers\screen_zoom_provider.dart | Dart | 22 | 0 | 6 | 28 | +| e:\Projects\icarus\lib\providers\screenshot_provider.dart | Dart | 13 | 0 | 4 | 17 | +| e:\Projects\icarus\lib\providers\strategy_filter_provider.dart | Dart | 66 | 0 | 14 | 80 | +| e:\Projects\icarus\lib\providers\strategy_page.dart | Dart | 152 | 0 | 15 | 167 | +| e:\Projects\icarus\lib\providers\strategy_provider.dart | Dart | 2,101 | 79 | 314 | 2,494 | +| e:\Projects\icarus\lib\providers\strategy_settings_provider.dart | Dart | 64 | 0 | 16 | 80 | +| e:\Projects\icarus\lib\providers\strategy_settings_provider.g.dart | Dart | 12 | 4 | 5 | 21 | +| e:\Projects\icarus\lib\providers\team_provider.dart | Dart | 11 | 0 | 4 | 15 | +| e:\Projects\icarus\lib\providers\text_provider.dart | Dart | 142 | 2 | 47 | 191 | +| e:\Projects\icarus\lib\providers\text_widget_height_provider.dart | Dart | 21 | 0 | 7 | 28 | +| e:\Projects\icarus\lib\providers\transition_provider.dart | Dart | 151 | 0 | 16 | 167 | +| e:\Projects\icarus\lib\providers\update_status_provider.dart | Dart | 5 | 0 | 2 | 7 | +| e:\Projects\icarus\lib\providers\utility_provider.dart | Dart | 139 | 2 | 39 | 180 | +| e:\Projects\icarus\lib\screenshot\screenshot_view.dart | Dart | 147 | 2 | 12 | 161 | +| e:\Projects\icarus\lib\services\clipboard_service.dart | Dart | 55 | 4 | 10 | 69 | +| e:\Projects\icarus\lib\services\deep_link_registrar.dart | Dart | 54 | 0 | 11 | 65 | +| e:\Projects\icarus\lib\sidebar.dart | Dart | 206 | 4 | 7 | 217 | +| e:\Projects\icarus\lib\strategy_view.dart | Dart | 161 | 8 | 13 | 182 | +| e:\Projects\icarus\lib\widgets\bg_dot_painter.dart | Dart | 53 | 5 | 15 | 73 | +| e:\Projects\icarus\lib\widgets\cloud_library_widgets.dart | Dart | 355 | 0 | 26 | 381 | +| e:\Projects\icarus\lib\widgets\color_picker_button.dart | Dart | 66 | 1 | 5 | 72 | +| e:\Projects\icarus\lib\widgets\current_line_up_painter.dart | Dart | 87 | 2 | 12 | 101 | +| e:\Projects\icarus\lib\widgets\current_path_bar.dart | Dart | 84 | 4 | 11 | 99 | +| e:\Projects\icarus\lib\widgets\cursor_circle.dart | Dart | 68 | 2 | 10 | 80 | +| e:\Projects\icarus\lib\widgets\custom_border_container.dart | Dart | 66 | 2 | 5 | 73 | +| e:\Projects\icarus\lib\widgets\custom_button.dart | Dart | 117 | 2 | 9 | 128 | +| e:\Projects\icarus\lib\widgets\custom_expansion_tile.dart | Dart | 167 | 23 | 35 | 225 | +| e:\Projects\icarus\lib\widgets\custom_folder_painter.dart | Dart | 68 | 24 | 16 | 108 | +| e:\Projects\icarus\lib\widgets\custom_menu_builder.dart | Dart | 0 | 0 | 1 | 1 | +| e:\Projects\icarus\lib\widgets\custom_search_field.dart | Dart | 167 | 21 | 17 | 205 | +| e:\Projects\icarus\lib\widgets\custom_segmented_tabs.dart | Dart | 267 | 13 | 39 | 319 | +| e:\Projects\icarus\lib\widgets\custom_text_field.dart | Dart | 47 | 0 | 3 | 50 | +| e:\Projects\icarus\lib\widgets\delete_area.dart | Dart | 100 | 1 | 4 | 105 | +| e:\Projects\icarus\lib\widgets\delete_capture.dart | Dart | 61 | 0 | 3 | 64 | +| e:\Projects\icarus\lib\widgets\demo_dialog.dart | Dart | 39 | 0 | 3 | 42 | +| e:\Projects\icarus\lib\widgets\demo_tag.dart | Dart | 64 | 0 | 6 | 70 | +| e:\Projects\icarus\lib\widgets\dialogs\auth\auth_dialog.dart | Dart | 189 | 0 | 20 | 209 | +| e:\Projects\icarus\lib\widgets\dialogs\confirm_alert_dialog.dart | Dart | 70 | 1 | 6 | 77 | +| e:\Projects\icarus\lib\widgets\dialogs\create_lineup_dialog.dart | Dart | 162 | 12 | 25 | 199 | +| e:\Projects\icarus\lib\widgets\dialogs\in_app_debug_dialog.dart | Dart | 84 | 0 | 4 | 88 | +| e:\Projects\icarus\lib\widgets\dialogs\strategy\create_strategy_dialog.dart | Dart | 83 | 8 | 7 | 98 | +| e:\Projects\icarus\lib\widgets\dialogs\strategy\delete_strategy_alert_dialog.dart | Dart | 71 | 2 | 5 | 78 | +| e:\Projects\icarus\lib\widgets\dialogs\strategy\line_up_media_page.dart | Dart | 247 | 5 | 18 | 270 | +| e:\Projects\icarus\lib\widgets\dialogs\strategy\rename_strategy_dialog.dart | Dart | 87 | 11 | 9 | 107 | +| e:\Projects\icarus\lib\widgets\dialogs\upload_image_dialog.dart | Dart | 421 | 3 | 33 | 457 | +| e:\Projects\icarus\lib\widgets\dialogs\web_view_dialog.dart | Dart | 29 | 0 | 3 | 32 | +| e:\Projects\icarus\lib\widgets\dot_painter.dart | Dart | 52 | 49 | 22 | 123 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\ability_widget.dart | Dart | 71 | 4 | 7 | 82 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\center_square_widget.dart | Dart | 67 | 0 | 3 | 70 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\custom_circle_widget.dart | Dart | 115 | 10 | 13 | 138 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\custom_square_widget.dart | Dart | 113 | 13 | 8 | 134 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\placed_ability_widget.dart | Dart | 281 | 15 | 33 | 329 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\resizable_square_widget.dart | Dart | 103 | 1 | 11 | 115 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\rotatable_image_widget.dart | Dart | 48 | 0 | 4 | 52 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\ability\rotatable_widget.dart | Dart | 91 | 33 | 10 | 134 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_feedback_widget.dart | Dart | 37 | 0 | 2 | 39 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_icon_widget.dart | Dart | 41 | 0 | 5 | 46 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\agents\agent_widget.dart | Dart | 191 | 11 | 29 | 231 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\image\image_widget.dart | Dart | 259 | 4 | 18 | 281 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\image\placed_image_builder.dart | Dart | 176 | 0 | 15 | 191 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\image\scalable_widget.dart | Dart | 45 | 3 | 5 | 53 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\placed_widget_builder.dart | Dart | 564 | 10 | 60 | 634 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\text\placed_text_builder.dart | Dart | 159 | 0 | 9 | 168 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\text\text_scale_controller.dart | Dart | 56 | 0 | 5 | 61 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\text\text_widget.dart | Dart | 120 | 5 | 12 | 137 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\custom_circle_utility_widget.dart | Dart | 110 | 0 | 8 | 118 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\custom_rectangle_utility_widget.dart | Dart | 118 | 0 | 8 | 126 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\image_utility_widget.dart | Dart | 38 | 0 | 4 | 42 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\placed_view_cone_widget.dart | Dart | 173 | 14 | 28 | 215 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\utility_widget_builder.dart | Dart | 69 | 1 | 4 | 74 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\utilities\view_cone_widget.dart | Dart | 148 | 18 | 27 | 193 | +| e:\Projects\icarus\lib\widgets\draggable_widgets\zoom_transform.dart | Dart | 18 | 0 | 2 | 20 | +| e:\Projects\icarus\lib\widgets\drawing_painter.dart | Dart | 510 | 25 | 59 | 594 | +| e:\Projects\icarus\lib\widgets\folder_content.dart | Dart | 415 | 10 | 26 | 451 | +| e:\Projects\icarus\lib\widgets\folder_edit_dialog.dart | Dart | 248 | 5 | 7 | 260 | +| e:\Projects\icarus\lib\widgets\folder_navigator.dart | Dart | 524 | 6 | 47 | 577 | +| e:\Projects\icarus\lib\widgets\folder_pill.dart | Dart | 275 | 0 | 13 | 288 | +| e:\Projects\icarus\lib\widgets\folder_tile.dart | Dart | 0 | 314 | 16 | 330 | +| e:\Projects\icarus\lib\widgets\global_shortcuts.dart | Dart | 140 | 1 | 15 | 156 | +| e:\Projects\icarus\lib\widgets\ica_drop_target.dart | Dart | 73 | 1 | 4 | 78 | +| e:\Projects\icarus\lib\widgets\image_drop_target.dart | Dart | 84 | 0 | 5 | 89 | +| e:\Projects\icarus\lib\widgets\image_paste_shortcut.dart | Dart | 0 | 0 | 1 | 1 | +| e:\Projects\icarus\lib\widgets\inner_container.dart | Dart | 9 | 0 | 2 | 11 | +| e:\Projects\icarus\lib\widgets\interaction_state_display.dart | Dart | 400 | 2 | 24 | 426 | +| e:\Projects\icarus\lib\widgets\line_up_line_painter.dart | Dart | 137 | 4 | 19 | 160 | +| e:\Projects\icarus\lib\widgets\line_up_media_carousel.dart | Dart | 247 | 6 | 21 | 274 | +| e:\Projects\icarus\lib\widgets\line_up_placer.dart | Dart | 235 | 3 | 18 | 256 | +| e:\Projects\icarus\lib\widgets\line_up_widget.dart | Dart | 76 | 0 | 9 | 85 | +| e:\Projects\icarus\lib\widgets\map_selector.dart | Dart | 204 | 8 | 11 | 223 | +| e:\Projects\icarus\lib\widgets\map_theme_settings_section.dart | Dart | 764 | 5 | 56 | 825 | +| e:\Projects\icarus\lib\widgets\map_tile.dart | Dart | 86 | 0 | 5 | 91 | +| e:\Projects\icarus\lib\widgets\mouse_watch.dart | Dart | 141 | 6 | 11 | 158 | +| e:\Projects\icarus\lib\widgets\numeric_drag_input.dart | Dart | 296 | 11 | 31 | 338 | +| e:\Projects\icarus\lib\widgets\page_transition_overlay.dart | Dart | 463 | 3 | 31 | 497 | +| e:\Projects\icarus\lib\widgets\pages_bar.dart | Dart | 115 | 0 | 16 | 131 | +| e:\Projects\icarus\lib\widgets\save_and_load_button.dart | Dart | 191 | 1 | 13 | 205 | +| e:\Projects\icarus\lib\widgets\selectable_icon_button.dart | Dart | 64 | 0 | 5 | 69 | +| e:\Projects\icarus\lib\widgets\settings_tab.dart | Dart | 237 | 0 | 5 | 242 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\ability_bar.dart | Dart | 124 | 3 | 10 | 137 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\agent_dragable.dart | Dart | 239 | 2 | 15 | 256 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\agent_filter.dart | Dart | 32 | 0 | 4 | 36 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\bottom_tray.dart | Dart | 0 | 13 | 4 | 17 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\color_buttons.dart | Dart | 71 | 61 | 10 | 142 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\custom_shape_tools.dart | Dart | 300 | 5 | 16 | 321 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\delete_options.dart | Dart | 118 | 0 | 3 | 121 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\drawing_tools.dart | Dart | 224 | 1 | 5 | 230 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\image_selector.dart | Dart | 0 | 0 | 2 | 2 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\role_picker.dart | Dart | 61 | 0 | 4 | 65 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\team_picker.dart | Dart | 77 | 1 | 9 | 87 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\text_tools.dart | Dart | 145 | 0 | 12 | 157 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\tool_grid.dart | Dart | 373 | 8 | 18 | 399 | +| e:\Projects\icarus\lib\widgets\sidebar_widgets\vision_cone_tools.dart | Dart | 152 | 0 | 7 | 159 | +| e:\Projects\icarus\lib\widgets\strategy_save_icon_button.dart | Dart | 117 | 37 | 22 | 176 | +| e:\Projects\icarus\lib\widgets\strategy_tile\strategy_tile.dart | Dart | 216 | 0 | 20 | 236 | +| e:\Projects\icarus\lib\widgets\strategy_tile\strategy_tile_sections.dart | Dart | 254 | 0 | 25 | 279 | +| e:\Projects\icarus\lib\widgets\youtube_view.dart | Dart | 51 | 30 | 11 | 92 | +| e:\Projects\icarus\linux\flutter\generated_plugin_registrant.cc | C++ | 31 | 4 | 5 | 40 | +| e:\Projects\icarus\linux\flutter\generated_plugin_registrant.h | C++ | 5 | 5 | 6 | 16 | +| e:\Projects\icarus\linux\main.cc | C++ | 5 | 0 | 2 | 7 | +| e:\Projects\icarus\linux\my_application.cc | C++ | 82 | 17 | 26 | 125 | +| e:\Projects\icarus\linux\my_application.h | C++ | 7 | 7 | 5 | 19 | +| e:\Projects\icarus\macos\Flutter\GeneratedPluginRegistrant.swift | Swift | 26 | 3 | 4 | 33 | +| e:\Projects\icarus\macos\RunnerTests\RunnerTests.swift | Swift | 7 | 2 | 4 | 13 | +| e:\Projects\icarus\macos\Runner\AppDelegate.swift | Swift | 11 | 0 | 3 | 14 | +| e:\Projects\icarus\macos\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json | JSON | 68 | 0 | 1 | 69 | +| e:\Projects\icarus\macos\Runner\Base.lproj\MainMenu.xib | XML | 343 | 0 | 1 | 344 | +| e:\Projects\icarus\macos\Runner\MainFlutterWindow.swift | Swift | 12 | 0 | 4 | 16 | +| e:\Projects\icarus\package.json | JSON | 15 | 0 | 1 | 16 | +| e:\Projects\icarus\pubspec.yaml | YAML | 98 | 6 | 10 | 114 | +| e:\Projects\icarus\scripts\bump_version.ps1 | PowerShell | 133 | 31 | 30 | 194 | +| e:\Projects\icarus\test\STRATEGY_INTEGRITY_MAINTENANCE.md | Markdown | 39 | 0 | 24 | 63 | +| e:\Projects\icarus\test\collab_sync_models_test.dart | Dart | 99 | 0 | 15 | 114 | +| e:\Projects\icarus\test\strategy_import_version_guard_test.dart | Dart | 58 | 0 | 11 | 69 | +| e:\Projects\icarus\test\strategy_integrity_test.dart | Dart | 367 | 8 | 49 | 424 | +| e:\Projects\icarus\test\update_checker_test.dart | Dart | 130 | 0 | 22 | 152 | +| e:\Projects\icarus\tool\_probe.dart | Dart | 33 | 0 | 2 | 35 | +| e:\Projects\icarus\tsconfig.json | JSON with Comments | 22 | 4 | 4 | 30 | +| e:\Projects\icarus\web\index.html | HTML | 19 | 15 | 5 | 39 | +| e:\Projects\icarus\web\manifest.json | JSON | 35 | 0 | 1 | 36 | +| e:\Projects\icarus\windows\flutter\generated_plugin_registrant.cc | C++ | 27 | 4 | 5 | 36 | +| e:\Projects\icarus\windows\flutter\generated_plugin_registrant.h | C++ | 5 | 5 | 6 | 16 | +| e:\Projects\icarus\windows\runner\flutter_window.cpp | C++ | 109 | 8 | 25 | 142 | +| e:\Projects\icarus\windows\runner\flutter_window.h | C++ | 25 | 5 | 10 | 40 | +| e:\Projects\icarus\windows\runner\main.cpp | C++ | 90 | 12 | 23 | 125 | +| e:\Projects\icarus\windows\runner\resource.h | C++ | 9 | 6 | 2 | 17 | +| e:\Projects\icarus\windows\runner\utils.cpp | C++ | 54 | 2 | 10 | 66 | +| e:\Projects\icarus\windows\runner\utils.h | C++ | 8 | 6 | 6 | 20 | +| e:\Projects\icarus\windows\runner\win32_window.cpp | C++ | 199 | 20 | 53 | 272 | +| e:\Projects\icarus\windows\runner\win32_window.h | C++ | 48 | 31 | 24 | 103 | +| Total | | 37,981 | 2,032 | 4,665 | 44,678 | ++-------------------------------------------------------------------------------------------------+--------------------+------------+------------+------------+------------+ \ No newline at end of file diff --git a/.agent/skills/convex-create-component/SKILL.md b/.agent/skills/convex-create-component/SKILL.md new file mode 100644 index 00000000..effe01fa --- /dev/null +++ b/.agent/skills/convex-create-component/SKILL.md @@ -0,0 +1,411 @@ +--- +name: convex-create-component +description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. +--- + +# Convex Create Component + +Create reusable Convex components with clear boundaries and a small app-facing API. + +## When to Use + +- Creating a new Convex component in an existing app +- Extracting reusable backend logic into a component +- Building a third-party integration that should own its own tables and workflows +- Packaging Convex functionality for reuse across multiple apps + +## When Not to Use + +- One-off business logic that belongs in the main app +- Thin utilities that do not need Convex tables or functions +- App-level orchestration that should stay in `convex/` +- Cases where a normal TypeScript library is enough + +## Workflow + +1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. +2. Choose the shape using the decision tree below and read the matching reference file. +3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. +4. Make a short plan for: + - what tables the component owns + - what public functions it exposes + - what data must be passed in from the app (auth, env vars, parent IDs) + - what stays in the app as wrappers or HTTP mounts +5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. +6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. +7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. +8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. +9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. +10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. + +## Choose the Shape + +Ask the user, then pick one path: + +| Goal | Shape | Reference | +|------|-------|-----------| +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | + +Read exactly one reference file before proceeding. + +## Default Approach + +Unless the user explicitly wants an npm package, default to a local component: + +- Put it under `convex/components//` +- Define it with `defineComponent(...)` in its own `convex.config.ts` +- Install it from the app's `convex/convex.config.ts` with `app.use(...)` +- Let `npx convex dev` generate the component's own `_generated/` files + +## Component Skeleton + +A minimal local component with a table and two functions, plus the app wiring. + +```ts +// convex/components/notifications/convex.config.ts +import { defineComponent } from "convex/server"; + +export default defineComponent("notifications"); +``` + +```ts +// convex/components/notifications/schema.ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notifications: defineTable({ + userId: v.string(), + message: v.string(), + read: v.boolean(), + }).index("by_user", ["userId"]), +}); +``` + +```ts +// convex/components/notifications/lib.ts +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server.js"; + +export const send = mutation({ + args: { userId: v.string(), message: v.string() }, + returns: v.id("notifications"), + handler: async (ctx, args) => { + return await ctx.db.insert("notifications", { + userId: args.userId, + message: args.message, + read: false, + }); + }, +}); + +export const listUnread = query({ + args: { userId: v.string() }, + returns: v.array( + v.object({ + _id: v.id("notifications"), + _creationTime: v.number(), + userId: v.string(), + message: v.string(), + read: v.boolean(), + }) + ), + handler: async (ctx, args) => { + return await ctx.db + .query("notifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .filter((q) => q.eq(q.field("read"), false)) + .collect(); + }, +}); +``` + +```ts +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import notifications from "./components/notifications/convex.config.js"; + +const app = defineApp(); +app.use(notifications); + +export default app; +``` + +```ts +// convex/notifications.ts (app-side wrapper) +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server"; +import { components } from "./_generated/api"; +import { getAuthUserId } from "@convex-dev/auth/server"; + +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); + +export const myUnread = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + return await ctx.runQuery(components.notifications.lib.listUnread, { + userId, + }); + }, +}); +``` + +Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. + +## Critical Rules + +- Keep authentication in the app. `ctx.auth` is not available inside components. +- Keep environment access in the app. Component functions cannot read `process.env`. +- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. +- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. +- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. +- Do not expose component functions directly to clients. Create app wrappers when client access is needed. +- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. +- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. +- Add `args` and `returns` validators to all public component functions. + +## Patterns + +### Authentication and environment access + +```ts +// Bad: component code cannot rely on app auth or env +const identity = await ctx.auth.getUserIdentity(); +const apiKey = process.env.OPENAI_API_KEY; +``` + +```ts +// Good: the app resolves auth and env, then passes explicit values +const userId = await getAuthUserId(ctx); +if (!userId) throw new Error("Not authenticated"); + +await ctx.runAction(components.translator.translate, { + userId, + apiKey: process.env.OPENAI_API_KEY, + text: args.text, +}); +``` + +### Client-facing API + +```ts +// Bad: assuming a component function is directly callable by clients +export const send = components.notifications.send; +``` + +```ts +// Good: re-export through an app mutation or query +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); +``` + +### IDs across the boundary + +```ts +// Bad: parent app table IDs are not valid component validators +args: { userId: v.id("users") } +``` + +```ts +// Good: treat parent-owned IDs as strings at the boundary +args: { userId: v.string() } +``` + +### Function Handles for callbacks + +When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. + +```ts +// App side: create a handle and pass it to the component +import { createFunctionHandle } from "convex/server"; + +export const startJob = mutation({ + handler: async (ctx) => { + const handle = await createFunctionHandle(internal.myModule.processItem); + await ctx.runMutation(components.workpool.enqueue, { + callback: handle, + }); + }, +}); +``` + +```ts +// Component side: accept and invoke the handle +import { v } from "convex/values"; +import type { FunctionHandle } from "convex/server"; +import { mutation } from "./_generated/server.js"; + +export const enqueue = mutation({ + args: { callback: v.string() }, + handler: async (ctx, args) => { + const handle = args.callback as FunctionHandle<"mutation">; + await ctx.scheduler.runAfter(0, handle, {}); + }, +}); +``` + +### Deriving validators from schema + +Instead of manually repeating field types in return validators, extend the schema validator: + +```ts +import { v } from "convex/values"; +import schema from "./schema.js"; + +const notificationDoc = schema.tables.notifications.validator.extend({ + _id: v.id("notifications"), + _creationTime: v.number(), +}); + +export const getLatest = query({ + args: {}, + returns: v.nullable(notificationDoc), + handler: async (ctx) => { + return await ctx.db.query("notifications").order("desc").first(); + }, +}); +``` + +### Static configuration with a globals table + +A common pattern for component configuration is a single-document "globals" table: + +```ts +// schema.ts +export default defineSchema({ + globals: defineTable({ + maxRetries: v.number(), + webhookUrl: v.optional(v.string()), + }), + // ... other tables +}); +``` + +```ts +// lib.ts +export const configure = mutation({ + args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, args) => { + const existing = await ctx.db.query("globals").first(); + if (existing) { + await ctx.db.patch(existing._id, args); + } else { + await ctx.db.insert("globals", args); + } + return null; + }, +}); +``` + +### Class-based client wrappers + +For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. + +```ts +// src/client/index.ts +import type { GenericMutationCtx, GenericDataModel } from "convex/server"; +import type { ComponentApi } from "../component/_generated/component.js"; + +type MutationCtx = Pick, "runMutation">; + +export class Notifications { + constructor( + private component: ComponentApi, + private options?: { defaultChannel?: string }, + ) {} + + async send(ctx: MutationCtx, args: { userId: string; message: string }) { + return await ctx.runMutation(this.component.lib.send, { + ...args, + channel: this.options?.defaultChannel ?? "default", + }); + } +} +``` + +```ts +// App usage +import { Notifications } from "@convex-dev/notifications"; +import { components } from "./_generated/api"; + +const notifications = new Notifications(components.notifications, { + defaultChannel: "alerts", +}); + +export const send = mutation({ + args: { message: v.string() }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + await notifications.send(ctx, { userId, message: args.message }); + }, +}); +``` + +## Validation + +Try validation in this order: + +1. `npx convex codegen --component-dir convex/components/` +2. `npx convex codegen` +3. `npx convex dev` + +Important: + +- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. +- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. +- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. + +## Reference Files + +Read exactly one of these after the user confirms the goal: + +- `references/local-components.md` +- `references/packaged-components.md` +- `references/hybrid-components.md` + +Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) + +## Checklist + +- [ ] Asked the user what they want to build and confirmed the shape +- [ ] Read the matching reference file +- [ ] Confirmed a component is the right abstraction +- [ ] Planned tables, public API, boundaries, and app wrappers +- [ ] Component lives under `convex/components//` (or package layout if publishing) +- [ ] Component imports from its own `./_generated/server` +- [ ] Auth, env access, and HTTP routes stay in the app +- [ ] Parent app IDs cross the boundary as `v.string()` +- [ ] Public functions have `args` and `returns` validators +- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.agent/skills/convex-create-component/agents/openai.yaml b/.agent/skills/convex-create-component/agents/openai.yaml new file mode 100644 index 00000000..ba9287e4 --- /dev/null +++ b/.agent/skills/convex-create-component/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Create Component" + short_description: "Design and build reusable Convex components with clear boundaries." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#14B8A6" + default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." + +policy: + allow_implicit_invocation: true diff --git a/.agent/skills/convex-create-component/assets/icon.svg b/.agent/skills/convex-create-component/assets/icon.svg new file mode 100644 index 00000000..10f4c2c4 --- /dev/null +++ b/.agent/skills/convex-create-component/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agent/skills/convex-create-component/references/hybrid-components.md b/.agent/skills/convex-create-component/references/hybrid-components.md new file mode 100644 index 00000000..d2bb3514 --- /dev/null +++ b/.agent/skills/convex-create-component/references/hybrid-components.md @@ -0,0 +1,37 @@ +# Hybrid Convex Components + +Read this file only when the user explicitly wants a hybrid setup. + +## What This Means + +A hybrid component combines a local Convex component with shared library code. + +This can help when: + +- the user wants a local install but also shared package logic +- the component needs extension points or override hooks +- some logic should live in normal TypeScript code outside the component boundary + +## Default Advice + +Treat hybrid as an advanced option, not the default. + +Before choosing it, ask: + +- Why is a plain local component not enough? +- Why is a packaged component not enough? +- What exactly needs to stay overridable or shared? + +If the answer is vague, fall back to local or packaged. + +## Risks + +- More moving parts +- Harder upgrades and backwards compatibility +- Easier to blur the component boundary + +## Checklist + +- [ ] User explicitly needs hybrid behavior +- [ ] Local-only and packaged-only options were considered first +- [ ] The extension points are clearly defined before coding diff --git a/.agent/skills/convex-create-component/references/local-components.md b/.agent/skills/convex-create-component/references/local-components.md new file mode 100644 index 00000000..7fbfe21a --- /dev/null +++ b/.agent/skills/convex-create-component/references/local-components.md @@ -0,0 +1,38 @@ +# Local Convex Components + +Read this file when the component should live inside the current app and does not need to be published as an npm package. + +## When to Choose This + +- The user wants the simplest path +- The component only needs to work in this repo +- The goal is extracting app logic into a cleaner boundary + +## Default Layout + +Use this structure unless the repo already has a clear alternative pattern: + +```text +convex/ + convex.config.ts + components/ + / + convex.config.ts + schema.ts + .ts +``` + +## Workflow Notes + +- Define the component with `defineComponent("")` +- Install it from the app with `defineApp()` and `app.use(...)` +- Keep auth, env access, public API wrappers, and HTTP route mounting in the app +- Let the component own isolated tables and reusable backend workflows +- Add app wrappers if clients need to call into the component + +## Checklist + +- [ ] Component is inside `convex/components//` +- [ ] App installs it with `app.use(...)` +- [ ] Component owns only its own tables +- [ ] App wrappers handle client-facing calls when needed diff --git a/.agent/skills/convex-create-component/references/packaged-components.md b/.agent/skills/convex-create-component/references/packaged-components.md new file mode 100644 index 00000000..5668e7ed --- /dev/null +++ b/.agent/skills/convex-create-component/references/packaged-components.md @@ -0,0 +1,51 @@ +# Packaged Convex Components + +Read this file when the user wants a reusable npm package or a component shared across multiple apps. + +## When to Choose This + +- The user wants to publish the component +- The user wants a stable reusable package boundary +- The component will be shared across multiple apps or teams + +## Default Approach + +- Prefer starting from `npx create-convex@latest --component` when possible +- Keep the official authoring docs as the source of truth for package layout and exports +- Validate the bundled package through an example app, not just the source files + +## Build Flow + +When building a packaged component, make sure the bundled output exists before the example app tries to consume it. + +Recommended order: + +1. `npx convex codegen --component-dir ./path/to/component` +2. Run the package build command +3. Run `npx convex dev --typecheck-components` in the example app + +Do not assume normal app codegen is enough for packaged component workflows. + +## Package Exports + +If publishing to npm, make sure the package exposes the entry points apps need: + +- package root for client helpers, types, or classes +- `./convex.config.js` for installing the component +- `./_generated/component.js` for the app-facing `ComponentApi` type +- `./test` for testing helpers when applicable + +## Testing + +- Use `convex-test` for component logic +- Register the component schema and modules with the test instance +- Test app-side wrapper code from an example app that installs the package +- Export a small helper from `./test` if consumers need easy test registration + +## Checklist + +- [ ] Packaging is actually required +- [ ] Build order avoids bundle and codegen races +- [ ] Package exports include install and typing entry points +- [ ] Example app exercises the packaged component +- [ ] Core behavior is covered by tests diff --git a/.agent/skills/convex-migration-helper/SKILL.md b/.agent/skills/convex-migration-helper/SKILL.md new file mode 100644 index 00000000..f353678f --- /dev/null +++ b/.agent/skills/convex-migration-helper/SKILL.md @@ -0,0 +1,524 @@ +--- +name: convex-migration-helper +description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. +--- + +# Convex Migration Helper + +Safely migrate Convex schemas and data when making breaking changes. + +## When to Use + +- Adding new required fields to existing tables +- Changing field types or structure +- Splitting or merging tables +- Renaming or deleting fields +- Migrating from nested to relational data + +## Key Concepts + +### Schema Validation Drives the Workflow + +Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: + +- You cannot add a required field if existing documents don't have it +- You cannot change a field's type if existing documents have the old type +- You cannot remove a field from the schema if existing documents still have it + +This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. + +### Online Migrations + +Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. + +### Prefer New Fields Over Changing Types + +When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. + +### Don't Delete Data + +Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. + +## Safe Changes (No Migration Needed) + +### Adding Optional Field + +```typescript +// Before +users: defineTable({ + name: v.string(), +}) + +// After - safe, new field is optional +users: defineTable({ + name: v.string(), + bio: v.optional(v.string()), +}) +``` + +### Adding New Table + +```typescript +posts: defineTable({ + userId: v.id("users"), + title: v.string(), +}).index("by_user", ["userId"]) +``` + +### Adding Index + +```typescript +users: defineTable({ + name: v.string(), + email: v.string(), +}) + .index("by_email", ["email"]) +``` + +## Breaking Changes: The Deployment Workflow + +Every breaking migration follows the same multi-deploy pattern: + +**Deploy 1 - Widen the schema:** + +1. Update schema to allow both old and new formats (e.g., add optional new field) +2. Update code to handle both formats when reading +3. Update code to write the new format for new documents +4. Deploy + +**Between deploys - Migrate data:** + +5. Run migration to backfill existing documents +6. Verify all documents are migrated + +**Deploy 2 - Narrow the schema:** + +7. Update schema to require the new format only +8. Remove code that handles the old format +9. Deploy + +## Using the Migrations Component (Recommended) + +For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. + +### Installation + +```bash +npm install @convex-dev/migrations +``` + +### Setup + +```typescript +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import migrations from "@convex-dev/migrations/convex.config.js"; + +const app = defineApp(); +app.use(migrations); +export default app; +``` + +```typescript +// convex/migrations.ts +import { Migrations } from "@convex-dev/migrations"; +import { components } from "./_generated/api.js"; +import { DataModel } from "./_generated/dataModel.js"; + +export const migrations = new Migrations(components.migrations); +export const run = migrations.runner(); +``` + +The `DataModel` type parameter is optional but provides type safety for migration definitions. + +### Define a Migration + +The `migrateOne` function processes a single document. The component handles batching and pagination automatically. + +```typescript +// convex/migrations.ts +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); +``` + +Shorthand: if you return an object, it is applied as a patch automatically. + +```typescript +export const clearDeprecatedField = migrations.define({ + table: "users", + migrateOne: () => ({ legacyField: undefined }), +}); +``` + +### Run a Migration + +From the CLI: + +```bash +# Define a one-off runner in convex/migrations.ts: +# export const runIt = migrations.runner(internal.migrations.addDefaultRole); +npx convex run migrations:runIt + +# Or use the general-purpose runner +npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' +``` + +Programmatically from another Convex function: + +```typescript +await migrations.runOne(ctx, internal.migrations.addDefaultRole); +``` + +### Run Multiple Migrations in Order + +```typescript +export const runAll = migrations.runner([ + internal.migrations.addDefaultRole, + internal.migrations.clearDeprecatedField, + internal.migrations.normalizeEmails, +]); +``` + +```bash +npx convex run migrations:runAll +``` + +If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. + +### Dry Run + +Test a migration before committing changes: + +```bash +npx convex run migrations:runIt '{"dryRun": true}' +``` + +This runs one batch and then rolls back, so you can see what it would do without changing any data. + +### Check Migration Status + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +### Cancel a Running Migration + +```bash +npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' +``` + +Or programmatically: + +```typescript +await migrations.cancel(ctx, internal.migrations.addDefaultRole); +``` + +### Run Migrations on Deploy + +Chain migration execution after deploying: + +```bash +npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod +``` + +### Configuration Options + +#### Custom Batch Size + +If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: + +```typescript +export const migrateHeavyTable = migrations.define({ + table: "largeDocuments", + batchSize: 10, + migrateOne: async (ctx, doc) => { + // migration logic + }, +}); +``` + +#### Migrate a Subset Using an Index + +Process only matching documents instead of the full table: + +```typescript +export const fixEmptyNames = migrations.define({ + table: "users", + customRange: (query) => + query.withIndex("by_name", (q) => q.eq("name", "")), + migrateOne: () => ({ name: "" }), +}); +``` + +#### Parallelize Within a Batch + +By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: + +```typescript +export const clearField = migrations.define({ + table: "myTable", + parallelize: true, + migrateOne: () => ({ optionalField: undefined }), +}); +``` + +## Common Migration Patterns + +### Adding a Required Field + +```typescript +// Deploy 1: Schema allows both states +users: defineTable({ + name: v.string(), + role: v.optional(v.union(v.literal("user"), v.literal("admin"))), +}) + +// Migration: backfill the field +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); + +// Deploy 2: After migration completes, make it required +users: defineTable({ + name: v.string(), + role: v.union(v.literal("user"), v.literal("admin")), +}) +``` + +### Deleting a Field + +Mark the field optional first, migrate data to remove it, then remove from schema: + +```typescript +// Deploy 1: Make optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()) + +// Migration +export const removeIsPro = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.isPro !== undefined) { + await ctx.db.patch(team._id, { isPro: undefined }); + } + }, +}); + +// Deploy 2: Remove isPro from schema entirely +``` + +### Changing a Field Type + +Prefer creating a new field. You can combine adding and deleting in one migration: + +```typescript +// Deploy 1: Add new field, keep old field optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) + +// Migration: convert old field to new field +export const convertToEnum = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.plan === undefined) { + await ctx.db.patch(team._id, { + plan: team.isPro ? "pro" : "basic", + isPro: undefined, + }); + } + }, +}); + +// Deploy 2: Remove isPro from schema, make plan required +``` + +### Splitting Nested Data Into a Separate Table + +```typescript +export const extractPreferences = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.preferences === undefined) return; + + const existing = await ctx.db + .query("userPreferences") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .first(); + + if (!existing) { + await ctx.db.insert("userPreferences", { + userId: user._id, + ...user.preferences, + }); + } + + await ctx.db.patch(user._id, { preferences: undefined }); + }, +}); +``` + +Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. + +### Cleaning Up Orphaned Documents + +```typescript +export const deleteOrphanedEmbeddings = migrations.define({ + table: "embeddings", + migrateOne: async (ctx, doc) => { + const chunk = await ctx.db + .query("chunks") + .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) + .first(); + + if (!chunk) { + await ctx.db.delete(doc._id); + } + }, +}); +``` + +## Migration Strategies for Zero Downtime + +During the migration window, your app must handle both old and new data formats. There are two main strategies. + +### Dual Write (Preferred) + +Write to both old and new structures. Read from the old structure until migration is complete. + +1. Deploy code that writes both formats, reads old format +2. Run migration on existing data +3. Deploy code that reads new format, still writes both +4. Deploy code that only reads and writes new format + +This is preferred because you can safely roll back at any point, the old format is always up to date. + +```typescript +// Bad: only writing to new structure before migration is done +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + await ctx.db.insert("teams", { + name: args.name, + plan: args.isPro ? "pro" : "basic", + }); + }, +}); + +// Good: writing to both structures during migration +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + const plan = args.isPro ? "pro" : "basic"; + await ctx.db.insert("teams", { + name: args.name, + isPro: args.isPro, + plan, + }); + }, +}); +``` + +### Dual Read + +Read both formats. Write only the new format. + +1. Deploy code that reads both formats (preferring new), writes only new format +2. Run migration on existing data +3. Deploy code that reads and writes only new format + +This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. + +```typescript +// Good: reading both formats, preferring new +function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { + if (team.plan !== undefined) return team.plan; + return team.isPro ? "pro" : "basic"; +} +``` + +## Small Table Shortcut + +For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: + +```typescript +import { internalMutation } from "./_generated/server"; + +export const backfillSmallTable = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("smallConfig").collect(); + for (const doc of docs) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: "default" }); + } + } + }, +}); +``` + +```bash +npx convex run migrations:backfillSmallTable +``` + +Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. + +## Verifying a Migration + +Query to check remaining unmigrated documents: + +```typescript +import { query } from "./_generated/server"; + +export const verifyMigration = query({ + handler: async (ctx) => { + const remaining = await ctx.db + .query("users") + .filter((q) => q.eq(q.field("role"), undefined)) + .take(10); + + return { + complete: remaining.length === 0, + sampleRemaining: remaining.map((u) => u._id), + }; + }, +}); +``` + +Or use the component's built-in status monitoring: + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +## Migration Checklist + +- [ ] Identify the breaking change and plan the multi-deploy workflow +- [ ] Update schema to allow both old and new formats +- [ ] Update code to handle both formats when reading +- [ ] Update code to write the new format for new documents +- [ ] Deploy widened schema and updated code +- [ ] Define migration using the `@convex-dev/migrations` component +- [ ] Test with `dryRun: true` +- [ ] Run migration and monitor status +- [ ] Verify all documents are migrated +- [ ] Update schema to require new format only +- [ ] Clean up code that handled old format +- [ ] Deploy final schema and code +- [ ] Remove migration code once confirmed stable + +## Common Pitfalls + +1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. +2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. +3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. +4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. +5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. +6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/.agent/skills/convex-migration-helper/agents/openai.yaml b/.agent/skills/convex-migration-helper/agents/openai.yaml new file mode 100644 index 00000000..c2a7fcc5 --- /dev/null +++ b/.agent/skills/convex-migration-helper/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Migration Helper" + short_description: "Plan and run safe Convex schema and data migrations." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#8B5CF6" + default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." + +policy: + allow_implicit_invocation: true diff --git a/.agent/skills/convex-migration-helper/assets/icon.svg b/.agent/skills/convex-migration-helper/assets/icon.svg new file mode 100644 index 00000000..fba7241a --- /dev/null +++ b/.agent/skills/convex-migration-helper/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agent/skills/convex-performance-audit/SKILL.md b/.agent/skills/convex-performance-audit/SKILL.md new file mode 100644 index 00000000..6ee0417f --- /dev/null +++ b/.agent/skills/convex-performance-audit/SKILL.md @@ -0,0 +1,143 @@ +--- +name: convex-performance-audit +description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. +--- + +# Convex Performance Audit + +Diagnose and fix performance problems in Convex applications, one problem class at a time. + +## When to Use + +- A Convex page or feature feels slow or expensive +- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts +- Low-freshness read paths are using reactivity where point-in-time reads would do +- OCC conflict errors or excessive mutation retries +- High subscription count or slow UI updates +- Functions approaching execution or transaction limits +- The same performance pattern needs fixing across sibling functions + +## When Not to Use + +- Initial Convex setup, auth setup, or component extraction +- Pure schema migrations with no performance goal +- One-off micro-optimizations without a user-visible or deployment-visible problem + +## Guardrails + +- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak +- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path +- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale + +## First Step: Gather Signals + +Start with the strongest signal available: + +1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. +2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. + - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. +3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. +4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. + +## Signal Routing + +After gathering signals, identify the problem class and read the matching reference file. + +| Signal | Reference | +|---|---| +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | + +Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. + +## Escalate Larger Fixes + +If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. + +Examples: + +- introducing digest or summary tables across multiple flows +- splitting documents to isolate frequently-updated fields +- reworking pagination or fetch strategy across several screens +- switching to a new index or denormalized field that needs migration-safe rollout + +When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. + +## Workflow + +### 1. Scope the problem + +Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. + +Write down: + +- entrypoint functions +- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` +- tables read +- tables written +- whether the path is high-read, high-write, or both + +### 2. Trace the full read and write set + +For each function in the path: + +1. Trace every `ctx.db.get()` and `ctx.db.query()` +2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` +3. Note foreign-key lookups, JS-side filtering, and full-document reads +4. Identify all sibling functions touching the same tables +5. Identify reactive stats, aggregates, or widgets rendered on the same page + +In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. + +### 3. Apply fixes from the relevant reference + +Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. + +Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. + +### 4. Fix sibling functions together + +When one function touching a table has a performance bug, audit sibling functions for the same pattern. + +After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. + +Examples: + +- If one list query switches from full docs to a digest table, inspect the other list queries for that table +- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk + +Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. + +### 5. Verify before finishing + +Confirm all of these: + +1. Results are the same as before, no dropped records +2. Eliminated reads or writes are no longer in the path where expected +3. Fallback behavior works when denormalized or indexed fields are missing +4. New writes avoid unnecessary invalidation when data is unchanged +5. Every relevant sibling reader and writer was inspected, not just the original function + +## Reference Files + +- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables +- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting +- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads +- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size + +Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. + +## Checklist + +- [ ] Gathered signals from insights, dashboard, or code audit +- [ ] Identified the problem class and read the matching reference +- [ ] Scoped one concrete user flow or function path +- [ ] Traced every read and write in that path +- [ ] Identified sibling functions touching the same tables +- [ ] Applied fixes from the reference, following the recommended fix order +- [ ] Fixed sibling functions consistently +- [ ] Verified behavior and confirmed no regressions diff --git a/.agent/skills/convex-performance-audit/agents/openai.yaml b/.agent/skills/convex-performance-audit/agents/openai.yaml new file mode 100644 index 00000000..9a21f387 --- /dev/null +++ b/.agent/skills/convex-performance-audit/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Performance Audit" + short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#EF4444" + default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." + +policy: + allow_implicit_invocation: true diff --git a/.agent/skills/convex-performance-audit/assets/icon.svg b/.agent/skills/convex-performance-audit/assets/icon.svg new file mode 100644 index 00000000..7ab9e09c --- /dev/null +++ b/.agent/skills/convex-performance-audit/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agent/skills/convex-performance-audit/references/function-budget.md b/.agent/skills/convex-performance-audit/references/function-budget.md new file mode 100644 index 00000000..c71d14cb --- /dev/null +++ b/.agent/skills/convex-performance-audit/references/function-budget.md @@ -0,0 +1,232 @@ +# Function Budget + +Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. + +## Core Principle + +Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. + +## Limits to Know + +These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. + +| Resource | Limit | +|---|---| +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | +| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | + +## Symptoms + +- "Function execution took too long" errors +- "Transaction too large" or read/write set size errors +- Slow queries that read many documents +- Client receiving large payloads that slow down page load +- `npx convex insights --details` showing high bytes read + +## Common Causes + +### Unbounded collection + +A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. + +### Large document reads on hot paths + +Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. + +### Mutation doing too much work + +A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. + +### Returning too much data to the client + +A query returning full documents when the client only needs a few fields. + +## Fix Order + +### 1. Bound your reads + +Never `.collect()` without a limit on a table that can grow unbounded. + +```ts +// Bad: unbounded read, breaks as the table grows +const messages = await ctx.db.query("messages").collect(); +``` + +```ts +// Good: paginate or limit +const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", channelId)) + .order("desc") + .take(50); +``` + +### 2. Read smaller shapes + +If the list page only needs title, author, and date, do not read full documents with rich content fields. + +Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. + +### 3. Break large mutations into batches + +If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. + +```ts +// Bad: one mutation updating every row +export const backfillAll = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("items").collect(); + for (const doc of docs) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + }, +}); +``` + +```ts +// Good: cursor-based batch processing +export const backfillBatch = internalMutation({ + args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, + handler: async (ctx, args) => { + const batchSize = args.batchSize ?? 100; + const result = await ctx.db + .query("items") + .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); + + for (const doc of result.page) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + } + + if (!result.isDone) { + await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { + cursor: result.continueCursor, + batchSize, + }); + } + }, +}); +``` + +### 4. Move heavy work to actions + +Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. + +Actions run outside the transaction and can call mutations to write results back. + +```ts +// Bad: heavy computation inside a mutation +export const processUpload = mutation({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.db.insert("results", result); + }, +}); +``` + +```ts +// Good: action for heavy work, mutation for the write +export const processUpload = action({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.runMutation(internal.results.store, { result }); + }, +}); +``` + +### 5. Trim return values + +Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. + +```ts +// Bad: returns full documents including large content fields +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("articles").take(20); + }, +}); +``` + +```ts +// Good: project to only the fields the client needs +export const list = query({ + handler: async (ctx) => { + const articles = await ctx.db.query("articles").take(20); + return articles.map((a) => ({ + _id: a._id, + title: a.title, + author: a.author, + createdAt: a._creationTime, + })); + }, +}); +``` + +### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions + +Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. + +```ts +// Bad: unnecessary overhead from ctx.runQuery inside a mutation +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await ctx.runQuery(api.users.getCurrentUser); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +```ts +// Good: plain helper function, no extra overhead +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await getCurrentUser(ctx); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. + +### 7. Avoid unnecessary `runAction` calls + +`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). + +```ts +// Bad: runAction overhead for no reason +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await ctx.runAction(internal.items.processOne, { item }); + } + }, +}); +``` + +```ts +// Good: plain function call +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await processOneItem(ctx, { item }); + } + }, +}); +``` + +## Verification + +1. No function execution or transaction size errors +2. `npx convex insights --details` shows reduced bytes read +3. Large mutations are batched and self-scheduling +4. Client payloads are reasonably sized for the UI they serve +5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible +6. Sibling functions with similar patterns were checked diff --git a/.agent/skills/convex-performance-audit/references/hot-path-rules.md b/.agent/skills/convex-performance-audit/references/hot-path-rules.md new file mode 100644 index 00000000..96a7b94e --- /dev/null +++ b/.agent/skills/convex-performance-audit/references/hot-path-rules.md @@ -0,0 +1,359 @@ +# Hot Path Rules + +Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. + +## Core Principle + +Every byte read or written multiplies with concurrency. + +Think: + +`cost x calls_per_second x 86400` + +In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. + +## Consistency Rule + +If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. + +Do this especially for: + +- multiple list queries over the same table +- multiple writers to the same table +- public browse and search queries over the same records +- helper functions reused by more than one endpoint + +## 1. Push Filters To Storage + +Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. + +Prefer: + +- `withIndex(...)` +- `.withSearchIndex(...)` for text search +- narrower tables +- summary tables + +before accepting a scan-plus-filter pattern. + +```ts +// Bad: scans then filters in JavaScript +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + const tasks = await ctx.db.query("tasks").collect(); + return tasks.filter((task) => task.status === "open"); + }, +}); +``` + +```ts +// Also bad: Convex .filter() does not push to storage either +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .filter((q) => q.eq(q.field("status"), "open")) + .collect(); + }, +}); +``` + +```ts +// Good: use an index so storage does the filtering +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .withIndex("by_status", (q) => q.eq("status", "open")) + .collect(); + }, +}); +``` + +### Migration rule for indexes + +New indexes on partially backfilled fields can create correctness bugs during rollout. + +Important Convex detail: + +`undefined !== false` + +If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. + +Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. + +If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. + +```ts +// Bad: optional booleans can miss older rows where the field is undefined +const projects = await ctx.db + .query("projects") + .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) + .order("desc") + .take(20); +``` + +```ts +// Good: switch hot-path reads only after the rollout is migration-safe +// See the migration helper skill for dual-read / backfill / cutover patterns. +``` + +### Check for redundant indexes + +Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. + +```ts +// Bad: two indexes where one would do +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team", ["team"]) + .index("by_team_and_user", ["team", "user"]) +``` + +```ts +// Good: single compound index serves both query patterns +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team_and_user", ["team", "user"]) +``` + +Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. + +## 2. Minimize Data Sources + +Trace every read. + +If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. + +### When to denormalize + +Denormalize when all of these are true: + +- the path is hot +- the joined document is much larger than the field you need +- many readers are paying that join cost repeatedly + +Useful mental model: + +`join_cost = rows_per_page x foreign_doc_size x pages_per_second` + +Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. + +### Fallback rule + +Denormalized data is an optimization. Live data is the correctness path. + +Rules: + +- If the denormalized field is missing or null, fall back to the live read +- Do not show placeholders instead of falling back +- In lookup maps, only include fully populated entries + +```ts +// Bad: missing denormalized data becomes a placeholder and blocks correctness +const ownerName = project.ownerName ?? "Unknown owner"; +``` + +```ts +// Good: denormalized data is an optimization, not the only source of truth +const ownerName = + project.ownerName ?? + (await ctx.db.get(project.ownerId))?.name ?? + null; +``` + +Bad lookup map pattern: + +```ts +const ownersById = { + [project.ownerId]: { ownerName: null }, +}; +``` + +That blocks fallback because the map says "I have data" when it does not. + +Good lookup map pattern: + +```ts +const ownersById = + project.ownerName !== undefined && project.ownerName !== null + ? { [project.ownerId]: { ownerName: project.ownerName } } + : {}; +``` + +### No denormalized copy yet + +Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. + +If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. + +Rollout order: + +1. Update schema +2. Update write path +3. Backfill +4. Switch read path + +## 3. Minimize Row Size + +Hot list pages should read the smallest document shape that still answers the UI. + +Prefer summary or digest tables over full source tables when: + +- the list page only needs a subset of fields +- source documents are large +- the query is high volume + +An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. + +Digest tables are a tradeoff, not a default: + +- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost +- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit + +```ts +// Bad: list page reads source docs, then joins owner data per row +const projects = await ctx.db + .query("projects") + .withIndex("by_public", (q) => q.eq("isPublic", true)) + .collect(); +``` + +```ts +// Good: list page reads the smaller digest shape first +const projects = await ctx.db + .query("projectDigests") + .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) + .order("desc") + .take(20); +``` + +## 4. Skip No-Op Writes + +No-op writes still cost work in Convex: + +- invalidation +- replication +- trigger execution +- downstream sync + +Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. + +Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. + +```ts +// Bad: patching unchanged values still triggers invalidation and downstream work +await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, +}); +``` + +```ts +// Good: only write when something actually changed +if (settings.theme !== args.theme || settings.locale !== args.locale) { + await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, + }); +} +``` + +## 5. Match Consistency To Read Patterns + +Choose read strategy based on traffic shape. + +### High-read, low-write + +Examples: + +- public browse pages +- search results +- landing pages +- directory listings + +Prefer: + +- point-in-time reads where appropriate +- explicit refresh +- local state for pagination +- caching where appropriate + +Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. + +### High-read, high-write + +Examples: + +- collaborative editors +- live dashboards +- presence-heavy views + +Reactive queries may be worth the ongoing cost. + +## Convex-Specific Notes + +### Reactive queries + +Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. + +On the client: + +- `useQuery` creates a live subscription +- `usePaginatedQuery` creates a live subscription per page + +For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. + +### Point-in-time reads + +Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. + +Use them for: + +- aggregate snapshots +- reports +- low-churn listings +- pages where explicit refresh is fine + +### Triggers and fan-out + +Triggers fire on every write, including writes that did not materially change the document. + +When a write exists only to keep derived state in sync: + +- diff before patching +- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate + +### Aggregates + +Reactive global counts invalidate frequently on busy tables. + +Prefer: + +- one-shot aggregate fetches +- periodic recomputation +- precomputed summary rows + +for global stats that do not need live updates every second. + +### Backfills + +For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. + +Deploy code that can handle both states before running the backfill. + +During the gap: + +- writes should populate the new shape +- reads should fall back safely + +## Verification + +Before closing the audit, confirm: + +1. Same results as before, no dropped records +2. The removed table or lookup is no longer in the hot-path read set +3. Tests or validation cover fallback behavior +4. Migration safety is preserved while fields or indexes are unbackfilled +5. Sibling functions were fixed consistently diff --git a/.agent/skills/convex-performance-audit/references/occ-conflicts.md b/.agent/skills/convex-performance-audit/references/occ-conflicts.md new file mode 100644 index 00000000..a96d0466 --- /dev/null +++ b/.agent/skills/convex-performance-audit/references/occ-conflicts.md @@ -0,0 +1,126 @@ +# OCC Conflict Resolution + +Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. + +## Core Principle + +Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. + +## Symptoms + +- OCC conflict errors in deployment logs or health page +- Mutations retrying multiple times before succeeding +- User-visible latency spikes on write-heavy pages +- `npx convex insights --details` showing high conflict rates + +## Common Causes + +### Hot documents + +Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. + +### Broad read sets causing false conflicts + +A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. + +### Fan-out from triggers or cascading writes + +A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. + +Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. + +### Write-then-read chains + +A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. + +## Fix Order + +### 1. Reduce read set size + +Narrower reads mean fewer false conflicts. + +```ts +// Bad: broad scan creates a wide conflict surface +const allTasks = await ctx.db.query("tasks").collect(); +const mine = allTasks.filter((t) => t.ownerId === userId); +``` + +```ts +// Good: indexed query touches only relevant documents +const mine = await ctx.db + .query("tasks") + .withIndex("by_owner", (q) => q.eq("ownerId", userId)) + .collect(); +``` + +### 2. Split hot documents + +When many writers target the same document, split the contention point. + +```ts +// Bad: every vote increments the same counter document +const counter = await ctx.db.get(pollCounterId); +await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); +``` + +```ts +// Good: shard the counter across multiple documents, aggregate on read +const shardIndex = Math.floor(Math.random() * SHARD_COUNT); +const shardId = shardIds[shardIndex]; +const shard = await ctx.db.get(shardId); +await ctx.db.patch(shardId, { count: shard!.count + 1 }); +``` + +Aggregate the shards in a query or scheduled job when you need the total. + +### 3. Skip no-op writes + +Writes that do not change data still participate in conflict detection and trigger invalidation. + +```ts +// Bad: patches even when nothing changed +await ctx.db.patch(doc._id, { status: args.status }); +``` + +```ts +// Good: only write when the value actually differs +if (doc.status !== args.status) { + await ctx.db.patch(doc._id, { status: args.status }); +} +``` + +### 4. Move non-critical work to scheduled functions + +If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. + +```ts +// Bad: analytics update in the same transaction as the user action +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +``` + +```ts +// Good: schedule the bookkeeping so the primary transaction is smaller +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { + event: "action", + userId, +}); +``` + +### 5. Combine competing writes + +If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. + +Do not introduce artificial locks or queues unless the above steps have been tried first. + +## Related: Invalidation Scope + +Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. + +## Verification + +1. OCC conflict rate has dropped in insights or dashboard +2. Mutation latency is lower and more consistent +3. No data correctness regressions from splitting or scheduling changes +4. Sibling writers to the same hot documents were fixed consistently diff --git a/.agent/skills/convex-performance-audit/references/subscription-cost.md b/.agent/skills/convex-performance-audit/references/subscription-cost.md new file mode 100644 index 00000000..ae7d1adb --- /dev/null +++ b/.agent/skills/convex-performance-audit/references/subscription-cost.md @@ -0,0 +1,252 @@ +# Subscription Cost + +Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. + +## Core Principle + +Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: + +`subscriptions x invalidation_frequency x query_cost` + +Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. + +## Symptoms + +- Dashboard shows high active subscription count +- UI feels sluggish or laggy despite fast individual queries +- React profiling shows frequent re-renders from Convex state +- Pages with many components each running their own `useQuery` +- Paginated lists where every loaded page stays subscribed + +## Common Causes + +### Reactive queries on low-freshness flows + +Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. + +### Overly broad queries + +A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. + +### Too many subscriptions per page + +A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. + +### Paginated queries keeping all pages live + +`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. + +### Frequently-updated fields on widely-read documents + +A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. + +## Fix Order + +### 1. Use point-in-time reads when live updates are not valuable + +Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. + +Consider a point-in-time read instead when all of these are true: + +- the flow is high-read +- the underlying data changes less often than users need to see +- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable + +Possible implementations depend on environment: + +- a server-rendered fetch +- a framework helper like `fetchQuery` +- a point-in-time client read such as `ConvexHttpClient.query()` + +```ts +// Reactive by default when fresh live data matters +function TeamPresence() { + const presence = useQuery(api.teams.livePresence, { teamId }); + return ; +} +``` + +```ts +// Point-in-time read when explicit refresh is acceptable +import { ConvexHttpClient } from "convex/browser"; + +const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); + +function SnapshotView() { + const [items, setItems] = useState([]); + + useEffect(() => { + client.query(api.items.snapshot).then(setItems); + }, []); + + return ; +} +``` + +Good candidates for point-in-time reads: + +- aggregate snapshots +- reports +- low-churn listings +- flows where explicit refresh is already acceptable + +Keep reactive for: + +- collaborative editing +- live dashboards +- presence-heavy views +- any surface where users expect fresh changes to appear automatically + +### 2. Batch related data into fewer queries + +Instead of N components each fetching their own related data, fetch it in a single query. + +```ts +// Bad: each card fetches its own author +function ProjectCard({ project }: { project: Project }) { + const author = useQuery(api.users.get, { id: project.authorId }); + return ; +} +``` + +```ts +// Good: parent query returns projects with author names included +function ProjectList() { + const projects = useQuery(api.projects.listWithAuthors); + return projects?.map((p) => ( + + )); +} +``` + +This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. + +This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. + +### 3. Use skip to avoid unnecessary subscriptions + +The `"skip"` value prevents a subscription from being created when the arguments are not ready. + +```ts +// Bad: subscribes with undefined args, wastes a subscription slot +const profile = useQuery(api.users.getProfile, { userId: selectedId! }); +``` + +```ts +// Good: skip when there is nothing to fetch +const profile = useQuery( + api.users.getProfile, + selectedId ? { userId: selectedId } : "skip", +); +``` + +### 4. Isolate frequently-updated fields into separate documents + +If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. + +```ts +// Bad: lastSeen lives on the user doc, every heartbeat invalidates +// every query that reads this user +const users = defineTable({ + name: v.string(), + email: v.string(), + lastSeen: v.number(), +}); +``` + +```ts +// Good: lastSeen lives in a separate heartbeat doc +const users = defineTable({ + name: v.string(), + email: v.string(), + heartbeatId: v.id("heartbeats"), +}); + +const heartbeats = defineTable({ + lastSeen: v.number(), +}); +``` + +Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. + +For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. + +### 5. Use the aggregate component for counts and sums + +Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. + +Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. + +If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. + +### 6. Narrow query read sets + +Queries that return less data and touch fewer documents invalidate less often. + +```ts +// Bad: returns all fields, invalidates on any field change +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("projects").collect(); + }, +}); +``` + +```ts +// Good: use a digest table with only the fields the list needs +export const listDigests = query({ + handler: async (ctx) => { + return await ctx.db.query("projectDigests").collect(); + }, +}); +``` + +Writes to fields not in the digest table do not invalidate the digest query. + +### 7. Remove `Date.now()` from queries + +Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. + +```ts +// Bad: Date.now() defeats query caching and causes frequent re-evaluation +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) + .take(100); +``` + +```ts +// Good: use a boolean field updated by a scheduled function +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_is_released", (q) => q.eq("isReleased", true)) + .take(100); +``` + +If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. + +### 8. Consider pagination strategy + +For long lists where users scroll through many pages: + +- If the data does not need live updates, use point-in-time fetching with manual "load more" +- If it does need live updates, accept the subscription cost but limit the number of loaded pages +- Consider whether older pages can be unloaded as the user scrolls forward + +### 9. Separate backend cost from UI churn + +If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. + +Treat this as a UX problem first when: + +- the underlying query is already reasonably cheap +- the complaint is flicker, loading flashes, or re-render churn +- live updates are still desirable once fresh data arrives + +## Verification + +1. Subscription count in dashboard is lower for the affected pages +2. UI responsiveness has improved +3. React profiling shows fewer unnecessary re-renders +4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily +5. Sibling pages with similar patterns were updated consistently diff --git a/.agent/skills/convex-quickstart/SKILL.md b/.agent/skills/convex-quickstart/SKILL.md new file mode 100644 index 00000000..369a6c9b --- /dev/null +++ b/.agent/skills/convex-quickstart/SKILL.md @@ -0,0 +1,337 @@ +--- +name: convex-quickstart +description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. +--- + +# Convex Quickstart + +Set up a working Convex project as fast as possible. + +## When to Use + +- Starting a brand new project with Convex +- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app +- Scaffolding a Convex app for prototyping + +## When Not to Use + +- The project already has Convex installed and `convex/` exists - just start building +- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill + +## Workflow + +1. Determine the starting point: new project or existing app +2. If new project, pick a template and scaffold with `npm create convex@latest` +3. If existing app, install `convex` and wire up the provider +4. Run `npx convex dev` to connect a deployment and start the dev loop +5. Verify the setup works + +## Path 1: New Project (Recommended) + +Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. + +### Pick a template + +| Template | Stack | +|----------|-------| +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | + +If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. + +You can also use any GitHub repo as a template: + +```bash +npm create convex@latest my-app -- -t owner/repo +npm create convex@latest my-app -- -t owner/repo#branch +``` + +### Scaffold the project + +Always pass the project name and template flag to avoid interactive prompts: + +```bash +npm create convex@latest my-app -- -t react-vite-shadcn +cd my-app +npm install +``` + +The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. + +To scaffold in the current directory (if it is empty): + +```bash +npm create convex@latest . -- -t react-vite-shadcn +npm install +``` + +### Start the dev loop + +`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. + +**Ask the user to run this themselves:** + +Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: +- Create a Convex project and dev deployment +- Write the deployment URL to `.env.local` +- Create the `convex/` directory with generated types +- Watch for changes and sync continuously + +The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. + +**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. + +### Start the frontend + +The user should also run the frontend dev server in a separate terminal: + +```bash +npm run dev +``` + +Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. + +### What you get + +After scaffolding, the project structure looks like: + +``` +my-app/ + convex/ # Backend functions and schema + _generated/ # Auto-generated types (check this into git) + schema.ts # Database schema (if template includes one) + src/ # Frontend code (or app/ for Next.js) + package.json + .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL +``` + +The template already has: +- `ConvexProvider` wired into the app root +- Correct env var names for the framework +- Tailwind and shadcn/ui ready (for shadcn templates) +- Auth provider configured (for auth templates) + +You are ready to start adding schema, functions, and UI. + +## Path 2: Add Convex to an Existing App + +Use this when the user already has a frontend project and wants to add Convex as the backend. + +### Install + +```bash +npm install convex +``` + +### Initialize and start dev loop + +Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. + +### Wire up the provider + +The Convex client must wrap the app at the root. The setup varies by framework. + +Create the `ConvexReactClient` at module scope, not inside a component: + +```tsx +// Bad: re-creates the client on every render +function App() { + const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + return ...; +} + +// Good: created once at module scope +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); +function App() { + return ...; +} +``` + +#### React (Vite) + +```tsx +// src/main.tsx +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import App from "./App"; + +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + +createRoot(document.getElementById("root")!).render( + + + + + , +); +``` + +#### Next.js (App Router) + +```tsx +// app/ConvexClientProvider.tsx +"use client"; + +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import { ReactNode } from "react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +export function ConvexClientProvider({ children }: { children: ReactNode }) { + return {children}; +} +``` + +```tsx +// app/layout.tsx +import { ConvexClientProvider } from "./ConvexClientProvider"; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} +``` + +#### Other frameworks + +For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: + +- [Vue](https://docs.convex.dev/quickstart/vue) +- [Svelte](https://docs.convex.dev/quickstart/svelte) +- [React Native](https://docs.convex.dev/quickstart/react-native) +- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) +- [Remix](https://docs.convex.dev/quickstart/remix) +- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) + +### Environment variables + +The env var name depends on the framework: + +| Framework | Variable | +|-----------|----------| +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | +| React Native | `EXPO_PUBLIC_CONVEX_URL` | + +`npx convex dev` writes the correct variable to `.env.local` automatically. + +## Agent Mode (Cloud-Based Agents) + +When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. + +Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: + +```bash +CONVEX_AGENT_MODE=anonymous npx convex dev +``` + +This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. + +## Verify the Setup + +After setup, confirm everything is working: + +1. The user confirms `npx convex dev` is running without errors +2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` +3. `.env.local` contains the deployment URL + +## Writing Your First Function + +Once the project is set up, create a schema and a query to verify the full loop works. + +`convex/schema.ts`: + +```ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + tasks: defineTable({ + text: v.string(), + completed: v.boolean(), + }), +}); +``` + +`convex/tasks.ts`: + +```ts +import { query, mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("tasks").collect(); + }, +}); + +export const create = mutation({ + args: { text: v.string() }, + handler: async (ctx, args) => { + await ctx.db.insert("tasks", { text: args.text, completed: false }); + }, +}); +``` + +Use in a React component (adjust the import path based on your file location relative to `convex/`): + +```tsx +import { useQuery, useMutation } from "convex/react"; +import { api } from "../convex/_generated/api"; + +function Tasks() { + const tasks = useQuery(api.tasks.list); + const create = useMutation(api.tasks.create); + + return ( +
+ + {tasks?.map((t) =>
{t.text}
)} +
+ ); +} +``` + +## Development vs Production + +Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. + +When ready to ship, deploy to production: + +```bash +npx convex deploy +``` + +This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. + +## Next Steps + +- Add authentication: use the `convex-setup-auth` skill +- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) +- Build components: use the `convex-create-component` skill +- Plan a migration: use the `convex-migration-helper` skill +- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) +- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) + +## Checklist + +- [ ] Determined starting point: new project or existing app +- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template +- [ ] If existing app: installed `convex` and wired up the provider +- [ ] User has `npx convex dev` running and connected to a deployment +- [ ] `convex/_generated/` directory exists with types +- [ ] `.env.local` has the deployment URL +- [ ] Verified a basic query/mutation round-trip works diff --git a/.agent/skills/convex-quickstart/agents/openai.yaml b/.agent/skills/convex-quickstart/agents/openai.yaml new file mode 100644 index 00000000..a51a6d09 --- /dev/null +++ b/.agent/skills/convex-quickstart/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Quickstart" + short_description: "Start a new Convex app or add Convex to an existing frontend." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#F97316" + default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." + +policy: + allow_implicit_invocation: true diff --git a/.agent/skills/convex-quickstart/assets/icon.svg b/.agent/skills/convex-quickstart/assets/icon.svg new file mode 100644 index 00000000..d83a73f3 --- /dev/null +++ b/.agent/skills/convex-quickstart/assets/icon.svg @@ -0,0 +1,4 @@ + diff --git a/.agent/skills/convex-setup-auth/SKILL.md b/.agent/skills/convex-setup-auth/SKILL.md new file mode 100644 index 00000000..5c0c994a --- /dev/null +++ b/.agent/skills/convex-setup-auth/SKILL.md @@ -0,0 +1,113 @@ +--- +name: convex-setup-auth +description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. +--- + +# Convex Authentication Setup + +Implement secure authentication in Convex with user management and access control. + +## When to Use + +- Setting up authentication for the first time +- Implementing user management (users table, identity mapping) +- Creating authentication helper functions +- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) + +## First Step: Choose the Auth Provider + +Convex supports multiple authentication approaches. Do not assume a provider. + +Before writing setup code: + +1. Ask the user which auth solution they want, unless the repository already makes it obvious +2. If the repo already uses a provider, continue with that provider unless the user wants to switch +3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding + +Common options: + +- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex +- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features +- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically +- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 +- Custom JWT provider - use when integrating an existing auth system not covered above + +Look for signals in the repo before asking: + +- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages +- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components +- Environment variables that clearly point at a provider + +## After Choosing a Provider + +Read the provider's official guide and the matching local reference file: + +- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` +- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` +- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` +- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` + +The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. + +Use those sources for: + +- package installation +- client provider wiring +- environment variables +- `convex/auth.config.ts` setup +- login and logout UI patterns +- framework-specific setup for React, Vite, or Next.js + +For shared auth behavior, use the official Convex docs as the source of truth: + +- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` +- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage +- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance +- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth + +Do not invent a provider-agnostic user sync pattern from memory. +For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. +For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. + +Do not invent provider-specific setup from memory when the docs are available. +Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. + +## Workflow + +1. Determine the provider, either by asking the user or inferring from the repo +2. Ask whether the user wants local-only setup or production-ready setup now +3. Read the matching provider reference file +4. Follow the official provider docs for current setup details +5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns +6. Only add app-level user storage if the docs and app requirements call for it +7. Add authorization checks for ownership, roles, or team access only where the app needs them +8. Verify login state, protected queries, environment variables, and production configuration if requested + +If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. +For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. +If the environment has browser automation tools, you can use them. +If it does not, give the user a short manual validation checklist instead. + +## Reference Files + +### Provider References + +- `references/convex-auth.md` +- `references/clerk.md` +- `references/workos-authkit.md` +- `references/auth0.md` + +## Checklist + +- [ ] Chosen the correct auth provider before writing setup code +- [ ] Read the relevant provider reference file +- [ ] Asked whether the user wants local-only setup or production-ready setup +- [ ] Used the official provider docs for provider-specific wiring +- [ ] Used the official Convex docs for shared auth behavior and authorization patterns +- [ ] Only added app-level user storage if the app actually needs it +- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth +- [ ] Added authentication checks in protected backend functions +- [ ] Added authorization checks where the app actually needs them +- [ ] Clear error messages ("Not authenticated", "Unauthorized") +- [ ] Client auth provider configured for the chosen provider +- [ ] If requested, production auth setup is covered too diff --git a/.agent/skills/convex-setup-auth/agents/openai.yaml b/.agent/skills/convex-setup-auth/agents/openai.yaml new file mode 100644 index 00000000..d1c90a14 --- /dev/null +++ b/.agent/skills/convex-setup-auth/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Setup Auth" + short_description: "Set up Convex auth, user identity mapping, and access control." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#2563EB" + default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." + +policy: + allow_implicit_invocation: true diff --git a/.agent/skills/convex-setup-auth/assets/icon.svg b/.agent/skills/convex-setup-auth/assets/icon.svg new file mode 100644 index 00000000..4917dbb4 --- /dev/null +++ b/.agent/skills/convex-setup-auth/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agent/skills/convex-setup-auth/references/auth0.md b/.agent/skills/convex-setup-auth/references/auth0.md new file mode 100644 index 00000000..9c729c5a --- /dev/null +++ b/.agent/skills/convex-setup-auth/references/auth0.md @@ -0,0 +1,116 @@ +# Auth0 + +Official docs: + +- https://docs.convex.dev/auth/auth0 +- https://auth0.github.io/auth0-cli/ +- https://auth0.github.io/auth0-cli/auth0_apps_create.html + +Use this when the app already uses Auth0 or the user wants Auth0 specifically. + +## Workflow + +1. Confirm the user wants Auth0 +2. Determine the app framework and whether Auth0 is already partly set up +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and Auth0 guides before making changes +5. Ask whether they want the fastest setup path by installing the Auth0 CLI +6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI +7. If they do not want the CLI path, use the Auth0 dashboard path instead +8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up +9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID +10. Set environment variables for local and production environments +11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +12. Gate Convex-backed UI with Convex auth state +13. Try to verify Convex reports the user as authenticated after Auth0 login +14. If the refresh-token path fails, stop improvising and send the user back to the official docs +15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered + +## What To Do + +- Read the official Convex and Auth0 guide before writing setup code +- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet +- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" +- Make sure the app has already completed the relevant Auth0 quickstart for its frontend +- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` +- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated + +## Key Setup Areas + +- install the Auth0 SDK for the app's framework +- configure `convex/auth.config.ts` with the Auth0 domain and client ID +- set environment variables for local and production environments +- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +- use Convex auth state when gating Convex-backed UI + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- frontend app entry or provider wrapper +- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` +- Auth0 environment variables commonly include: + - `AUTH0_DOMAIN` + - `AUTH0_CLIENT_ID` + - `VITE_AUTH0_DOMAIN` + - `VITE_AUTH0_CLIENT_ID` + +## Concrete Steps + +1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework +2. Ask whether the user wants the Auth0 CLI path +3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` +4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app +5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard +6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard +7. Install the Auth0 SDK for the app's framework +8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID +9. Set frontend and backend environment variables +10. Wrap the app in `Auth0Provider` +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` +12. Run the normal Convex dev or deploy flow after backend config changes +13. Try the official provider config shown in the Convex docs +14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now +15. Only claim success if the user can sign in and Convex recognizes the authenticated session +16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too + +## Gotchas + +- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch +- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant +- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard +- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced +- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end +- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled +- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation +- Keep dev and prod tenants separate if the project uses different Auth0 environments +- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. +- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. +- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. +- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered +- Verify production environment variables and redirect settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the Auth0 login flow +- Verify Convex-authenticated UI renders only after Convex auth state is ready +- Verify protected Convex queries succeed after login +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- Verify the Auth0 app settings match the real local callback and logout URLs during development +- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully +- If production-ready setup was requested, verify the production Auth0 configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Auth0 +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Complete the relevant Auth0 frontend setup +- [ ] Configure `convex/auth.config.ts` +- [ ] Set environment variables +- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs +- [ ] If requested, configure the production deployment too diff --git a/.agent/skills/convex-setup-auth/references/clerk.md b/.agent/skills/convex-setup-auth/references/clerk.md new file mode 100644 index 00000000..7dbde194 --- /dev/null +++ b/.agent/skills/convex-setup-auth/references/clerk.md @@ -0,0 +1,113 @@ +# Clerk + +Official docs: + +- https://docs.convex.dev/auth/clerk +- https://clerk.com/docs/guides/development/integrations/databases/convex + +Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. + +## Workflow + +1. Confirm the user wants Clerk +2. Make sure the user has a Clerk account and a Clerk application +3. Determine the app framework: + - React + - Next.js + - TanStack Start +4. Ask whether the user wants local-only setup or production-ready setup now +5. Gather the Clerk keys and the Clerk Frontend API URL +6. Follow the correct framework section in the official docs +7. Complete the backend and client wiring +8. Verify Convex reports the user as authenticated after login +9. If the user wants production-ready setup, make sure the production Clerk config is also covered + +## What To Do + +- Read the official Convex and Clerk guide before writing setup code +- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application +- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active +- Match the guide to the app's framework, usually React, Next.js, or TanStack Start +- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` + +## Key Setup Areas + +- install the Clerk SDK for the framework in use +- configure `convex/auth.config.ts` with the Clerk issuer domain +- set the required Clerk environment variables +- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` +- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- React or Vite client entry such as `src/main.tsx` +- Next.js client wrapper for Convex if using App Router +- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` +- Clerk app creation page: `https://dashboard.clerk.com/apps/new` +- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` +- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` +- Clerk environment variables: + - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs + - `CLERK_FRONTEND_API_URL` in the Clerk docs + - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps + - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps + - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required + +`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. + +## Concrete Steps + +1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` +2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` +3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed +4. Open `https://dashboard.clerk.com/apps/setup/convex` +5. Activate the Convex integration in Clerk if it is not already active +6. Copy the Clerk Frontend API URL shown there +7. Install the Clerk package for the app's framework +8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens +9. Set the publishable key in the frontend environment +10. Set the issuer domain or Frontend API URL so Convex can validate the JWT +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` +12. Wrap the app in `ClerkProvider` +13. Use Convex auth helpers for authenticated rendering +14. Run the normal Convex dev or deploy flow after updating backend auth config +15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too + +## Gotchas + +- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render +- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper +- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config +- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. +- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. +- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. +- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. +- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` +- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included +- Verify production redirect URLs and any production Clerk domain values before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can sign in with Clerk +- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in +- Verify `useConvexAuth()` reaches the authenticated state after Clerk login +- Verify protected Convex queries run successfully inside authenticated UI +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- If production-ready setup was requested, verify the production Clerk configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Clerk +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Follow the correct framework section in the official guide +- [ ] Set Clerk environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify Convex authenticated state after login +- [ ] If requested, configure the production deployment too diff --git a/.agent/skills/convex-setup-auth/references/convex-auth.md b/.agent/skills/convex-setup-auth/references/convex-auth.md new file mode 100644 index 00000000..d4824d24 --- /dev/null +++ b/.agent/skills/convex-setup-auth/references/convex-auth.md @@ -0,0 +1,143 @@ +# Convex Auth + +Official docs: https://docs.convex.dev/auth/convex-auth +Setup guide: https://labs.convex.dev/auth/setup + +Use this when the user wants auth handled directly in Convex rather than through a third-party provider. + +## Workflow + +1. Confirm the user wants Convex Auth specifically +2. Determine which sign-in methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords and password reset +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the Convex Auth setup guide before writing code +5. Make sure the project has a configured Convex deployment: + - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set + - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing +6. Install the auth packages: + - `npm install @convex-dev/auth @auth/core@0.37.0` +7. Run the initialization command: + - `npx @convex-dev/auth` +8. Confirm the initializer created: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +9. Add the required `authTables` to `convex/schema.ts` +10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` +11. Configure at least one auth method in `convex/auth.ts` +12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code +13. Verify the client can sign in successfully +14. Verify Convex receives authenticated identity in backend functions +15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well +16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex + +## What This Reference Is For + +- choosing Convex Auth as the default provider for a new Convex app +- understanding whether the app wants magic links, OTPs, OAuth, or passwords +- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior + +## What To Do + +- Read the Convex Auth setup guide before writing setup code +- Follow the setup flow from the docs rather than recreating it from memory +- If the app is new, consider starting from the official starter flow instead of hand-wiring everything +- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra + +## Concrete Steps + +1. Install `@convex-dev/auth` and `@auth/core@0.37.0` +2. Run `npx convex dev` if the project does not already have a configured deployment +3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment +4. Run `npx @convex-dev/auth` +5. Confirm the generated auth setup is present before continuing: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +6. Add `authTables` to `convex/schema.ts` +7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry +8. Configure the selected auth methods in `convex/auth.ts` +9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed +10. Verify login locally +11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment + +## Expected Files and Decisions + +- `convex/schema.ts` +- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file +- generated Convex Auth setup produced by `npx @convex-dev/auth` +- an existing configured Convex deployment, or the ability to create one with `npx convex dev` +- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods + +- Decide whether the user is creating a new app or adding auth to an existing app +- For a new app, prefer the official starter flow instead of rebuilding setup by hand +- Decide which auth methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords +- Decide whether the user wants local-only setup or production-ready setup now +- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough + +## Gotchas + +- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. +- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. +- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. +- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. +- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. +- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. +- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. +- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. +- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. +- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment +- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Human Handoff + +If `npx convex dev` or deployment setup requires human input: + +- stop and explain exactly what the user needs to do +- say why that step is required +- resume the auth setup immediately after the user confirms it is done + +## Validation + +- Verify the user can complete a sign-in flow +- Offer to validate sign up, sign out, and sign back in with the configured auth method +- If browser automation is available in the environment, you can do this directly +- If browser automation is not available, give the user a short manual validation checklist instead +- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions +- Verify protected UI only renders after Convex-authenticated state is ready +- Verify environment variables and redirect settings match the current app environment +- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in +- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed +- If production-ready setup was requested, verify the production deployment is also configured correctly + +## Checklist + +- [ ] Confirm the user wants Convex Auth specifically +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Ensure a Convex deployment is configured before running auth initialization +- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` +- [ ] Run `npx convex dev` first if needed +- [ ] Run `npx @convex-dev/auth` +- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created +- [ ] Follow the setup guide for package install and wiring +- [ ] Add `authTables` to `convex/schema.ts` +- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` +- [ ] Configure at least one auth method in `convex/auth.ts` +- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes +- [ ] Confirm which sign-in methods the app needs +- [ ] Verify the client can sign in and the backend receives authenticated identity +- [ ] Offer end-to-end validation of sign up, sign out, and sign back in +- [ ] If requested, configure the production deployment too +- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.agent/skills/convex-setup-auth/references/workos-authkit.md b/.agent/skills/convex-setup-auth/references/workos-authkit.md new file mode 100644 index 00000000..038cb9f3 --- /dev/null +++ b/.agent/skills/convex-setup-auth/references/workos-authkit.md @@ -0,0 +1,114 @@ +# WorkOS AuthKit + +Official docs: + +- https://docs.convex.dev/auth/authkit/ +- https://docs.convex.dev/auth/authkit/add-to-app +- https://docs.convex.dev/auth/authkit/auto-provision + +Use this when the app already uses WorkOS or the user wants AuthKit specifically. + +## Workflow + +1. Confirm the user wants WorkOS AuthKit +2. Determine whether they want: + - a Convex-managed WorkOS team + - an existing WorkOS team +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and WorkOS AuthKit guide +5. Create or update `convex.json` for the app's framework and real local port +6. Follow the correct branch of the setup flow based on that choice +7. Configure the required WorkOS environment variables +8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs +9. Wire the client provider and callback flow +10. Verify authenticated requests reach Convex +11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too +12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex + +## What To Do + +- Read the official Convex and WorkOS AuthKit guide before writing setup code +- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team +- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra +- Follow the current setup flow from the docs instead of relying on older examples + +## Key Setup Areas + +- package installation for the app's framework +- `convex.json` with the `authKit` section for dev, and preview or prod if needed +- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration +- `convex/auth.config.ts` wiring for WorkOS-issued JWTs +- client provider setup and token flow into Convex +- login callback and redirect configuration + +## Files and Env Vars To Expect + +- `convex.json` +- `convex/auth.config.ts` +- frontend auth provider wiring +- callback or redirect route setup where the framework requires it +- WorkOS environment variables commonly include: + - `WORKOS_CLIENT_ID` + - `WORKOS_API_KEY` + - `WORKOS_COOKIE_PASSWORD` + - `VITE_WORKOS_CLIENT_ID` + - `VITE_WORKOS_REDIRECT_URI` + - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` + +For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. + +## Concrete Steps + +1. Choose Convex-managed or existing WorkOS team +2. Create or update `convex.json` with the `authKit` section for the framework in use +3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port +4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow +5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` +6. Create or update `convex/auth.config.ts` for WorkOS JWT validation +7. Run the normal Convex dev or deploy flow so backend config is synced +8. Wire the WorkOS client provider in the app +9. Configure callback and redirect handling +10. Verify the user can sign in and return to the app +11. Verify Convex sees the authenticated user after login +12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too + +## Gotchas + +- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious +- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys +- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex +- Do not mix dev and prod WorkOS credentials or redirect URIs +- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it +- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. +- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. +- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. +- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. +- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered +- Verify the production redirect and callback settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the login flow and return to the app +- Verify the callback URL matches the real frontend port in local dev +- Verify Convex receives authenticated requests after login +- Verify `convex.json` matches the framework and chosen WorkOS setup path +- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path +- Verify environment variables differ correctly between local and production where needed +- If production-ready setup was requested, verify the production WorkOS configuration is also covered + +## Checklist + +- [ ] Confirm the user wants WorkOS AuthKit +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Choose Convex-managed or existing WorkOS team +- [ ] Create or update `convex.json` +- [ ] Configure WorkOS environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify authenticated requests reach Convex after login +- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-create-component/SKILL.md b/.agents/skills/convex-create-component/SKILL.md new file mode 100644 index 00000000..effe01fa --- /dev/null +++ b/.agents/skills/convex-create-component/SKILL.md @@ -0,0 +1,411 @@ +--- +name: convex-create-component +description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. +--- + +# Convex Create Component + +Create reusable Convex components with clear boundaries and a small app-facing API. + +## When to Use + +- Creating a new Convex component in an existing app +- Extracting reusable backend logic into a component +- Building a third-party integration that should own its own tables and workflows +- Packaging Convex functionality for reuse across multiple apps + +## When Not to Use + +- One-off business logic that belongs in the main app +- Thin utilities that do not need Convex tables or functions +- App-level orchestration that should stay in `convex/` +- Cases where a normal TypeScript library is enough + +## Workflow + +1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. +2. Choose the shape using the decision tree below and read the matching reference file. +3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. +4. Make a short plan for: + - what tables the component owns + - what public functions it exposes + - what data must be passed in from the app (auth, env vars, parent IDs) + - what stays in the app as wrappers or HTTP mounts +5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. +6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. +7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. +8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. +9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. +10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. + +## Choose the Shape + +Ask the user, then pick one path: + +| Goal | Shape | Reference | +|------|-------|-----------| +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | + +Read exactly one reference file before proceeding. + +## Default Approach + +Unless the user explicitly wants an npm package, default to a local component: + +- Put it under `convex/components//` +- Define it with `defineComponent(...)` in its own `convex.config.ts` +- Install it from the app's `convex/convex.config.ts` with `app.use(...)` +- Let `npx convex dev` generate the component's own `_generated/` files + +## Component Skeleton + +A minimal local component with a table and two functions, plus the app wiring. + +```ts +// convex/components/notifications/convex.config.ts +import { defineComponent } from "convex/server"; + +export default defineComponent("notifications"); +``` + +```ts +// convex/components/notifications/schema.ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notifications: defineTable({ + userId: v.string(), + message: v.string(), + read: v.boolean(), + }).index("by_user", ["userId"]), +}); +``` + +```ts +// convex/components/notifications/lib.ts +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server.js"; + +export const send = mutation({ + args: { userId: v.string(), message: v.string() }, + returns: v.id("notifications"), + handler: async (ctx, args) => { + return await ctx.db.insert("notifications", { + userId: args.userId, + message: args.message, + read: false, + }); + }, +}); + +export const listUnread = query({ + args: { userId: v.string() }, + returns: v.array( + v.object({ + _id: v.id("notifications"), + _creationTime: v.number(), + userId: v.string(), + message: v.string(), + read: v.boolean(), + }) + ), + handler: async (ctx, args) => { + return await ctx.db + .query("notifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .filter((q) => q.eq(q.field("read"), false)) + .collect(); + }, +}); +``` + +```ts +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import notifications from "./components/notifications/convex.config.js"; + +const app = defineApp(); +app.use(notifications); + +export default app; +``` + +```ts +// convex/notifications.ts (app-side wrapper) +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server"; +import { components } from "./_generated/api"; +import { getAuthUserId } from "@convex-dev/auth/server"; + +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); + +export const myUnread = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + return await ctx.runQuery(components.notifications.lib.listUnread, { + userId, + }); + }, +}); +``` + +Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. + +## Critical Rules + +- Keep authentication in the app. `ctx.auth` is not available inside components. +- Keep environment access in the app. Component functions cannot read `process.env`. +- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. +- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. +- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. +- Do not expose component functions directly to clients. Create app wrappers when client access is needed. +- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. +- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. +- Add `args` and `returns` validators to all public component functions. + +## Patterns + +### Authentication and environment access + +```ts +// Bad: component code cannot rely on app auth or env +const identity = await ctx.auth.getUserIdentity(); +const apiKey = process.env.OPENAI_API_KEY; +``` + +```ts +// Good: the app resolves auth and env, then passes explicit values +const userId = await getAuthUserId(ctx); +if (!userId) throw new Error("Not authenticated"); + +await ctx.runAction(components.translator.translate, { + userId, + apiKey: process.env.OPENAI_API_KEY, + text: args.text, +}); +``` + +### Client-facing API + +```ts +// Bad: assuming a component function is directly callable by clients +export const send = components.notifications.send; +``` + +```ts +// Good: re-export through an app mutation or query +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); +``` + +### IDs across the boundary + +```ts +// Bad: parent app table IDs are not valid component validators +args: { userId: v.id("users") } +``` + +```ts +// Good: treat parent-owned IDs as strings at the boundary +args: { userId: v.string() } +``` + +### Function Handles for callbacks + +When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. + +```ts +// App side: create a handle and pass it to the component +import { createFunctionHandle } from "convex/server"; + +export const startJob = mutation({ + handler: async (ctx) => { + const handle = await createFunctionHandle(internal.myModule.processItem); + await ctx.runMutation(components.workpool.enqueue, { + callback: handle, + }); + }, +}); +``` + +```ts +// Component side: accept and invoke the handle +import { v } from "convex/values"; +import type { FunctionHandle } from "convex/server"; +import { mutation } from "./_generated/server.js"; + +export const enqueue = mutation({ + args: { callback: v.string() }, + handler: async (ctx, args) => { + const handle = args.callback as FunctionHandle<"mutation">; + await ctx.scheduler.runAfter(0, handle, {}); + }, +}); +``` + +### Deriving validators from schema + +Instead of manually repeating field types in return validators, extend the schema validator: + +```ts +import { v } from "convex/values"; +import schema from "./schema.js"; + +const notificationDoc = schema.tables.notifications.validator.extend({ + _id: v.id("notifications"), + _creationTime: v.number(), +}); + +export const getLatest = query({ + args: {}, + returns: v.nullable(notificationDoc), + handler: async (ctx) => { + return await ctx.db.query("notifications").order("desc").first(); + }, +}); +``` + +### Static configuration with a globals table + +A common pattern for component configuration is a single-document "globals" table: + +```ts +// schema.ts +export default defineSchema({ + globals: defineTable({ + maxRetries: v.number(), + webhookUrl: v.optional(v.string()), + }), + // ... other tables +}); +``` + +```ts +// lib.ts +export const configure = mutation({ + args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, args) => { + const existing = await ctx.db.query("globals").first(); + if (existing) { + await ctx.db.patch(existing._id, args); + } else { + await ctx.db.insert("globals", args); + } + return null; + }, +}); +``` + +### Class-based client wrappers + +For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. + +```ts +// src/client/index.ts +import type { GenericMutationCtx, GenericDataModel } from "convex/server"; +import type { ComponentApi } from "../component/_generated/component.js"; + +type MutationCtx = Pick, "runMutation">; + +export class Notifications { + constructor( + private component: ComponentApi, + private options?: { defaultChannel?: string }, + ) {} + + async send(ctx: MutationCtx, args: { userId: string; message: string }) { + return await ctx.runMutation(this.component.lib.send, { + ...args, + channel: this.options?.defaultChannel ?? "default", + }); + } +} +``` + +```ts +// App usage +import { Notifications } from "@convex-dev/notifications"; +import { components } from "./_generated/api"; + +const notifications = new Notifications(components.notifications, { + defaultChannel: "alerts", +}); + +export const send = mutation({ + args: { message: v.string() }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + await notifications.send(ctx, { userId, message: args.message }); + }, +}); +``` + +## Validation + +Try validation in this order: + +1. `npx convex codegen --component-dir convex/components/` +2. `npx convex codegen` +3. `npx convex dev` + +Important: + +- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. +- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. +- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. + +## Reference Files + +Read exactly one of these after the user confirms the goal: + +- `references/local-components.md` +- `references/packaged-components.md` +- `references/hybrid-components.md` + +Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) + +## Checklist + +- [ ] Asked the user what they want to build and confirmed the shape +- [ ] Read the matching reference file +- [ ] Confirmed a component is the right abstraction +- [ ] Planned tables, public API, boundaries, and app wrappers +- [ ] Component lives under `convex/components//` (or package layout if publishing) +- [ ] Component imports from its own `./_generated/server` +- [ ] Auth, env access, and HTTP routes stay in the app +- [ ] Parent app IDs cross the boundary as `v.string()` +- [ ] Public functions have `args` and `returns` validators +- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.agents/skills/convex-create-component/agents/openai.yaml b/.agents/skills/convex-create-component/agents/openai.yaml new file mode 100644 index 00000000..ba9287e4 --- /dev/null +++ b/.agents/skills/convex-create-component/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Create Component" + short_description: "Design and build reusable Convex components with clear boundaries." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#14B8A6" + default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." + +policy: + allow_implicit_invocation: true diff --git a/.agents/skills/convex-create-component/assets/icon.svg b/.agents/skills/convex-create-component/assets/icon.svg new file mode 100644 index 00000000..10f4c2c4 --- /dev/null +++ b/.agents/skills/convex-create-component/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agents/skills/convex-create-component/references/hybrid-components.md b/.agents/skills/convex-create-component/references/hybrid-components.md new file mode 100644 index 00000000..d2bb3514 --- /dev/null +++ b/.agents/skills/convex-create-component/references/hybrid-components.md @@ -0,0 +1,37 @@ +# Hybrid Convex Components + +Read this file only when the user explicitly wants a hybrid setup. + +## What This Means + +A hybrid component combines a local Convex component with shared library code. + +This can help when: + +- the user wants a local install but also shared package logic +- the component needs extension points or override hooks +- some logic should live in normal TypeScript code outside the component boundary + +## Default Advice + +Treat hybrid as an advanced option, not the default. + +Before choosing it, ask: + +- Why is a plain local component not enough? +- Why is a packaged component not enough? +- What exactly needs to stay overridable or shared? + +If the answer is vague, fall back to local or packaged. + +## Risks + +- More moving parts +- Harder upgrades and backwards compatibility +- Easier to blur the component boundary + +## Checklist + +- [ ] User explicitly needs hybrid behavior +- [ ] Local-only and packaged-only options were considered first +- [ ] The extension points are clearly defined before coding diff --git a/.agents/skills/convex-create-component/references/local-components.md b/.agents/skills/convex-create-component/references/local-components.md new file mode 100644 index 00000000..7fbfe21a --- /dev/null +++ b/.agents/skills/convex-create-component/references/local-components.md @@ -0,0 +1,38 @@ +# Local Convex Components + +Read this file when the component should live inside the current app and does not need to be published as an npm package. + +## When to Choose This + +- The user wants the simplest path +- The component only needs to work in this repo +- The goal is extracting app logic into a cleaner boundary + +## Default Layout + +Use this structure unless the repo already has a clear alternative pattern: + +```text +convex/ + convex.config.ts + components/ + / + convex.config.ts + schema.ts + .ts +``` + +## Workflow Notes + +- Define the component with `defineComponent("")` +- Install it from the app with `defineApp()` and `app.use(...)` +- Keep auth, env access, public API wrappers, and HTTP route mounting in the app +- Let the component own isolated tables and reusable backend workflows +- Add app wrappers if clients need to call into the component + +## Checklist + +- [ ] Component is inside `convex/components//` +- [ ] App installs it with `app.use(...)` +- [ ] Component owns only its own tables +- [ ] App wrappers handle client-facing calls when needed diff --git a/.agents/skills/convex-create-component/references/packaged-components.md b/.agents/skills/convex-create-component/references/packaged-components.md new file mode 100644 index 00000000..5668e7ed --- /dev/null +++ b/.agents/skills/convex-create-component/references/packaged-components.md @@ -0,0 +1,51 @@ +# Packaged Convex Components + +Read this file when the user wants a reusable npm package or a component shared across multiple apps. + +## When to Choose This + +- The user wants to publish the component +- The user wants a stable reusable package boundary +- The component will be shared across multiple apps or teams + +## Default Approach + +- Prefer starting from `npx create-convex@latest --component` when possible +- Keep the official authoring docs as the source of truth for package layout and exports +- Validate the bundled package through an example app, not just the source files + +## Build Flow + +When building a packaged component, make sure the bundled output exists before the example app tries to consume it. + +Recommended order: + +1. `npx convex codegen --component-dir ./path/to/component` +2. Run the package build command +3. Run `npx convex dev --typecheck-components` in the example app + +Do not assume normal app codegen is enough for packaged component workflows. + +## Package Exports + +If publishing to npm, make sure the package exposes the entry points apps need: + +- package root for client helpers, types, or classes +- `./convex.config.js` for installing the component +- `./_generated/component.js` for the app-facing `ComponentApi` type +- `./test` for testing helpers when applicable + +## Testing + +- Use `convex-test` for component logic +- Register the component schema and modules with the test instance +- Test app-side wrapper code from an example app that installs the package +- Export a small helper from `./test` if consumers need easy test registration + +## Checklist + +- [ ] Packaging is actually required +- [ ] Build order avoids bundle and codegen races +- [ ] Package exports include install and typing entry points +- [ ] Example app exercises the packaged component +- [ ] Core behavior is covered by tests diff --git a/.agents/skills/convex-migration-helper/SKILL.md b/.agents/skills/convex-migration-helper/SKILL.md new file mode 100644 index 00000000..f353678f --- /dev/null +++ b/.agents/skills/convex-migration-helper/SKILL.md @@ -0,0 +1,524 @@ +--- +name: convex-migration-helper +description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. +--- + +# Convex Migration Helper + +Safely migrate Convex schemas and data when making breaking changes. + +## When to Use + +- Adding new required fields to existing tables +- Changing field types or structure +- Splitting or merging tables +- Renaming or deleting fields +- Migrating from nested to relational data + +## Key Concepts + +### Schema Validation Drives the Workflow + +Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: + +- You cannot add a required field if existing documents don't have it +- You cannot change a field's type if existing documents have the old type +- You cannot remove a field from the schema if existing documents still have it + +This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. + +### Online Migrations + +Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. + +### Prefer New Fields Over Changing Types + +When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. + +### Don't Delete Data + +Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. + +## Safe Changes (No Migration Needed) + +### Adding Optional Field + +```typescript +// Before +users: defineTable({ + name: v.string(), +}) + +// After - safe, new field is optional +users: defineTable({ + name: v.string(), + bio: v.optional(v.string()), +}) +``` + +### Adding New Table + +```typescript +posts: defineTable({ + userId: v.id("users"), + title: v.string(), +}).index("by_user", ["userId"]) +``` + +### Adding Index + +```typescript +users: defineTable({ + name: v.string(), + email: v.string(), +}) + .index("by_email", ["email"]) +``` + +## Breaking Changes: The Deployment Workflow + +Every breaking migration follows the same multi-deploy pattern: + +**Deploy 1 - Widen the schema:** + +1. Update schema to allow both old and new formats (e.g., add optional new field) +2. Update code to handle both formats when reading +3. Update code to write the new format for new documents +4. Deploy + +**Between deploys - Migrate data:** + +5. Run migration to backfill existing documents +6. Verify all documents are migrated + +**Deploy 2 - Narrow the schema:** + +7. Update schema to require the new format only +8. Remove code that handles the old format +9. Deploy + +## Using the Migrations Component (Recommended) + +For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. + +### Installation + +```bash +npm install @convex-dev/migrations +``` + +### Setup + +```typescript +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import migrations from "@convex-dev/migrations/convex.config.js"; + +const app = defineApp(); +app.use(migrations); +export default app; +``` + +```typescript +// convex/migrations.ts +import { Migrations } from "@convex-dev/migrations"; +import { components } from "./_generated/api.js"; +import { DataModel } from "./_generated/dataModel.js"; + +export const migrations = new Migrations(components.migrations); +export const run = migrations.runner(); +``` + +The `DataModel` type parameter is optional but provides type safety for migration definitions. + +### Define a Migration + +The `migrateOne` function processes a single document. The component handles batching and pagination automatically. + +```typescript +// convex/migrations.ts +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); +``` + +Shorthand: if you return an object, it is applied as a patch automatically. + +```typescript +export const clearDeprecatedField = migrations.define({ + table: "users", + migrateOne: () => ({ legacyField: undefined }), +}); +``` + +### Run a Migration + +From the CLI: + +```bash +# Define a one-off runner in convex/migrations.ts: +# export const runIt = migrations.runner(internal.migrations.addDefaultRole); +npx convex run migrations:runIt + +# Or use the general-purpose runner +npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' +``` + +Programmatically from another Convex function: + +```typescript +await migrations.runOne(ctx, internal.migrations.addDefaultRole); +``` + +### Run Multiple Migrations in Order + +```typescript +export const runAll = migrations.runner([ + internal.migrations.addDefaultRole, + internal.migrations.clearDeprecatedField, + internal.migrations.normalizeEmails, +]); +``` + +```bash +npx convex run migrations:runAll +``` + +If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. + +### Dry Run + +Test a migration before committing changes: + +```bash +npx convex run migrations:runIt '{"dryRun": true}' +``` + +This runs one batch and then rolls back, so you can see what it would do without changing any data. + +### Check Migration Status + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +### Cancel a Running Migration + +```bash +npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' +``` + +Or programmatically: + +```typescript +await migrations.cancel(ctx, internal.migrations.addDefaultRole); +``` + +### Run Migrations on Deploy + +Chain migration execution after deploying: + +```bash +npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod +``` + +### Configuration Options + +#### Custom Batch Size + +If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: + +```typescript +export const migrateHeavyTable = migrations.define({ + table: "largeDocuments", + batchSize: 10, + migrateOne: async (ctx, doc) => { + // migration logic + }, +}); +``` + +#### Migrate a Subset Using an Index + +Process only matching documents instead of the full table: + +```typescript +export const fixEmptyNames = migrations.define({ + table: "users", + customRange: (query) => + query.withIndex("by_name", (q) => q.eq("name", "")), + migrateOne: () => ({ name: "" }), +}); +``` + +#### Parallelize Within a Batch + +By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: + +```typescript +export const clearField = migrations.define({ + table: "myTable", + parallelize: true, + migrateOne: () => ({ optionalField: undefined }), +}); +``` + +## Common Migration Patterns + +### Adding a Required Field + +```typescript +// Deploy 1: Schema allows both states +users: defineTable({ + name: v.string(), + role: v.optional(v.union(v.literal("user"), v.literal("admin"))), +}) + +// Migration: backfill the field +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); + +// Deploy 2: After migration completes, make it required +users: defineTable({ + name: v.string(), + role: v.union(v.literal("user"), v.literal("admin")), +}) +``` + +### Deleting a Field + +Mark the field optional first, migrate data to remove it, then remove from schema: + +```typescript +// Deploy 1: Make optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()) + +// Migration +export const removeIsPro = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.isPro !== undefined) { + await ctx.db.patch(team._id, { isPro: undefined }); + } + }, +}); + +// Deploy 2: Remove isPro from schema entirely +``` + +### Changing a Field Type + +Prefer creating a new field. You can combine adding and deleting in one migration: + +```typescript +// Deploy 1: Add new field, keep old field optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) + +// Migration: convert old field to new field +export const convertToEnum = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.plan === undefined) { + await ctx.db.patch(team._id, { + plan: team.isPro ? "pro" : "basic", + isPro: undefined, + }); + } + }, +}); + +// Deploy 2: Remove isPro from schema, make plan required +``` + +### Splitting Nested Data Into a Separate Table + +```typescript +export const extractPreferences = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.preferences === undefined) return; + + const existing = await ctx.db + .query("userPreferences") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .first(); + + if (!existing) { + await ctx.db.insert("userPreferences", { + userId: user._id, + ...user.preferences, + }); + } + + await ctx.db.patch(user._id, { preferences: undefined }); + }, +}); +``` + +Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. + +### Cleaning Up Orphaned Documents + +```typescript +export const deleteOrphanedEmbeddings = migrations.define({ + table: "embeddings", + migrateOne: async (ctx, doc) => { + const chunk = await ctx.db + .query("chunks") + .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) + .first(); + + if (!chunk) { + await ctx.db.delete(doc._id); + } + }, +}); +``` + +## Migration Strategies for Zero Downtime + +During the migration window, your app must handle both old and new data formats. There are two main strategies. + +### Dual Write (Preferred) + +Write to both old and new structures. Read from the old structure until migration is complete. + +1. Deploy code that writes both formats, reads old format +2. Run migration on existing data +3. Deploy code that reads new format, still writes both +4. Deploy code that only reads and writes new format + +This is preferred because you can safely roll back at any point, the old format is always up to date. + +```typescript +// Bad: only writing to new structure before migration is done +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + await ctx.db.insert("teams", { + name: args.name, + plan: args.isPro ? "pro" : "basic", + }); + }, +}); + +// Good: writing to both structures during migration +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + const plan = args.isPro ? "pro" : "basic"; + await ctx.db.insert("teams", { + name: args.name, + isPro: args.isPro, + plan, + }); + }, +}); +``` + +### Dual Read + +Read both formats. Write only the new format. + +1. Deploy code that reads both formats (preferring new), writes only new format +2. Run migration on existing data +3. Deploy code that reads and writes only new format + +This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. + +```typescript +// Good: reading both formats, preferring new +function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { + if (team.plan !== undefined) return team.plan; + return team.isPro ? "pro" : "basic"; +} +``` + +## Small Table Shortcut + +For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: + +```typescript +import { internalMutation } from "./_generated/server"; + +export const backfillSmallTable = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("smallConfig").collect(); + for (const doc of docs) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: "default" }); + } + } + }, +}); +``` + +```bash +npx convex run migrations:backfillSmallTable +``` + +Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. + +## Verifying a Migration + +Query to check remaining unmigrated documents: + +```typescript +import { query } from "./_generated/server"; + +export const verifyMigration = query({ + handler: async (ctx) => { + const remaining = await ctx.db + .query("users") + .filter((q) => q.eq(q.field("role"), undefined)) + .take(10); + + return { + complete: remaining.length === 0, + sampleRemaining: remaining.map((u) => u._id), + }; + }, +}); +``` + +Or use the component's built-in status monitoring: + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +## Migration Checklist + +- [ ] Identify the breaking change and plan the multi-deploy workflow +- [ ] Update schema to allow both old and new formats +- [ ] Update code to handle both formats when reading +- [ ] Update code to write the new format for new documents +- [ ] Deploy widened schema and updated code +- [ ] Define migration using the `@convex-dev/migrations` component +- [ ] Test with `dryRun: true` +- [ ] Run migration and monitor status +- [ ] Verify all documents are migrated +- [ ] Update schema to require new format only +- [ ] Clean up code that handled old format +- [ ] Deploy final schema and code +- [ ] Remove migration code once confirmed stable + +## Common Pitfalls + +1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. +2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. +3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. +4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. +5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. +6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/.agents/skills/convex-migration-helper/agents/openai.yaml b/.agents/skills/convex-migration-helper/agents/openai.yaml new file mode 100644 index 00000000..c2a7fcc5 --- /dev/null +++ b/.agents/skills/convex-migration-helper/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Migration Helper" + short_description: "Plan and run safe Convex schema and data migrations." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#8B5CF6" + default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." + +policy: + allow_implicit_invocation: true diff --git a/.agents/skills/convex-migration-helper/assets/icon.svg b/.agents/skills/convex-migration-helper/assets/icon.svg new file mode 100644 index 00000000..fba7241a --- /dev/null +++ b/.agents/skills/convex-migration-helper/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agents/skills/convex-performance-audit/SKILL.md b/.agents/skills/convex-performance-audit/SKILL.md new file mode 100644 index 00000000..6ee0417f --- /dev/null +++ b/.agents/skills/convex-performance-audit/SKILL.md @@ -0,0 +1,143 @@ +--- +name: convex-performance-audit +description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. +--- + +# Convex Performance Audit + +Diagnose and fix performance problems in Convex applications, one problem class at a time. + +## When to Use + +- A Convex page or feature feels slow or expensive +- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts +- Low-freshness read paths are using reactivity where point-in-time reads would do +- OCC conflict errors or excessive mutation retries +- High subscription count or slow UI updates +- Functions approaching execution or transaction limits +- The same performance pattern needs fixing across sibling functions + +## When Not to Use + +- Initial Convex setup, auth setup, or component extraction +- Pure schema migrations with no performance goal +- One-off micro-optimizations without a user-visible or deployment-visible problem + +## Guardrails + +- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak +- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path +- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale + +## First Step: Gather Signals + +Start with the strongest signal available: + +1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. +2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. + - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. +3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. +4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. + +## Signal Routing + +After gathering signals, identify the problem class and read the matching reference file. + +| Signal | Reference | +|---|---| +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | + +Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. + +## Escalate Larger Fixes + +If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. + +Examples: + +- introducing digest or summary tables across multiple flows +- splitting documents to isolate frequently-updated fields +- reworking pagination or fetch strategy across several screens +- switching to a new index or denormalized field that needs migration-safe rollout + +When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. + +## Workflow + +### 1. Scope the problem + +Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. + +Write down: + +- entrypoint functions +- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` +- tables read +- tables written +- whether the path is high-read, high-write, or both + +### 2. Trace the full read and write set + +For each function in the path: + +1. Trace every `ctx.db.get()` and `ctx.db.query()` +2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` +3. Note foreign-key lookups, JS-side filtering, and full-document reads +4. Identify all sibling functions touching the same tables +5. Identify reactive stats, aggregates, or widgets rendered on the same page + +In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. + +### 3. Apply fixes from the relevant reference + +Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. + +Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. + +### 4. Fix sibling functions together + +When one function touching a table has a performance bug, audit sibling functions for the same pattern. + +After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. + +Examples: + +- If one list query switches from full docs to a digest table, inspect the other list queries for that table +- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk + +Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. + +### 5. Verify before finishing + +Confirm all of these: + +1. Results are the same as before, no dropped records +2. Eliminated reads or writes are no longer in the path where expected +3. Fallback behavior works when denormalized or indexed fields are missing +4. New writes avoid unnecessary invalidation when data is unchanged +5. Every relevant sibling reader and writer was inspected, not just the original function + +## Reference Files + +- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables +- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting +- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads +- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size + +Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. + +## Checklist + +- [ ] Gathered signals from insights, dashboard, or code audit +- [ ] Identified the problem class and read the matching reference +- [ ] Scoped one concrete user flow or function path +- [ ] Traced every read and write in that path +- [ ] Identified sibling functions touching the same tables +- [ ] Applied fixes from the reference, following the recommended fix order +- [ ] Fixed sibling functions consistently +- [ ] Verified behavior and confirmed no regressions diff --git a/.agents/skills/convex-performance-audit/agents/openai.yaml b/.agents/skills/convex-performance-audit/agents/openai.yaml new file mode 100644 index 00000000..9a21f387 --- /dev/null +++ b/.agents/skills/convex-performance-audit/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Performance Audit" + short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#EF4444" + default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." + +policy: + allow_implicit_invocation: true diff --git a/.agents/skills/convex-performance-audit/assets/icon.svg b/.agents/skills/convex-performance-audit/assets/icon.svg new file mode 100644 index 00000000..7ab9e09c --- /dev/null +++ b/.agents/skills/convex-performance-audit/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agents/skills/convex-performance-audit/references/function-budget.md b/.agents/skills/convex-performance-audit/references/function-budget.md new file mode 100644 index 00000000..c71d14cb --- /dev/null +++ b/.agents/skills/convex-performance-audit/references/function-budget.md @@ -0,0 +1,232 @@ +# Function Budget + +Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. + +## Core Principle + +Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. + +## Limits to Know + +These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. + +| Resource | Limit | +|---|---| +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | +| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | + +## Symptoms + +- "Function execution took too long" errors +- "Transaction too large" or read/write set size errors +- Slow queries that read many documents +- Client receiving large payloads that slow down page load +- `npx convex insights --details` showing high bytes read + +## Common Causes + +### Unbounded collection + +A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. + +### Large document reads on hot paths + +Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. + +### Mutation doing too much work + +A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. + +### Returning too much data to the client + +A query returning full documents when the client only needs a few fields. + +## Fix Order + +### 1. Bound your reads + +Never `.collect()` without a limit on a table that can grow unbounded. + +```ts +// Bad: unbounded read, breaks as the table grows +const messages = await ctx.db.query("messages").collect(); +``` + +```ts +// Good: paginate or limit +const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", channelId)) + .order("desc") + .take(50); +``` + +### 2. Read smaller shapes + +If the list page only needs title, author, and date, do not read full documents with rich content fields. + +Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. + +### 3. Break large mutations into batches + +If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. + +```ts +// Bad: one mutation updating every row +export const backfillAll = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("items").collect(); + for (const doc of docs) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + }, +}); +``` + +```ts +// Good: cursor-based batch processing +export const backfillBatch = internalMutation({ + args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, + handler: async (ctx, args) => { + const batchSize = args.batchSize ?? 100; + const result = await ctx.db + .query("items") + .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); + + for (const doc of result.page) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + } + + if (!result.isDone) { + await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { + cursor: result.continueCursor, + batchSize, + }); + } + }, +}); +``` + +### 4. Move heavy work to actions + +Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. + +Actions run outside the transaction and can call mutations to write results back. + +```ts +// Bad: heavy computation inside a mutation +export const processUpload = mutation({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.db.insert("results", result); + }, +}); +``` + +```ts +// Good: action for heavy work, mutation for the write +export const processUpload = action({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.runMutation(internal.results.store, { result }); + }, +}); +``` + +### 5. Trim return values + +Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. + +```ts +// Bad: returns full documents including large content fields +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("articles").take(20); + }, +}); +``` + +```ts +// Good: project to only the fields the client needs +export const list = query({ + handler: async (ctx) => { + const articles = await ctx.db.query("articles").take(20); + return articles.map((a) => ({ + _id: a._id, + title: a.title, + author: a.author, + createdAt: a._creationTime, + })); + }, +}); +``` + +### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions + +Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. + +```ts +// Bad: unnecessary overhead from ctx.runQuery inside a mutation +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await ctx.runQuery(api.users.getCurrentUser); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +```ts +// Good: plain helper function, no extra overhead +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await getCurrentUser(ctx); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. + +### 7. Avoid unnecessary `runAction` calls + +`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). + +```ts +// Bad: runAction overhead for no reason +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await ctx.runAction(internal.items.processOne, { item }); + } + }, +}); +``` + +```ts +// Good: plain function call +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await processOneItem(ctx, { item }); + } + }, +}); +``` + +## Verification + +1. No function execution or transaction size errors +2. `npx convex insights --details` shows reduced bytes read +3. Large mutations are batched and self-scheduling +4. Client payloads are reasonably sized for the UI they serve +5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible +6. Sibling functions with similar patterns were checked diff --git a/.agents/skills/convex-performance-audit/references/hot-path-rules.md b/.agents/skills/convex-performance-audit/references/hot-path-rules.md new file mode 100644 index 00000000..96a7b94e --- /dev/null +++ b/.agents/skills/convex-performance-audit/references/hot-path-rules.md @@ -0,0 +1,359 @@ +# Hot Path Rules + +Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. + +## Core Principle + +Every byte read or written multiplies with concurrency. + +Think: + +`cost x calls_per_second x 86400` + +In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. + +## Consistency Rule + +If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. + +Do this especially for: + +- multiple list queries over the same table +- multiple writers to the same table +- public browse and search queries over the same records +- helper functions reused by more than one endpoint + +## 1. Push Filters To Storage + +Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. + +Prefer: + +- `withIndex(...)` +- `.withSearchIndex(...)` for text search +- narrower tables +- summary tables + +before accepting a scan-plus-filter pattern. + +```ts +// Bad: scans then filters in JavaScript +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + const tasks = await ctx.db.query("tasks").collect(); + return tasks.filter((task) => task.status === "open"); + }, +}); +``` + +```ts +// Also bad: Convex .filter() does not push to storage either +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .filter((q) => q.eq(q.field("status"), "open")) + .collect(); + }, +}); +``` + +```ts +// Good: use an index so storage does the filtering +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .withIndex("by_status", (q) => q.eq("status", "open")) + .collect(); + }, +}); +``` + +### Migration rule for indexes + +New indexes on partially backfilled fields can create correctness bugs during rollout. + +Important Convex detail: + +`undefined !== false` + +If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. + +Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. + +If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. + +```ts +// Bad: optional booleans can miss older rows where the field is undefined +const projects = await ctx.db + .query("projects") + .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) + .order("desc") + .take(20); +``` + +```ts +// Good: switch hot-path reads only after the rollout is migration-safe +// See the migration helper skill for dual-read / backfill / cutover patterns. +``` + +### Check for redundant indexes + +Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. + +```ts +// Bad: two indexes where one would do +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team", ["team"]) + .index("by_team_and_user", ["team", "user"]) +``` + +```ts +// Good: single compound index serves both query patterns +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team_and_user", ["team", "user"]) +``` + +Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. + +## 2. Minimize Data Sources + +Trace every read. + +If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. + +### When to denormalize + +Denormalize when all of these are true: + +- the path is hot +- the joined document is much larger than the field you need +- many readers are paying that join cost repeatedly + +Useful mental model: + +`join_cost = rows_per_page x foreign_doc_size x pages_per_second` + +Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. + +### Fallback rule + +Denormalized data is an optimization. Live data is the correctness path. + +Rules: + +- If the denormalized field is missing or null, fall back to the live read +- Do not show placeholders instead of falling back +- In lookup maps, only include fully populated entries + +```ts +// Bad: missing denormalized data becomes a placeholder and blocks correctness +const ownerName = project.ownerName ?? "Unknown owner"; +``` + +```ts +// Good: denormalized data is an optimization, not the only source of truth +const ownerName = + project.ownerName ?? + (await ctx.db.get(project.ownerId))?.name ?? + null; +``` + +Bad lookup map pattern: + +```ts +const ownersById = { + [project.ownerId]: { ownerName: null }, +}; +``` + +That blocks fallback because the map says "I have data" when it does not. + +Good lookup map pattern: + +```ts +const ownersById = + project.ownerName !== undefined && project.ownerName !== null + ? { [project.ownerId]: { ownerName: project.ownerName } } + : {}; +``` + +### No denormalized copy yet + +Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. + +If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. + +Rollout order: + +1. Update schema +2. Update write path +3. Backfill +4. Switch read path + +## 3. Minimize Row Size + +Hot list pages should read the smallest document shape that still answers the UI. + +Prefer summary or digest tables over full source tables when: + +- the list page only needs a subset of fields +- source documents are large +- the query is high volume + +An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. + +Digest tables are a tradeoff, not a default: + +- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost +- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit + +```ts +// Bad: list page reads source docs, then joins owner data per row +const projects = await ctx.db + .query("projects") + .withIndex("by_public", (q) => q.eq("isPublic", true)) + .collect(); +``` + +```ts +// Good: list page reads the smaller digest shape first +const projects = await ctx.db + .query("projectDigests") + .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) + .order("desc") + .take(20); +``` + +## 4. Skip No-Op Writes + +No-op writes still cost work in Convex: + +- invalidation +- replication +- trigger execution +- downstream sync + +Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. + +Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. + +```ts +// Bad: patching unchanged values still triggers invalidation and downstream work +await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, +}); +``` + +```ts +// Good: only write when something actually changed +if (settings.theme !== args.theme || settings.locale !== args.locale) { + await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, + }); +} +``` + +## 5. Match Consistency To Read Patterns + +Choose read strategy based on traffic shape. + +### High-read, low-write + +Examples: + +- public browse pages +- search results +- landing pages +- directory listings + +Prefer: + +- point-in-time reads where appropriate +- explicit refresh +- local state for pagination +- caching where appropriate + +Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. + +### High-read, high-write + +Examples: + +- collaborative editors +- live dashboards +- presence-heavy views + +Reactive queries may be worth the ongoing cost. + +## Convex-Specific Notes + +### Reactive queries + +Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. + +On the client: + +- `useQuery` creates a live subscription +- `usePaginatedQuery` creates a live subscription per page + +For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. + +### Point-in-time reads + +Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. + +Use them for: + +- aggregate snapshots +- reports +- low-churn listings +- pages where explicit refresh is fine + +### Triggers and fan-out + +Triggers fire on every write, including writes that did not materially change the document. + +When a write exists only to keep derived state in sync: + +- diff before patching +- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate + +### Aggregates + +Reactive global counts invalidate frequently on busy tables. + +Prefer: + +- one-shot aggregate fetches +- periodic recomputation +- precomputed summary rows + +for global stats that do not need live updates every second. + +### Backfills + +For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. + +Deploy code that can handle both states before running the backfill. + +During the gap: + +- writes should populate the new shape +- reads should fall back safely + +## Verification + +Before closing the audit, confirm: + +1. Same results as before, no dropped records +2. The removed table or lookup is no longer in the hot-path read set +3. Tests or validation cover fallback behavior +4. Migration safety is preserved while fields or indexes are unbackfilled +5. Sibling functions were fixed consistently diff --git a/.agents/skills/convex-performance-audit/references/occ-conflicts.md b/.agents/skills/convex-performance-audit/references/occ-conflicts.md new file mode 100644 index 00000000..a96d0466 --- /dev/null +++ b/.agents/skills/convex-performance-audit/references/occ-conflicts.md @@ -0,0 +1,126 @@ +# OCC Conflict Resolution + +Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. + +## Core Principle + +Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. + +## Symptoms + +- OCC conflict errors in deployment logs or health page +- Mutations retrying multiple times before succeeding +- User-visible latency spikes on write-heavy pages +- `npx convex insights --details` showing high conflict rates + +## Common Causes + +### Hot documents + +Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. + +### Broad read sets causing false conflicts + +A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. + +### Fan-out from triggers or cascading writes + +A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. + +Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. + +### Write-then-read chains + +A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. + +## Fix Order + +### 1. Reduce read set size + +Narrower reads mean fewer false conflicts. + +```ts +// Bad: broad scan creates a wide conflict surface +const allTasks = await ctx.db.query("tasks").collect(); +const mine = allTasks.filter((t) => t.ownerId === userId); +``` + +```ts +// Good: indexed query touches only relevant documents +const mine = await ctx.db + .query("tasks") + .withIndex("by_owner", (q) => q.eq("ownerId", userId)) + .collect(); +``` + +### 2. Split hot documents + +When many writers target the same document, split the contention point. + +```ts +// Bad: every vote increments the same counter document +const counter = await ctx.db.get(pollCounterId); +await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); +``` + +```ts +// Good: shard the counter across multiple documents, aggregate on read +const shardIndex = Math.floor(Math.random() * SHARD_COUNT); +const shardId = shardIds[shardIndex]; +const shard = await ctx.db.get(shardId); +await ctx.db.patch(shardId, { count: shard!.count + 1 }); +``` + +Aggregate the shards in a query or scheduled job when you need the total. + +### 3. Skip no-op writes + +Writes that do not change data still participate in conflict detection and trigger invalidation. + +```ts +// Bad: patches even when nothing changed +await ctx.db.patch(doc._id, { status: args.status }); +``` + +```ts +// Good: only write when the value actually differs +if (doc.status !== args.status) { + await ctx.db.patch(doc._id, { status: args.status }); +} +``` + +### 4. Move non-critical work to scheduled functions + +If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. + +```ts +// Bad: analytics update in the same transaction as the user action +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +``` + +```ts +// Good: schedule the bookkeeping so the primary transaction is smaller +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { + event: "action", + userId, +}); +``` + +### 5. Combine competing writes + +If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. + +Do not introduce artificial locks or queues unless the above steps have been tried first. + +## Related: Invalidation Scope + +Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. + +## Verification + +1. OCC conflict rate has dropped in insights or dashboard +2. Mutation latency is lower and more consistent +3. No data correctness regressions from splitting or scheduling changes +4. Sibling writers to the same hot documents were fixed consistently diff --git a/.agents/skills/convex-performance-audit/references/subscription-cost.md b/.agents/skills/convex-performance-audit/references/subscription-cost.md new file mode 100644 index 00000000..ae7d1adb --- /dev/null +++ b/.agents/skills/convex-performance-audit/references/subscription-cost.md @@ -0,0 +1,252 @@ +# Subscription Cost + +Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. + +## Core Principle + +Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: + +`subscriptions x invalidation_frequency x query_cost` + +Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. + +## Symptoms + +- Dashboard shows high active subscription count +- UI feels sluggish or laggy despite fast individual queries +- React profiling shows frequent re-renders from Convex state +- Pages with many components each running their own `useQuery` +- Paginated lists where every loaded page stays subscribed + +## Common Causes + +### Reactive queries on low-freshness flows + +Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. + +### Overly broad queries + +A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. + +### Too many subscriptions per page + +A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. + +### Paginated queries keeping all pages live + +`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. + +### Frequently-updated fields on widely-read documents + +A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. + +## Fix Order + +### 1. Use point-in-time reads when live updates are not valuable + +Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. + +Consider a point-in-time read instead when all of these are true: + +- the flow is high-read +- the underlying data changes less often than users need to see +- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable + +Possible implementations depend on environment: + +- a server-rendered fetch +- a framework helper like `fetchQuery` +- a point-in-time client read such as `ConvexHttpClient.query()` + +```ts +// Reactive by default when fresh live data matters +function TeamPresence() { + const presence = useQuery(api.teams.livePresence, { teamId }); + return ; +} +``` + +```ts +// Point-in-time read when explicit refresh is acceptable +import { ConvexHttpClient } from "convex/browser"; + +const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); + +function SnapshotView() { + const [items, setItems] = useState([]); + + useEffect(() => { + client.query(api.items.snapshot).then(setItems); + }, []); + + return ; +} +``` + +Good candidates for point-in-time reads: + +- aggregate snapshots +- reports +- low-churn listings +- flows where explicit refresh is already acceptable + +Keep reactive for: + +- collaborative editing +- live dashboards +- presence-heavy views +- any surface where users expect fresh changes to appear automatically + +### 2. Batch related data into fewer queries + +Instead of N components each fetching their own related data, fetch it in a single query. + +```ts +// Bad: each card fetches its own author +function ProjectCard({ project }: { project: Project }) { + const author = useQuery(api.users.get, { id: project.authorId }); + return ; +} +``` + +```ts +// Good: parent query returns projects with author names included +function ProjectList() { + const projects = useQuery(api.projects.listWithAuthors); + return projects?.map((p) => ( + + )); +} +``` + +This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. + +This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. + +### 3. Use skip to avoid unnecessary subscriptions + +The `"skip"` value prevents a subscription from being created when the arguments are not ready. + +```ts +// Bad: subscribes with undefined args, wastes a subscription slot +const profile = useQuery(api.users.getProfile, { userId: selectedId! }); +``` + +```ts +// Good: skip when there is nothing to fetch +const profile = useQuery( + api.users.getProfile, + selectedId ? { userId: selectedId } : "skip", +); +``` + +### 4. Isolate frequently-updated fields into separate documents + +If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. + +```ts +// Bad: lastSeen lives on the user doc, every heartbeat invalidates +// every query that reads this user +const users = defineTable({ + name: v.string(), + email: v.string(), + lastSeen: v.number(), +}); +``` + +```ts +// Good: lastSeen lives in a separate heartbeat doc +const users = defineTable({ + name: v.string(), + email: v.string(), + heartbeatId: v.id("heartbeats"), +}); + +const heartbeats = defineTable({ + lastSeen: v.number(), +}); +``` + +Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. + +For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. + +### 5. Use the aggregate component for counts and sums + +Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. + +Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. + +If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. + +### 6. Narrow query read sets + +Queries that return less data and touch fewer documents invalidate less often. + +```ts +// Bad: returns all fields, invalidates on any field change +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("projects").collect(); + }, +}); +``` + +```ts +// Good: use a digest table with only the fields the list needs +export const listDigests = query({ + handler: async (ctx) => { + return await ctx.db.query("projectDigests").collect(); + }, +}); +``` + +Writes to fields not in the digest table do not invalidate the digest query. + +### 7. Remove `Date.now()` from queries + +Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. + +```ts +// Bad: Date.now() defeats query caching and causes frequent re-evaluation +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) + .take(100); +``` + +```ts +// Good: use a boolean field updated by a scheduled function +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_is_released", (q) => q.eq("isReleased", true)) + .take(100); +``` + +If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. + +### 8. Consider pagination strategy + +For long lists where users scroll through many pages: + +- If the data does not need live updates, use point-in-time fetching with manual "load more" +- If it does need live updates, accept the subscription cost but limit the number of loaded pages +- Consider whether older pages can be unloaded as the user scrolls forward + +### 9. Separate backend cost from UI churn + +If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. + +Treat this as a UX problem first when: + +- the underlying query is already reasonably cheap +- the complaint is flicker, loading flashes, or re-render churn +- live updates are still desirable once fresh data arrives + +## Verification + +1. Subscription count in dashboard is lower for the affected pages +2. UI responsiveness has improved +3. React profiling shows fewer unnecessary re-renders +4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily +5. Sibling pages with similar patterns were updated consistently diff --git a/.agents/skills/convex-quickstart/SKILL.md b/.agents/skills/convex-quickstart/SKILL.md new file mode 100644 index 00000000..369a6c9b --- /dev/null +++ b/.agents/skills/convex-quickstart/SKILL.md @@ -0,0 +1,337 @@ +--- +name: convex-quickstart +description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. +--- + +# Convex Quickstart + +Set up a working Convex project as fast as possible. + +## When to Use + +- Starting a brand new project with Convex +- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app +- Scaffolding a Convex app for prototyping + +## When Not to Use + +- The project already has Convex installed and `convex/` exists - just start building +- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill + +## Workflow + +1. Determine the starting point: new project or existing app +2. If new project, pick a template and scaffold with `npm create convex@latest` +3. If existing app, install `convex` and wire up the provider +4. Run `npx convex dev` to connect a deployment and start the dev loop +5. Verify the setup works + +## Path 1: New Project (Recommended) + +Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. + +### Pick a template + +| Template | Stack | +|----------|-------| +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | + +If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. + +You can also use any GitHub repo as a template: + +```bash +npm create convex@latest my-app -- -t owner/repo +npm create convex@latest my-app -- -t owner/repo#branch +``` + +### Scaffold the project + +Always pass the project name and template flag to avoid interactive prompts: + +```bash +npm create convex@latest my-app -- -t react-vite-shadcn +cd my-app +npm install +``` + +The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. + +To scaffold in the current directory (if it is empty): + +```bash +npm create convex@latest . -- -t react-vite-shadcn +npm install +``` + +### Start the dev loop + +`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. + +**Ask the user to run this themselves:** + +Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: +- Create a Convex project and dev deployment +- Write the deployment URL to `.env.local` +- Create the `convex/` directory with generated types +- Watch for changes and sync continuously + +The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. + +**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. + +### Start the frontend + +The user should also run the frontend dev server in a separate terminal: + +```bash +npm run dev +``` + +Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. + +### What you get + +After scaffolding, the project structure looks like: + +``` +my-app/ + convex/ # Backend functions and schema + _generated/ # Auto-generated types (check this into git) + schema.ts # Database schema (if template includes one) + src/ # Frontend code (or app/ for Next.js) + package.json + .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL +``` + +The template already has: +- `ConvexProvider` wired into the app root +- Correct env var names for the framework +- Tailwind and shadcn/ui ready (for shadcn templates) +- Auth provider configured (for auth templates) + +You are ready to start adding schema, functions, and UI. + +## Path 2: Add Convex to an Existing App + +Use this when the user already has a frontend project and wants to add Convex as the backend. + +### Install + +```bash +npm install convex +``` + +### Initialize and start dev loop + +Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. + +### Wire up the provider + +The Convex client must wrap the app at the root. The setup varies by framework. + +Create the `ConvexReactClient` at module scope, not inside a component: + +```tsx +// Bad: re-creates the client on every render +function App() { + const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + return ...; +} + +// Good: created once at module scope +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); +function App() { + return ...; +} +``` + +#### React (Vite) + +```tsx +// src/main.tsx +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import App from "./App"; + +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + +createRoot(document.getElementById("root")!).render( + + + + + , +); +``` + +#### Next.js (App Router) + +```tsx +// app/ConvexClientProvider.tsx +"use client"; + +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import { ReactNode } from "react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +export function ConvexClientProvider({ children }: { children: ReactNode }) { + return {children}; +} +``` + +```tsx +// app/layout.tsx +import { ConvexClientProvider } from "./ConvexClientProvider"; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} +``` + +#### Other frameworks + +For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: + +- [Vue](https://docs.convex.dev/quickstart/vue) +- [Svelte](https://docs.convex.dev/quickstart/svelte) +- [React Native](https://docs.convex.dev/quickstart/react-native) +- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) +- [Remix](https://docs.convex.dev/quickstart/remix) +- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) + +### Environment variables + +The env var name depends on the framework: + +| Framework | Variable | +|-----------|----------| +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | +| React Native | `EXPO_PUBLIC_CONVEX_URL` | + +`npx convex dev` writes the correct variable to `.env.local` automatically. + +## Agent Mode (Cloud-Based Agents) + +When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. + +Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: + +```bash +CONVEX_AGENT_MODE=anonymous npx convex dev +``` + +This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. + +## Verify the Setup + +After setup, confirm everything is working: + +1. The user confirms `npx convex dev` is running without errors +2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` +3. `.env.local` contains the deployment URL + +## Writing Your First Function + +Once the project is set up, create a schema and a query to verify the full loop works. + +`convex/schema.ts`: + +```ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + tasks: defineTable({ + text: v.string(), + completed: v.boolean(), + }), +}); +``` + +`convex/tasks.ts`: + +```ts +import { query, mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("tasks").collect(); + }, +}); + +export const create = mutation({ + args: { text: v.string() }, + handler: async (ctx, args) => { + await ctx.db.insert("tasks", { text: args.text, completed: false }); + }, +}); +``` + +Use in a React component (adjust the import path based on your file location relative to `convex/`): + +```tsx +import { useQuery, useMutation } from "convex/react"; +import { api } from "../convex/_generated/api"; + +function Tasks() { + const tasks = useQuery(api.tasks.list); + const create = useMutation(api.tasks.create); + + return ( +
+ + {tasks?.map((t) =>
{t.text}
)} +
+ ); +} +``` + +## Development vs Production + +Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. + +When ready to ship, deploy to production: + +```bash +npx convex deploy +``` + +This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. + +## Next Steps + +- Add authentication: use the `convex-setup-auth` skill +- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) +- Build components: use the `convex-create-component` skill +- Plan a migration: use the `convex-migration-helper` skill +- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) +- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) + +## Checklist + +- [ ] Determined starting point: new project or existing app +- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template +- [ ] If existing app: installed `convex` and wired up the provider +- [ ] User has `npx convex dev` running and connected to a deployment +- [ ] `convex/_generated/` directory exists with types +- [ ] `.env.local` has the deployment URL +- [ ] Verified a basic query/mutation round-trip works diff --git a/.agents/skills/convex-quickstart/agents/openai.yaml b/.agents/skills/convex-quickstart/agents/openai.yaml new file mode 100644 index 00000000..a51a6d09 --- /dev/null +++ b/.agents/skills/convex-quickstart/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Quickstart" + short_description: "Start a new Convex app or add Convex to an existing frontend." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#F97316" + default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." + +policy: + allow_implicit_invocation: true diff --git a/.agents/skills/convex-quickstart/assets/icon.svg b/.agents/skills/convex-quickstart/assets/icon.svg new file mode 100644 index 00000000..d83a73f3 --- /dev/null +++ b/.agents/skills/convex-quickstart/assets/icon.svg @@ -0,0 +1,4 @@ + diff --git a/.agents/skills/convex-setup-auth/SKILL.md b/.agents/skills/convex-setup-auth/SKILL.md new file mode 100644 index 00000000..5c0c994a --- /dev/null +++ b/.agents/skills/convex-setup-auth/SKILL.md @@ -0,0 +1,113 @@ +--- +name: convex-setup-auth +description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. +--- + +# Convex Authentication Setup + +Implement secure authentication in Convex with user management and access control. + +## When to Use + +- Setting up authentication for the first time +- Implementing user management (users table, identity mapping) +- Creating authentication helper functions +- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) + +## First Step: Choose the Auth Provider + +Convex supports multiple authentication approaches. Do not assume a provider. + +Before writing setup code: + +1. Ask the user which auth solution they want, unless the repository already makes it obvious +2. If the repo already uses a provider, continue with that provider unless the user wants to switch +3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding + +Common options: + +- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex +- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features +- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically +- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 +- Custom JWT provider - use when integrating an existing auth system not covered above + +Look for signals in the repo before asking: + +- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages +- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components +- Environment variables that clearly point at a provider + +## After Choosing a Provider + +Read the provider's official guide and the matching local reference file: + +- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` +- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` +- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` +- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` + +The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. + +Use those sources for: + +- package installation +- client provider wiring +- environment variables +- `convex/auth.config.ts` setup +- login and logout UI patterns +- framework-specific setup for React, Vite, or Next.js + +For shared auth behavior, use the official Convex docs as the source of truth: + +- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` +- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage +- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance +- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth + +Do not invent a provider-agnostic user sync pattern from memory. +For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. +For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. + +Do not invent provider-specific setup from memory when the docs are available. +Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. + +## Workflow + +1. Determine the provider, either by asking the user or inferring from the repo +2. Ask whether the user wants local-only setup or production-ready setup now +3. Read the matching provider reference file +4. Follow the official provider docs for current setup details +5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns +6. Only add app-level user storage if the docs and app requirements call for it +7. Add authorization checks for ownership, roles, or team access only where the app needs them +8. Verify login state, protected queries, environment variables, and production configuration if requested + +If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. +For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. +If the environment has browser automation tools, you can use them. +If it does not, give the user a short manual validation checklist instead. + +## Reference Files + +### Provider References + +- `references/convex-auth.md` +- `references/clerk.md` +- `references/workos-authkit.md` +- `references/auth0.md` + +## Checklist + +- [ ] Chosen the correct auth provider before writing setup code +- [ ] Read the relevant provider reference file +- [ ] Asked whether the user wants local-only setup or production-ready setup +- [ ] Used the official provider docs for provider-specific wiring +- [ ] Used the official Convex docs for shared auth behavior and authorization patterns +- [ ] Only added app-level user storage if the app actually needs it +- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth +- [ ] Added authentication checks in protected backend functions +- [ ] Added authorization checks where the app actually needs them +- [ ] Clear error messages ("Not authenticated", "Unauthorized") +- [ ] Client auth provider configured for the chosen provider +- [ ] If requested, production auth setup is covered too diff --git a/.agents/skills/convex-setup-auth/agents/openai.yaml b/.agents/skills/convex-setup-auth/agents/openai.yaml new file mode 100644 index 00000000..d1c90a14 --- /dev/null +++ b/.agents/skills/convex-setup-auth/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Setup Auth" + short_description: "Set up Convex auth, user identity mapping, and access control." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#2563EB" + default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." + +policy: + allow_implicit_invocation: true diff --git a/.agents/skills/convex-setup-auth/assets/icon.svg b/.agents/skills/convex-setup-auth/assets/icon.svg new file mode 100644 index 00000000..4917dbb4 --- /dev/null +++ b/.agents/skills/convex-setup-auth/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.agents/skills/convex-setup-auth/references/auth0.md b/.agents/skills/convex-setup-auth/references/auth0.md new file mode 100644 index 00000000..9c729c5a --- /dev/null +++ b/.agents/skills/convex-setup-auth/references/auth0.md @@ -0,0 +1,116 @@ +# Auth0 + +Official docs: + +- https://docs.convex.dev/auth/auth0 +- https://auth0.github.io/auth0-cli/ +- https://auth0.github.io/auth0-cli/auth0_apps_create.html + +Use this when the app already uses Auth0 or the user wants Auth0 specifically. + +## Workflow + +1. Confirm the user wants Auth0 +2. Determine the app framework and whether Auth0 is already partly set up +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and Auth0 guides before making changes +5. Ask whether they want the fastest setup path by installing the Auth0 CLI +6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI +7. If they do not want the CLI path, use the Auth0 dashboard path instead +8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up +9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID +10. Set environment variables for local and production environments +11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +12. Gate Convex-backed UI with Convex auth state +13. Try to verify Convex reports the user as authenticated after Auth0 login +14. If the refresh-token path fails, stop improvising and send the user back to the official docs +15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered + +## What To Do + +- Read the official Convex and Auth0 guide before writing setup code +- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet +- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" +- Make sure the app has already completed the relevant Auth0 quickstart for its frontend +- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` +- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated + +## Key Setup Areas + +- install the Auth0 SDK for the app's framework +- configure `convex/auth.config.ts` with the Auth0 domain and client ID +- set environment variables for local and production environments +- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +- use Convex auth state when gating Convex-backed UI + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- frontend app entry or provider wrapper +- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` +- Auth0 environment variables commonly include: + - `AUTH0_DOMAIN` + - `AUTH0_CLIENT_ID` + - `VITE_AUTH0_DOMAIN` + - `VITE_AUTH0_CLIENT_ID` + +## Concrete Steps + +1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework +2. Ask whether the user wants the Auth0 CLI path +3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` +4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app +5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard +6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard +7. Install the Auth0 SDK for the app's framework +8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID +9. Set frontend and backend environment variables +10. Wrap the app in `Auth0Provider` +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` +12. Run the normal Convex dev or deploy flow after backend config changes +13. Try the official provider config shown in the Convex docs +14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now +15. Only claim success if the user can sign in and Convex recognizes the authenticated session +16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too + +## Gotchas + +- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch +- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant +- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard +- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced +- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end +- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled +- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation +- Keep dev and prod tenants separate if the project uses different Auth0 environments +- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. +- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. +- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. +- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered +- Verify production environment variables and redirect settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the Auth0 login flow +- Verify Convex-authenticated UI renders only after Convex auth state is ready +- Verify protected Convex queries succeed after login +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- Verify the Auth0 app settings match the real local callback and logout URLs during development +- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully +- If production-ready setup was requested, verify the production Auth0 configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Auth0 +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Complete the relevant Auth0 frontend setup +- [ ] Configure `convex/auth.config.ts` +- [ ] Set environment variables +- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs +- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-setup-auth/references/clerk.md b/.agents/skills/convex-setup-auth/references/clerk.md new file mode 100644 index 00000000..7dbde194 --- /dev/null +++ b/.agents/skills/convex-setup-auth/references/clerk.md @@ -0,0 +1,113 @@ +# Clerk + +Official docs: + +- https://docs.convex.dev/auth/clerk +- https://clerk.com/docs/guides/development/integrations/databases/convex + +Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. + +## Workflow + +1. Confirm the user wants Clerk +2. Make sure the user has a Clerk account and a Clerk application +3. Determine the app framework: + - React + - Next.js + - TanStack Start +4. Ask whether the user wants local-only setup or production-ready setup now +5. Gather the Clerk keys and the Clerk Frontend API URL +6. Follow the correct framework section in the official docs +7. Complete the backend and client wiring +8. Verify Convex reports the user as authenticated after login +9. If the user wants production-ready setup, make sure the production Clerk config is also covered + +## What To Do + +- Read the official Convex and Clerk guide before writing setup code +- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application +- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active +- Match the guide to the app's framework, usually React, Next.js, or TanStack Start +- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` + +## Key Setup Areas + +- install the Clerk SDK for the framework in use +- configure `convex/auth.config.ts` with the Clerk issuer domain +- set the required Clerk environment variables +- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` +- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- React or Vite client entry such as `src/main.tsx` +- Next.js client wrapper for Convex if using App Router +- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` +- Clerk app creation page: `https://dashboard.clerk.com/apps/new` +- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` +- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` +- Clerk environment variables: + - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs + - `CLERK_FRONTEND_API_URL` in the Clerk docs + - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps + - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps + - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required + +`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. + +## Concrete Steps + +1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` +2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` +3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed +4. Open `https://dashboard.clerk.com/apps/setup/convex` +5. Activate the Convex integration in Clerk if it is not already active +6. Copy the Clerk Frontend API URL shown there +7. Install the Clerk package for the app's framework +8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens +9. Set the publishable key in the frontend environment +10. Set the issuer domain or Frontend API URL so Convex can validate the JWT +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` +12. Wrap the app in `ClerkProvider` +13. Use Convex auth helpers for authenticated rendering +14. Run the normal Convex dev or deploy flow after updating backend auth config +15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too + +## Gotchas + +- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render +- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper +- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config +- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. +- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. +- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. +- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. +- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` +- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included +- Verify production redirect URLs and any production Clerk domain values before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can sign in with Clerk +- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in +- Verify `useConvexAuth()` reaches the authenticated state after Clerk login +- Verify protected Convex queries run successfully inside authenticated UI +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- If production-ready setup was requested, verify the production Clerk configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Clerk +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Follow the correct framework section in the official guide +- [ ] Set Clerk environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify Convex authenticated state after login +- [ ] If requested, configure the production deployment too diff --git a/.agents/skills/convex-setup-auth/references/convex-auth.md b/.agents/skills/convex-setup-auth/references/convex-auth.md new file mode 100644 index 00000000..d4824d24 --- /dev/null +++ b/.agents/skills/convex-setup-auth/references/convex-auth.md @@ -0,0 +1,143 @@ +# Convex Auth + +Official docs: https://docs.convex.dev/auth/convex-auth +Setup guide: https://labs.convex.dev/auth/setup + +Use this when the user wants auth handled directly in Convex rather than through a third-party provider. + +## Workflow + +1. Confirm the user wants Convex Auth specifically +2. Determine which sign-in methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords and password reset +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the Convex Auth setup guide before writing code +5. Make sure the project has a configured Convex deployment: + - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set + - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing +6. Install the auth packages: + - `npm install @convex-dev/auth @auth/core@0.37.0` +7. Run the initialization command: + - `npx @convex-dev/auth` +8. Confirm the initializer created: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +9. Add the required `authTables` to `convex/schema.ts` +10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` +11. Configure at least one auth method in `convex/auth.ts` +12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code +13. Verify the client can sign in successfully +14. Verify Convex receives authenticated identity in backend functions +15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well +16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex + +## What This Reference Is For + +- choosing Convex Auth as the default provider for a new Convex app +- understanding whether the app wants magic links, OTPs, OAuth, or passwords +- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior + +## What To Do + +- Read the Convex Auth setup guide before writing setup code +- Follow the setup flow from the docs rather than recreating it from memory +- If the app is new, consider starting from the official starter flow instead of hand-wiring everything +- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra + +## Concrete Steps + +1. Install `@convex-dev/auth` and `@auth/core@0.37.0` +2. Run `npx convex dev` if the project does not already have a configured deployment +3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment +4. Run `npx @convex-dev/auth` +5. Confirm the generated auth setup is present before continuing: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +6. Add `authTables` to `convex/schema.ts` +7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry +8. Configure the selected auth methods in `convex/auth.ts` +9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed +10. Verify login locally +11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment + +## Expected Files and Decisions + +- `convex/schema.ts` +- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file +- generated Convex Auth setup produced by `npx @convex-dev/auth` +- an existing configured Convex deployment, or the ability to create one with `npx convex dev` +- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods + +- Decide whether the user is creating a new app or adding auth to an existing app +- For a new app, prefer the official starter flow instead of rebuilding setup by hand +- Decide which auth methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords +- Decide whether the user wants local-only setup or production-ready setup now +- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough + +## Gotchas + +- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. +- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. +- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. +- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. +- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. +- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. +- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. +- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. +- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. +- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment +- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Human Handoff + +If `npx convex dev` or deployment setup requires human input: + +- stop and explain exactly what the user needs to do +- say why that step is required +- resume the auth setup immediately after the user confirms it is done + +## Validation + +- Verify the user can complete a sign-in flow +- Offer to validate sign up, sign out, and sign back in with the configured auth method +- If browser automation is available in the environment, you can do this directly +- If browser automation is not available, give the user a short manual validation checklist instead +- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions +- Verify protected UI only renders after Convex-authenticated state is ready +- Verify environment variables and redirect settings match the current app environment +- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in +- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed +- If production-ready setup was requested, verify the production deployment is also configured correctly + +## Checklist + +- [ ] Confirm the user wants Convex Auth specifically +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Ensure a Convex deployment is configured before running auth initialization +- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` +- [ ] Run `npx convex dev` first if needed +- [ ] Run `npx @convex-dev/auth` +- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created +- [ ] Follow the setup guide for package install and wiring +- [ ] Add `authTables` to `convex/schema.ts` +- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` +- [ ] Configure at least one auth method in `convex/auth.ts` +- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes +- [ ] Confirm which sign-in methods the app needs +- [ ] Verify the client can sign in and the backend receives authenticated identity +- [ ] Offer end-to-end validation of sign up, sign out, and sign back in +- [ ] If requested, configure the production deployment too +- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.agents/skills/convex-setup-auth/references/workos-authkit.md b/.agents/skills/convex-setup-auth/references/workos-authkit.md new file mode 100644 index 00000000..038cb9f3 --- /dev/null +++ b/.agents/skills/convex-setup-auth/references/workos-authkit.md @@ -0,0 +1,114 @@ +# WorkOS AuthKit + +Official docs: + +- https://docs.convex.dev/auth/authkit/ +- https://docs.convex.dev/auth/authkit/add-to-app +- https://docs.convex.dev/auth/authkit/auto-provision + +Use this when the app already uses WorkOS or the user wants AuthKit specifically. + +## Workflow + +1. Confirm the user wants WorkOS AuthKit +2. Determine whether they want: + - a Convex-managed WorkOS team + - an existing WorkOS team +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and WorkOS AuthKit guide +5. Create or update `convex.json` for the app's framework and real local port +6. Follow the correct branch of the setup flow based on that choice +7. Configure the required WorkOS environment variables +8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs +9. Wire the client provider and callback flow +10. Verify authenticated requests reach Convex +11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too +12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex + +## What To Do + +- Read the official Convex and WorkOS AuthKit guide before writing setup code +- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team +- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra +- Follow the current setup flow from the docs instead of relying on older examples + +## Key Setup Areas + +- package installation for the app's framework +- `convex.json` with the `authKit` section for dev, and preview or prod if needed +- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration +- `convex/auth.config.ts` wiring for WorkOS-issued JWTs +- client provider setup and token flow into Convex +- login callback and redirect configuration + +## Files and Env Vars To Expect + +- `convex.json` +- `convex/auth.config.ts` +- frontend auth provider wiring +- callback or redirect route setup where the framework requires it +- WorkOS environment variables commonly include: + - `WORKOS_CLIENT_ID` + - `WORKOS_API_KEY` + - `WORKOS_COOKIE_PASSWORD` + - `VITE_WORKOS_CLIENT_ID` + - `VITE_WORKOS_REDIRECT_URI` + - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` + +For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. + +## Concrete Steps + +1. Choose Convex-managed or existing WorkOS team +2. Create or update `convex.json` with the `authKit` section for the framework in use +3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port +4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow +5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` +6. Create or update `convex/auth.config.ts` for WorkOS JWT validation +7. Run the normal Convex dev or deploy flow so backend config is synced +8. Wire the WorkOS client provider in the app +9. Configure callback and redirect handling +10. Verify the user can sign in and return to the app +11. Verify Convex sees the authenticated user after login +12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too + +## Gotchas + +- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious +- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys +- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex +- Do not mix dev and prod WorkOS credentials or redirect URIs +- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it +- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. +- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. +- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. +- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. +- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered +- Verify the production redirect and callback settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the login flow and return to the app +- Verify the callback URL matches the real frontend port in local dev +- Verify Convex receives authenticated requests after login +- Verify `convex.json` matches the framework and chosen WorkOS setup path +- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path +- Verify environment variables differ correctly between local and production where needed +- If production-ready setup was requested, verify the production WorkOS configuration is also covered + +## Checklist + +- [ ] Confirm the user wants WorkOS AuthKit +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Choose Convex-managed or existing WorkOS team +- [ ] Create or update `convex.json` +- [ ] Configure WorkOS environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify authenticated requests reach Convex after login +- [ ] If requested, configure the production deployment too diff --git a/.claude/skills/convex-create-component/SKILL.md b/.claude/skills/convex-create-component/SKILL.md new file mode 100644 index 00000000..effe01fa --- /dev/null +++ b/.claude/skills/convex-create-component/SKILL.md @@ -0,0 +1,411 @@ +--- +name: convex-create-component +description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. +--- + +# Convex Create Component + +Create reusable Convex components with clear boundaries and a small app-facing API. + +## When to Use + +- Creating a new Convex component in an existing app +- Extracting reusable backend logic into a component +- Building a third-party integration that should own its own tables and workflows +- Packaging Convex functionality for reuse across multiple apps + +## When Not to Use + +- One-off business logic that belongs in the main app +- Thin utilities that do not need Convex tables or functions +- App-level orchestration that should stay in `convex/` +- Cases where a normal TypeScript library is enough + +## Workflow + +1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. +2. Choose the shape using the decision tree below and read the matching reference file. +3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. +4. Make a short plan for: + - what tables the component owns + - what public functions it exposes + - what data must be passed in from the app (auth, env vars, parent IDs) + - what stays in the app as wrappers or HTTP mounts +5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. +6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. +7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. +8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. +9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. +10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. + +## Choose the Shape + +Ask the user, then pick one path: + +| Goal | Shape | Reference | +|------|-------|-----------| +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | + +Read exactly one reference file before proceeding. + +## Default Approach + +Unless the user explicitly wants an npm package, default to a local component: + +- Put it under `convex/components//` +- Define it with `defineComponent(...)` in its own `convex.config.ts` +- Install it from the app's `convex/convex.config.ts` with `app.use(...)` +- Let `npx convex dev` generate the component's own `_generated/` files + +## Component Skeleton + +A minimal local component with a table and two functions, plus the app wiring. + +```ts +// convex/components/notifications/convex.config.ts +import { defineComponent } from "convex/server"; + +export default defineComponent("notifications"); +``` + +```ts +// convex/components/notifications/schema.ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notifications: defineTable({ + userId: v.string(), + message: v.string(), + read: v.boolean(), + }).index("by_user", ["userId"]), +}); +``` + +```ts +// convex/components/notifications/lib.ts +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server.js"; + +export const send = mutation({ + args: { userId: v.string(), message: v.string() }, + returns: v.id("notifications"), + handler: async (ctx, args) => { + return await ctx.db.insert("notifications", { + userId: args.userId, + message: args.message, + read: false, + }); + }, +}); + +export const listUnread = query({ + args: { userId: v.string() }, + returns: v.array( + v.object({ + _id: v.id("notifications"), + _creationTime: v.number(), + userId: v.string(), + message: v.string(), + read: v.boolean(), + }) + ), + handler: async (ctx, args) => { + return await ctx.db + .query("notifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .filter((q) => q.eq(q.field("read"), false)) + .collect(); + }, +}); +``` + +```ts +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import notifications from "./components/notifications/convex.config.js"; + +const app = defineApp(); +app.use(notifications); + +export default app; +``` + +```ts +// convex/notifications.ts (app-side wrapper) +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server"; +import { components } from "./_generated/api"; +import { getAuthUserId } from "@convex-dev/auth/server"; + +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); + +export const myUnread = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + return await ctx.runQuery(components.notifications.lib.listUnread, { + userId, + }); + }, +}); +``` + +Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. + +## Critical Rules + +- Keep authentication in the app. `ctx.auth` is not available inside components. +- Keep environment access in the app. Component functions cannot read `process.env`. +- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. +- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. +- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. +- Do not expose component functions directly to clients. Create app wrappers when client access is needed. +- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. +- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. +- Add `args` and `returns` validators to all public component functions. + +## Patterns + +### Authentication and environment access + +```ts +// Bad: component code cannot rely on app auth or env +const identity = await ctx.auth.getUserIdentity(); +const apiKey = process.env.OPENAI_API_KEY; +``` + +```ts +// Good: the app resolves auth and env, then passes explicit values +const userId = await getAuthUserId(ctx); +if (!userId) throw new Error("Not authenticated"); + +await ctx.runAction(components.translator.translate, { + userId, + apiKey: process.env.OPENAI_API_KEY, + text: args.text, +}); +``` + +### Client-facing API + +```ts +// Bad: assuming a component function is directly callable by clients +export const send = components.notifications.send; +``` + +```ts +// Good: re-export through an app mutation or query +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); +``` + +### IDs across the boundary + +```ts +// Bad: parent app table IDs are not valid component validators +args: { userId: v.id("users") } +``` + +```ts +// Good: treat parent-owned IDs as strings at the boundary +args: { userId: v.string() } +``` + +### Function Handles for callbacks + +When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. + +```ts +// App side: create a handle and pass it to the component +import { createFunctionHandle } from "convex/server"; + +export const startJob = mutation({ + handler: async (ctx) => { + const handle = await createFunctionHandle(internal.myModule.processItem); + await ctx.runMutation(components.workpool.enqueue, { + callback: handle, + }); + }, +}); +``` + +```ts +// Component side: accept and invoke the handle +import { v } from "convex/values"; +import type { FunctionHandle } from "convex/server"; +import { mutation } from "./_generated/server.js"; + +export const enqueue = mutation({ + args: { callback: v.string() }, + handler: async (ctx, args) => { + const handle = args.callback as FunctionHandle<"mutation">; + await ctx.scheduler.runAfter(0, handle, {}); + }, +}); +``` + +### Deriving validators from schema + +Instead of manually repeating field types in return validators, extend the schema validator: + +```ts +import { v } from "convex/values"; +import schema from "./schema.js"; + +const notificationDoc = schema.tables.notifications.validator.extend({ + _id: v.id("notifications"), + _creationTime: v.number(), +}); + +export const getLatest = query({ + args: {}, + returns: v.nullable(notificationDoc), + handler: async (ctx) => { + return await ctx.db.query("notifications").order("desc").first(); + }, +}); +``` + +### Static configuration with a globals table + +A common pattern for component configuration is a single-document "globals" table: + +```ts +// schema.ts +export default defineSchema({ + globals: defineTable({ + maxRetries: v.number(), + webhookUrl: v.optional(v.string()), + }), + // ... other tables +}); +``` + +```ts +// lib.ts +export const configure = mutation({ + args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, args) => { + const existing = await ctx.db.query("globals").first(); + if (existing) { + await ctx.db.patch(existing._id, args); + } else { + await ctx.db.insert("globals", args); + } + return null; + }, +}); +``` + +### Class-based client wrappers + +For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. + +```ts +// src/client/index.ts +import type { GenericMutationCtx, GenericDataModel } from "convex/server"; +import type { ComponentApi } from "../component/_generated/component.js"; + +type MutationCtx = Pick, "runMutation">; + +export class Notifications { + constructor( + private component: ComponentApi, + private options?: { defaultChannel?: string }, + ) {} + + async send(ctx: MutationCtx, args: { userId: string; message: string }) { + return await ctx.runMutation(this.component.lib.send, { + ...args, + channel: this.options?.defaultChannel ?? "default", + }); + } +} +``` + +```ts +// App usage +import { Notifications } from "@convex-dev/notifications"; +import { components } from "./_generated/api"; + +const notifications = new Notifications(components.notifications, { + defaultChannel: "alerts", +}); + +export const send = mutation({ + args: { message: v.string() }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + await notifications.send(ctx, { userId, message: args.message }); + }, +}); +``` + +## Validation + +Try validation in this order: + +1. `npx convex codegen --component-dir convex/components/` +2. `npx convex codegen` +3. `npx convex dev` + +Important: + +- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. +- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. +- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. + +## Reference Files + +Read exactly one of these after the user confirms the goal: + +- `references/local-components.md` +- `references/packaged-components.md` +- `references/hybrid-components.md` + +Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) + +## Checklist + +- [ ] Asked the user what they want to build and confirmed the shape +- [ ] Read the matching reference file +- [ ] Confirmed a component is the right abstraction +- [ ] Planned tables, public API, boundaries, and app wrappers +- [ ] Component lives under `convex/components//` (or package layout if publishing) +- [ ] Component imports from its own `./_generated/server` +- [ ] Auth, env access, and HTTP routes stay in the app +- [ ] Parent app IDs cross the boundary as `v.string()` +- [ ] Public functions have `args` and `returns` validators +- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.claude/skills/convex-create-component/agents/openai.yaml b/.claude/skills/convex-create-component/agents/openai.yaml new file mode 100644 index 00000000..ba9287e4 --- /dev/null +++ b/.claude/skills/convex-create-component/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Create Component" + short_description: "Design and build reusable Convex components with clear boundaries." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#14B8A6" + default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." + +policy: + allow_implicit_invocation: true diff --git a/.claude/skills/convex-create-component/assets/icon.svg b/.claude/skills/convex-create-component/assets/icon.svg new file mode 100644 index 00000000..10f4c2c4 --- /dev/null +++ b/.claude/skills/convex-create-component/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.claude/skills/convex-create-component/references/hybrid-components.md b/.claude/skills/convex-create-component/references/hybrid-components.md new file mode 100644 index 00000000..d2bb3514 --- /dev/null +++ b/.claude/skills/convex-create-component/references/hybrid-components.md @@ -0,0 +1,37 @@ +# Hybrid Convex Components + +Read this file only when the user explicitly wants a hybrid setup. + +## What This Means + +A hybrid component combines a local Convex component with shared library code. + +This can help when: + +- the user wants a local install but also shared package logic +- the component needs extension points or override hooks +- some logic should live in normal TypeScript code outside the component boundary + +## Default Advice + +Treat hybrid as an advanced option, not the default. + +Before choosing it, ask: + +- Why is a plain local component not enough? +- Why is a packaged component not enough? +- What exactly needs to stay overridable or shared? + +If the answer is vague, fall back to local or packaged. + +## Risks + +- More moving parts +- Harder upgrades and backwards compatibility +- Easier to blur the component boundary + +## Checklist + +- [ ] User explicitly needs hybrid behavior +- [ ] Local-only and packaged-only options were considered first +- [ ] The extension points are clearly defined before coding diff --git a/.claude/skills/convex-create-component/references/local-components.md b/.claude/skills/convex-create-component/references/local-components.md new file mode 100644 index 00000000..7fbfe21a --- /dev/null +++ b/.claude/skills/convex-create-component/references/local-components.md @@ -0,0 +1,38 @@ +# Local Convex Components + +Read this file when the component should live inside the current app and does not need to be published as an npm package. + +## When to Choose This + +- The user wants the simplest path +- The component only needs to work in this repo +- The goal is extracting app logic into a cleaner boundary + +## Default Layout + +Use this structure unless the repo already has a clear alternative pattern: + +```text +convex/ + convex.config.ts + components/ + / + convex.config.ts + schema.ts + .ts +``` + +## Workflow Notes + +- Define the component with `defineComponent("")` +- Install it from the app with `defineApp()` and `app.use(...)` +- Keep auth, env access, public API wrappers, and HTTP route mounting in the app +- Let the component own isolated tables and reusable backend workflows +- Add app wrappers if clients need to call into the component + +## Checklist + +- [ ] Component is inside `convex/components//` +- [ ] App installs it with `app.use(...)` +- [ ] Component owns only its own tables +- [ ] App wrappers handle client-facing calls when needed diff --git a/.claude/skills/convex-create-component/references/packaged-components.md b/.claude/skills/convex-create-component/references/packaged-components.md new file mode 100644 index 00000000..5668e7ed --- /dev/null +++ b/.claude/skills/convex-create-component/references/packaged-components.md @@ -0,0 +1,51 @@ +# Packaged Convex Components + +Read this file when the user wants a reusable npm package or a component shared across multiple apps. + +## When to Choose This + +- The user wants to publish the component +- The user wants a stable reusable package boundary +- The component will be shared across multiple apps or teams + +## Default Approach + +- Prefer starting from `npx create-convex@latest --component` when possible +- Keep the official authoring docs as the source of truth for package layout and exports +- Validate the bundled package through an example app, not just the source files + +## Build Flow + +When building a packaged component, make sure the bundled output exists before the example app tries to consume it. + +Recommended order: + +1. `npx convex codegen --component-dir ./path/to/component` +2. Run the package build command +3. Run `npx convex dev --typecheck-components` in the example app + +Do not assume normal app codegen is enough for packaged component workflows. + +## Package Exports + +If publishing to npm, make sure the package exposes the entry points apps need: + +- package root for client helpers, types, or classes +- `./convex.config.js` for installing the component +- `./_generated/component.js` for the app-facing `ComponentApi` type +- `./test` for testing helpers when applicable + +## Testing + +- Use `convex-test` for component logic +- Register the component schema and modules with the test instance +- Test app-side wrapper code from an example app that installs the package +- Export a small helper from `./test` if consumers need easy test registration + +## Checklist + +- [ ] Packaging is actually required +- [ ] Build order avoids bundle and codegen races +- [ ] Package exports include install and typing entry points +- [ ] Example app exercises the packaged component +- [ ] Core behavior is covered by tests diff --git a/.claude/skills/convex-migration-helper/SKILL.md b/.claude/skills/convex-migration-helper/SKILL.md new file mode 100644 index 00000000..f353678f --- /dev/null +++ b/.claude/skills/convex-migration-helper/SKILL.md @@ -0,0 +1,524 @@ +--- +name: convex-migration-helper +description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. +--- + +# Convex Migration Helper + +Safely migrate Convex schemas and data when making breaking changes. + +## When to Use + +- Adding new required fields to existing tables +- Changing field types or structure +- Splitting or merging tables +- Renaming or deleting fields +- Migrating from nested to relational data + +## Key Concepts + +### Schema Validation Drives the Workflow + +Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: + +- You cannot add a required field if existing documents don't have it +- You cannot change a field's type if existing documents have the old type +- You cannot remove a field from the schema if existing documents still have it + +This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. + +### Online Migrations + +Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. + +### Prefer New Fields Over Changing Types + +When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. + +### Don't Delete Data + +Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. + +## Safe Changes (No Migration Needed) + +### Adding Optional Field + +```typescript +// Before +users: defineTable({ + name: v.string(), +}) + +// After - safe, new field is optional +users: defineTable({ + name: v.string(), + bio: v.optional(v.string()), +}) +``` + +### Adding New Table + +```typescript +posts: defineTable({ + userId: v.id("users"), + title: v.string(), +}).index("by_user", ["userId"]) +``` + +### Adding Index + +```typescript +users: defineTable({ + name: v.string(), + email: v.string(), +}) + .index("by_email", ["email"]) +``` + +## Breaking Changes: The Deployment Workflow + +Every breaking migration follows the same multi-deploy pattern: + +**Deploy 1 - Widen the schema:** + +1. Update schema to allow both old and new formats (e.g., add optional new field) +2. Update code to handle both formats when reading +3. Update code to write the new format for new documents +4. Deploy + +**Between deploys - Migrate data:** + +5. Run migration to backfill existing documents +6. Verify all documents are migrated + +**Deploy 2 - Narrow the schema:** + +7. Update schema to require the new format only +8. Remove code that handles the old format +9. Deploy + +## Using the Migrations Component (Recommended) + +For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. + +### Installation + +```bash +npm install @convex-dev/migrations +``` + +### Setup + +```typescript +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import migrations from "@convex-dev/migrations/convex.config.js"; + +const app = defineApp(); +app.use(migrations); +export default app; +``` + +```typescript +// convex/migrations.ts +import { Migrations } from "@convex-dev/migrations"; +import { components } from "./_generated/api.js"; +import { DataModel } from "./_generated/dataModel.js"; + +export const migrations = new Migrations(components.migrations); +export const run = migrations.runner(); +``` + +The `DataModel` type parameter is optional but provides type safety for migration definitions. + +### Define a Migration + +The `migrateOne` function processes a single document. The component handles batching and pagination automatically. + +```typescript +// convex/migrations.ts +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); +``` + +Shorthand: if you return an object, it is applied as a patch automatically. + +```typescript +export const clearDeprecatedField = migrations.define({ + table: "users", + migrateOne: () => ({ legacyField: undefined }), +}); +``` + +### Run a Migration + +From the CLI: + +```bash +# Define a one-off runner in convex/migrations.ts: +# export const runIt = migrations.runner(internal.migrations.addDefaultRole); +npx convex run migrations:runIt + +# Or use the general-purpose runner +npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' +``` + +Programmatically from another Convex function: + +```typescript +await migrations.runOne(ctx, internal.migrations.addDefaultRole); +``` + +### Run Multiple Migrations in Order + +```typescript +export const runAll = migrations.runner([ + internal.migrations.addDefaultRole, + internal.migrations.clearDeprecatedField, + internal.migrations.normalizeEmails, +]); +``` + +```bash +npx convex run migrations:runAll +``` + +If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. + +### Dry Run + +Test a migration before committing changes: + +```bash +npx convex run migrations:runIt '{"dryRun": true}' +``` + +This runs one batch and then rolls back, so you can see what it would do without changing any data. + +### Check Migration Status + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +### Cancel a Running Migration + +```bash +npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' +``` + +Or programmatically: + +```typescript +await migrations.cancel(ctx, internal.migrations.addDefaultRole); +``` + +### Run Migrations on Deploy + +Chain migration execution after deploying: + +```bash +npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod +``` + +### Configuration Options + +#### Custom Batch Size + +If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: + +```typescript +export const migrateHeavyTable = migrations.define({ + table: "largeDocuments", + batchSize: 10, + migrateOne: async (ctx, doc) => { + // migration logic + }, +}); +``` + +#### Migrate a Subset Using an Index + +Process only matching documents instead of the full table: + +```typescript +export const fixEmptyNames = migrations.define({ + table: "users", + customRange: (query) => + query.withIndex("by_name", (q) => q.eq("name", "")), + migrateOne: () => ({ name: "" }), +}); +``` + +#### Parallelize Within a Batch + +By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: + +```typescript +export const clearField = migrations.define({ + table: "myTable", + parallelize: true, + migrateOne: () => ({ optionalField: undefined }), +}); +``` + +## Common Migration Patterns + +### Adding a Required Field + +```typescript +// Deploy 1: Schema allows both states +users: defineTable({ + name: v.string(), + role: v.optional(v.union(v.literal("user"), v.literal("admin"))), +}) + +// Migration: backfill the field +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); + +// Deploy 2: After migration completes, make it required +users: defineTable({ + name: v.string(), + role: v.union(v.literal("user"), v.literal("admin")), +}) +``` + +### Deleting a Field + +Mark the field optional first, migrate data to remove it, then remove from schema: + +```typescript +// Deploy 1: Make optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()) + +// Migration +export const removeIsPro = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.isPro !== undefined) { + await ctx.db.patch(team._id, { isPro: undefined }); + } + }, +}); + +// Deploy 2: Remove isPro from schema entirely +``` + +### Changing a Field Type + +Prefer creating a new field. You can combine adding and deleting in one migration: + +```typescript +// Deploy 1: Add new field, keep old field optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) + +// Migration: convert old field to new field +export const convertToEnum = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.plan === undefined) { + await ctx.db.patch(team._id, { + plan: team.isPro ? "pro" : "basic", + isPro: undefined, + }); + } + }, +}); + +// Deploy 2: Remove isPro from schema, make plan required +``` + +### Splitting Nested Data Into a Separate Table + +```typescript +export const extractPreferences = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.preferences === undefined) return; + + const existing = await ctx.db + .query("userPreferences") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .first(); + + if (!existing) { + await ctx.db.insert("userPreferences", { + userId: user._id, + ...user.preferences, + }); + } + + await ctx.db.patch(user._id, { preferences: undefined }); + }, +}); +``` + +Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. + +### Cleaning Up Orphaned Documents + +```typescript +export const deleteOrphanedEmbeddings = migrations.define({ + table: "embeddings", + migrateOne: async (ctx, doc) => { + const chunk = await ctx.db + .query("chunks") + .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) + .first(); + + if (!chunk) { + await ctx.db.delete(doc._id); + } + }, +}); +``` + +## Migration Strategies for Zero Downtime + +During the migration window, your app must handle both old and new data formats. There are two main strategies. + +### Dual Write (Preferred) + +Write to both old and new structures. Read from the old structure until migration is complete. + +1. Deploy code that writes both formats, reads old format +2. Run migration on existing data +3. Deploy code that reads new format, still writes both +4. Deploy code that only reads and writes new format + +This is preferred because you can safely roll back at any point, the old format is always up to date. + +```typescript +// Bad: only writing to new structure before migration is done +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + await ctx.db.insert("teams", { + name: args.name, + plan: args.isPro ? "pro" : "basic", + }); + }, +}); + +// Good: writing to both structures during migration +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + const plan = args.isPro ? "pro" : "basic"; + await ctx.db.insert("teams", { + name: args.name, + isPro: args.isPro, + plan, + }); + }, +}); +``` + +### Dual Read + +Read both formats. Write only the new format. + +1. Deploy code that reads both formats (preferring new), writes only new format +2. Run migration on existing data +3. Deploy code that reads and writes only new format + +This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. + +```typescript +// Good: reading both formats, preferring new +function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { + if (team.plan !== undefined) return team.plan; + return team.isPro ? "pro" : "basic"; +} +``` + +## Small Table Shortcut + +For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: + +```typescript +import { internalMutation } from "./_generated/server"; + +export const backfillSmallTable = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("smallConfig").collect(); + for (const doc of docs) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: "default" }); + } + } + }, +}); +``` + +```bash +npx convex run migrations:backfillSmallTable +``` + +Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. + +## Verifying a Migration + +Query to check remaining unmigrated documents: + +```typescript +import { query } from "./_generated/server"; + +export const verifyMigration = query({ + handler: async (ctx) => { + const remaining = await ctx.db + .query("users") + .filter((q) => q.eq(q.field("role"), undefined)) + .take(10); + + return { + complete: remaining.length === 0, + sampleRemaining: remaining.map((u) => u._id), + }; + }, +}); +``` + +Or use the component's built-in status monitoring: + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +## Migration Checklist + +- [ ] Identify the breaking change and plan the multi-deploy workflow +- [ ] Update schema to allow both old and new formats +- [ ] Update code to handle both formats when reading +- [ ] Update code to write the new format for new documents +- [ ] Deploy widened schema and updated code +- [ ] Define migration using the `@convex-dev/migrations` component +- [ ] Test with `dryRun: true` +- [ ] Run migration and monitor status +- [ ] Verify all documents are migrated +- [ ] Update schema to require new format only +- [ ] Clean up code that handled old format +- [ ] Deploy final schema and code +- [ ] Remove migration code once confirmed stable + +## Common Pitfalls + +1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. +2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. +3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. +4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. +5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. +6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/.claude/skills/convex-migration-helper/agents/openai.yaml b/.claude/skills/convex-migration-helper/agents/openai.yaml new file mode 100644 index 00000000..c2a7fcc5 --- /dev/null +++ b/.claude/skills/convex-migration-helper/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Migration Helper" + short_description: "Plan and run safe Convex schema and data migrations." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#8B5CF6" + default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." + +policy: + allow_implicit_invocation: true diff --git a/.claude/skills/convex-migration-helper/assets/icon.svg b/.claude/skills/convex-migration-helper/assets/icon.svg new file mode 100644 index 00000000..fba7241a --- /dev/null +++ b/.claude/skills/convex-migration-helper/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.claude/skills/convex-performance-audit/SKILL.md b/.claude/skills/convex-performance-audit/SKILL.md new file mode 100644 index 00000000..6ee0417f --- /dev/null +++ b/.claude/skills/convex-performance-audit/SKILL.md @@ -0,0 +1,143 @@ +--- +name: convex-performance-audit +description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. +--- + +# Convex Performance Audit + +Diagnose and fix performance problems in Convex applications, one problem class at a time. + +## When to Use + +- A Convex page or feature feels slow or expensive +- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts +- Low-freshness read paths are using reactivity where point-in-time reads would do +- OCC conflict errors or excessive mutation retries +- High subscription count or slow UI updates +- Functions approaching execution or transaction limits +- The same performance pattern needs fixing across sibling functions + +## When Not to Use + +- Initial Convex setup, auth setup, or component extraction +- Pure schema migrations with no performance goal +- One-off micro-optimizations without a user-visible or deployment-visible problem + +## Guardrails + +- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak +- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path +- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale + +## First Step: Gather Signals + +Start with the strongest signal available: + +1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. +2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. + - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. +3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. +4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. + +## Signal Routing + +After gathering signals, identify the problem class and read the matching reference file. + +| Signal | Reference | +|---|---| +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | + +Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. + +## Escalate Larger Fixes + +If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. + +Examples: + +- introducing digest or summary tables across multiple flows +- splitting documents to isolate frequently-updated fields +- reworking pagination or fetch strategy across several screens +- switching to a new index or denormalized field that needs migration-safe rollout + +When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. + +## Workflow + +### 1. Scope the problem + +Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. + +Write down: + +- entrypoint functions +- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` +- tables read +- tables written +- whether the path is high-read, high-write, or both + +### 2. Trace the full read and write set + +For each function in the path: + +1. Trace every `ctx.db.get()` and `ctx.db.query()` +2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` +3. Note foreign-key lookups, JS-side filtering, and full-document reads +4. Identify all sibling functions touching the same tables +5. Identify reactive stats, aggregates, or widgets rendered on the same page + +In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. + +### 3. Apply fixes from the relevant reference + +Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. + +Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. + +### 4. Fix sibling functions together + +When one function touching a table has a performance bug, audit sibling functions for the same pattern. + +After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. + +Examples: + +- If one list query switches from full docs to a digest table, inspect the other list queries for that table +- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk + +Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. + +### 5. Verify before finishing + +Confirm all of these: + +1. Results are the same as before, no dropped records +2. Eliminated reads or writes are no longer in the path where expected +3. Fallback behavior works when denormalized or indexed fields are missing +4. New writes avoid unnecessary invalidation when data is unchanged +5. Every relevant sibling reader and writer was inspected, not just the original function + +## Reference Files + +- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables +- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting +- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads +- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size + +Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. + +## Checklist + +- [ ] Gathered signals from insights, dashboard, or code audit +- [ ] Identified the problem class and read the matching reference +- [ ] Scoped one concrete user flow or function path +- [ ] Traced every read and write in that path +- [ ] Identified sibling functions touching the same tables +- [ ] Applied fixes from the reference, following the recommended fix order +- [ ] Fixed sibling functions consistently +- [ ] Verified behavior and confirmed no regressions diff --git a/.claude/skills/convex-performance-audit/agents/openai.yaml b/.claude/skills/convex-performance-audit/agents/openai.yaml new file mode 100644 index 00000000..9a21f387 --- /dev/null +++ b/.claude/skills/convex-performance-audit/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Performance Audit" + short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#EF4444" + default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." + +policy: + allow_implicit_invocation: true diff --git a/.claude/skills/convex-performance-audit/assets/icon.svg b/.claude/skills/convex-performance-audit/assets/icon.svg new file mode 100644 index 00000000..7ab9e09c --- /dev/null +++ b/.claude/skills/convex-performance-audit/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.claude/skills/convex-performance-audit/references/function-budget.md b/.claude/skills/convex-performance-audit/references/function-budget.md new file mode 100644 index 00000000..c71d14cb --- /dev/null +++ b/.claude/skills/convex-performance-audit/references/function-budget.md @@ -0,0 +1,232 @@ +# Function Budget + +Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. + +## Core Principle + +Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. + +## Limits to Know + +These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. + +| Resource | Limit | +|---|---| +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | +| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | + +## Symptoms + +- "Function execution took too long" errors +- "Transaction too large" or read/write set size errors +- Slow queries that read many documents +- Client receiving large payloads that slow down page load +- `npx convex insights --details` showing high bytes read + +## Common Causes + +### Unbounded collection + +A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. + +### Large document reads on hot paths + +Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. + +### Mutation doing too much work + +A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. + +### Returning too much data to the client + +A query returning full documents when the client only needs a few fields. + +## Fix Order + +### 1. Bound your reads + +Never `.collect()` without a limit on a table that can grow unbounded. + +```ts +// Bad: unbounded read, breaks as the table grows +const messages = await ctx.db.query("messages").collect(); +``` + +```ts +// Good: paginate or limit +const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", channelId)) + .order("desc") + .take(50); +``` + +### 2. Read smaller shapes + +If the list page only needs title, author, and date, do not read full documents with rich content fields. + +Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. + +### 3. Break large mutations into batches + +If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. + +```ts +// Bad: one mutation updating every row +export const backfillAll = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("items").collect(); + for (const doc of docs) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + }, +}); +``` + +```ts +// Good: cursor-based batch processing +export const backfillBatch = internalMutation({ + args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, + handler: async (ctx, args) => { + const batchSize = args.batchSize ?? 100; + const result = await ctx.db + .query("items") + .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); + + for (const doc of result.page) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + } + + if (!result.isDone) { + await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { + cursor: result.continueCursor, + batchSize, + }); + } + }, +}); +``` + +### 4. Move heavy work to actions + +Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. + +Actions run outside the transaction and can call mutations to write results back. + +```ts +// Bad: heavy computation inside a mutation +export const processUpload = mutation({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.db.insert("results", result); + }, +}); +``` + +```ts +// Good: action for heavy work, mutation for the write +export const processUpload = action({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.runMutation(internal.results.store, { result }); + }, +}); +``` + +### 5. Trim return values + +Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. + +```ts +// Bad: returns full documents including large content fields +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("articles").take(20); + }, +}); +``` + +```ts +// Good: project to only the fields the client needs +export const list = query({ + handler: async (ctx) => { + const articles = await ctx.db.query("articles").take(20); + return articles.map((a) => ({ + _id: a._id, + title: a.title, + author: a.author, + createdAt: a._creationTime, + })); + }, +}); +``` + +### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions + +Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. + +```ts +// Bad: unnecessary overhead from ctx.runQuery inside a mutation +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await ctx.runQuery(api.users.getCurrentUser); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +```ts +// Good: plain helper function, no extra overhead +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await getCurrentUser(ctx); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. + +### 7. Avoid unnecessary `runAction` calls + +`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). + +```ts +// Bad: runAction overhead for no reason +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await ctx.runAction(internal.items.processOne, { item }); + } + }, +}); +``` + +```ts +// Good: plain function call +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await processOneItem(ctx, { item }); + } + }, +}); +``` + +## Verification + +1. No function execution or transaction size errors +2. `npx convex insights --details` shows reduced bytes read +3. Large mutations are batched and self-scheduling +4. Client payloads are reasonably sized for the UI they serve +5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible +6. Sibling functions with similar patterns were checked diff --git a/.claude/skills/convex-performance-audit/references/hot-path-rules.md b/.claude/skills/convex-performance-audit/references/hot-path-rules.md new file mode 100644 index 00000000..96a7b94e --- /dev/null +++ b/.claude/skills/convex-performance-audit/references/hot-path-rules.md @@ -0,0 +1,359 @@ +# Hot Path Rules + +Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. + +## Core Principle + +Every byte read or written multiplies with concurrency. + +Think: + +`cost x calls_per_second x 86400` + +In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. + +## Consistency Rule + +If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. + +Do this especially for: + +- multiple list queries over the same table +- multiple writers to the same table +- public browse and search queries over the same records +- helper functions reused by more than one endpoint + +## 1. Push Filters To Storage + +Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. + +Prefer: + +- `withIndex(...)` +- `.withSearchIndex(...)` for text search +- narrower tables +- summary tables + +before accepting a scan-plus-filter pattern. + +```ts +// Bad: scans then filters in JavaScript +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + const tasks = await ctx.db.query("tasks").collect(); + return tasks.filter((task) => task.status === "open"); + }, +}); +``` + +```ts +// Also bad: Convex .filter() does not push to storage either +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .filter((q) => q.eq(q.field("status"), "open")) + .collect(); + }, +}); +``` + +```ts +// Good: use an index so storage does the filtering +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .withIndex("by_status", (q) => q.eq("status", "open")) + .collect(); + }, +}); +``` + +### Migration rule for indexes + +New indexes on partially backfilled fields can create correctness bugs during rollout. + +Important Convex detail: + +`undefined !== false` + +If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. + +Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. + +If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. + +```ts +// Bad: optional booleans can miss older rows where the field is undefined +const projects = await ctx.db + .query("projects") + .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) + .order("desc") + .take(20); +``` + +```ts +// Good: switch hot-path reads only after the rollout is migration-safe +// See the migration helper skill for dual-read / backfill / cutover patterns. +``` + +### Check for redundant indexes + +Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. + +```ts +// Bad: two indexes where one would do +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team", ["team"]) + .index("by_team_and_user", ["team", "user"]) +``` + +```ts +// Good: single compound index serves both query patterns +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team_and_user", ["team", "user"]) +``` + +Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. + +## 2. Minimize Data Sources + +Trace every read. + +If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. + +### When to denormalize + +Denormalize when all of these are true: + +- the path is hot +- the joined document is much larger than the field you need +- many readers are paying that join cost repeatedly + +Useful mental model: + +`join_cost = rows_per_page x foreign_doc_size x pages_per_second` + +Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. + +### Fallback rule + +Denormalized data is an optimization. Live data is the correctness path. + +Rules: + +- If the denormalized field is missing or null, fall back to the live read +- Do not show placeholders instead of falling back +- In lookup maps, only include fully populated entries + +```ts +// Bad: missing denormalized data becomes a placeholder and blocks correctness +const ownerName = project.ownerName ?? "Unknown owner"; +``` + +```ts +// Good: denormalized data is an optimization, not the only source of truth +const ownerName = + project.ownerName ?? + (await ctx.db.get(project.ownerId))?.name ?? + null; +``` + +Bad lookup map pattern: + +```ts +const ownersById = { + [project.ownerId]: { ownerName: null }, +}; +``` + +That blocks fallback because the map says "I have data" when it does not. + +Good lookup map pattern: + +```ts +const ownersById = + project.ownerName !== undefined && project.ownerName !== null + ? { [project.ownerId]: { ownerName: project.ownerName } } + : {}; +``` + +### No denormalized copy yet + +Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. + +If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. + +Rollout order: + +1. Update schema +2. Update write path +3. Backfill +4. Switch read path + +## 3. Minimize Row Size + +Hot list pages should read the smallest document shape that still answers the UI. + +Prefer summary or digest tables over full source tables when: + +- the list page only needs a subset of fields +- source documents are large +- the query is high volume + +An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. + +Digest tables are a tradeoff, not a default: + +- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost +- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit + +```ts +// Bad: list page reads source docs, then joins owner data per row +const projects = await ctx.db + .query("projects") + .withIndex("by_public", (q) => q.eq("isPublic", true)) + .collect(); +``` + +```ts +// Good: list page reads the smaller digest shape first +const projects = await ctx.db + .query("projectDigests") + .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) + .order("desc") + .take(20); +``` + +## 4. Skip No-Op Writes + +No-op writes still cost work in Convex: + +- invalidation +- replication +- trigger execution +- downstream sync + +Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. + +Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. + +```ts +// Bad: patching unchanged values still triggers invalidation and downstream work +await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, +}); +``` + +```ts +// Good: only write when something actually changed +if (settings.theme !== args.theme || settings.locale !== args.locale) { + await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, + }); +} +``` + +## 5. Match Consistency To Read Patterns + +Choose read strategy based on traffic shape. + +### High-read, low-write + +Examples: + +- public browse pages +- search results +- landing pages +- directory listings + +Prefer: + +- point-in-time reads where appropriate +- explicit refresh +- local state for pagination +- caching where appropriate + +Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. + +### High-read, high-write + +Examples: + +- collaborative editors +- live dashboards +- presence-heavy views + +Reactive queries may be worth the ongoing cost. + +## Convex-Specific Notes + +### Reactive queries + +Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. + +On the client: + +- `useQuery` creates a live subscription +- `usePaginatedQuery` creates a live subscription per page + +For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. + +### Point-in-time reads + +Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. + +Use them for: + +- aggregate snapshots +- reports +- low-churn listings +- pages where explicit refresh is fine + +### Triggers and fan-out + +Triggers fire on every write, including writes that did not materially change the document. + +When a write exists only to keep derived state in sync: + +- diff before patching +- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate + +### Aggregates + +Reactive global counts invalidate frequently on busy tables. + +Prefer: + +- one-shot aggregate fetches +- periodic recomputation +- precomputed summary rows + +for global stats that do not need live updates every second. + +### Backfills + +For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. + +Deploy code that can handle both states before running the backfill. + +During the gap: + +- writes should populate the new shape +- reads should fall back safely + +## Verification + +Before closing the audit, confirm: + +1. Same results as before, no dropped records +2. The removed table or lookup is no longer in the hot-path read set +3. Tests or validation cover fallback behavior +4. Migration safety is preserved while fields or indexes are unbackfilled +5. Sibling functions were fixed consistently diff --git a/.claude/skills/convex-performance-audit/references/occ-conflicts.md b/.claude/skills/convex-performance-audit/references/occ-conflicts.md new file mode 100644 index 00000000..a96d0466 --- /dev/null +++ b/.claude/skills/convex-performance-audit/references/occ-conflicts.md @@ -0,0 +1,126 @@ +# OCC Conflict Resolution + +Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. + +## Core Principle + +Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. + +## Symptoms + +- OCC conflict errors in deployment logs or health page +- Mutations retrying multiple times before succeeding +- User-visible latency spikes on write-heavy pages +- `npx convex insights --details` showing high conflict rates + +## Common Causes + +### Hot documents + +Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. + +### Broad read sets causing false conflicts + +A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. + +### Fan-out from triggers or cascading writes + +A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. + +Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. + +### Write-then-read chains + +A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. + +## Fix Order + +### 1. Reduce read set size + +Narrower reads mean fewer false conflicts. + +```ts +// Bad: broad scan creates a wide conflict surface +const allTasks = await ctx.db.query("tasks").collect(); +const mine = allTasks.filter((t) => t.ownerId === userId); +``` + +```ts +// Good: indexed query touches only relevant documents +const mine = await ctx.db + .query("tasks") + .withIndex("by_owner", (q) => q.eq("ownerId", userId)) + .collect(); +``` + +### 2. Split hot documents + +When many writers target the same document, split the contention point. + +```ts +// Bad: every vote increments the same counter document +const counter = await ctx.db.get(pollCounterId); +await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); +``` + +```ts +// Good: shard the counter across multiple documents, aggregate on read +const shardIndex = Math.floor(Math.random() * SHARD_COUNT); +const shardId = shardIds[shardIndex]; +const shard = await ctx.db.get(shardId); +await ctx.db.patch(shardId, { count: shard!.count + 1 }); +``` + +Aggregate the shards in a query or scheduled job when you need the total. + +### 3. Skip no-op writes + +Writes that do not change data still participate in conflict detection and trigger invalidation. + +```ts +// Bad: patches even when nothing changed +await ctx.db.patch(doc._id, { status: args.status }); +``` + +```ts +// Good: only write when the value actually differs +if (doc.status !== args.status) { + await ctx.db.patch(doc._id, { status: args.status }); +} +``` + +### 4. Move non-critical work to scheduled functions + +If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. + +```ts +// Bad: analytics update in the same transaction as the user action +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +``` + +```ts +// Good: schedule the bookkeeping so the primary transaction is smaller +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { + event: "action", + userId, +}); +``` + +### 5. Combine competing writes + +If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. + +Do not introduce artificial locks or queues unless the above steps have been tried first. + +## Related: Invalidation Scope + +Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. + +## Verification + +1. OCC conflict rate has dropped in insights or dashboard +2. Mutation latency is lower and more consistent +3. No data correctness regressions from splitting or scheduling changes +4. Sibling writers to the same hot documents were fixed consistently diff --git a/.claude/skills/convex-performance-audit/references/subscription-cost.md b/.claude/skills/convex-performance-audit/references/subscription-cost.md new file mode 100644 index 00000000..ae7d1adb --- /dev/null +++ b/.claude/skills/convex-performance-audit/references/subscription-cost.md @@ -0,0 +1,252 @@ +# Subscription Cost + +Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. + +## Core Principle + +Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: + +`subscriptions x invalidation_frequency x query_cost` + +Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. + +## Symptoms + +- Dashboard shows high active subscription count +- UI feels sluggish or laggy despite fast individual queries +- React profiling shows frequent re-renders from Convex state +- Pages with many components each running their own `useQuery` +- Paginated lists where every loaded page stays subscribed + +## Common Causes + +### Reactive queries on low-freshness flows + +Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. + +### Overly broad queries + +A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. + +### Too many subscriptions per page + +A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. + +### Paginated queries keeping all pages live + +`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. + +### Frequently-updated fields on widely-read documents + +A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. + +## Fix Order + +### 1. Use point-in-time reads when live updates are not valuable + +Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. + +Consider a point-in-time read instead when all of these are true: + +- the flow is high-read +- the underlying data changes less often than users need to see +- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable + +Possible implementations depend on environment: + +- a server-rendered fetch +- a framework helper like `fetchQuery` +- a point-in-time client read such as `ConvexHttpClient.query()` + +```ts +// Reactive by default when fresh live data matters +function TeamPresence() { + const presence = useQuery(api.teams.livePresence, { teamId }); + return ; +} +``` + +```ts +// Point-in-time read when explicit refresh is acceptable +import { ConvexHttpClient } from "convex/browser"; + +const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); + +function SnapshotView() { + const [items, setItems] = useState([]); + + useEffect(() => { + client.query(api.items.snapshot).then(setItems); + }, []); + + return ; +} +``` + +Good candidates for point-in-time reads: + +- aggregate snapshots +- reports +- low-churn listings +- flows where explicit refresh is already acceptable + +Keep reactive for: + +- collaborative editing +- live dashboards +- presence-heavy views +- any surface where users expect fresh changes to appear automatically + +### 2. Batch related data into fewer queries + +Instead of N components each fetching their own related data, fetch it in a single query. + +```ts +// Bad: each card fetches its own author +function ProjectCard({ project }: { project: Project }) { + const author = useQuery(api.users.get, { id: project.authorId }); + return ; +} +``` + +```ts +// Good: parent query returns projects with author names included +function ProjectList() { + const projects = useQuery(api.projects.listWithAuthors); + return projects?.map((p) => ( + + )); +} +``` + +This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. + +This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. + +### 3. Use skip to avoid unnecessary subscriptions + +The `"skip"` value prevents a subscription from being created when the arguments are not ready. + +```ts +// Bad: subscribes with undefined args, wastes a subscription slot +const profile = useQuery(api.users.getProfile, { userId: selectedId! }); +``` + +```ts +// Good: skip when there is nothing to fetch +const profile = useQuery( + api.users.getProfile, + selectedId ? { userId: selectedId } : "skip", +); +``` + +### 4. Isolate frequently-updated fields into separate documents + +If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. + +```ts +// Bad: lastSeen lives on the user doc, every heartbeat invalidates +// every query that reads this user +const users = defineTable({ + name: v.string(), + email: v.string(), + lastSeen: v.number(), +}); +``` + +```ts +// Good: lastSeen lives in a separate heartbeat doc +const users = defineTable({ + name: v.string(), + email: v.string(), + heartbeatId: v.id("heartbeats"), +}); + +const heartbeats = defineTable({ + lastSeen: v.number(), +}); +``` + +Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. + +For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. + +### 5. Use the aggregate component for counts and sums + +Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. + +Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. + +If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. + +### 6. Narrow query read sets + +Queries that return less data and touch fewer documents invalidate less often. + +```ts +// Bad: returns all fields, invalidates on any field change +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("projects").collect(); + }, +}); +``` + +```ts +// Good: use a digest table with only the fields the list needs +export const listDigests = query({ + handler: async (ctx) => { + return await ctx.db.query("projectDigests").collect(); + }, +}); +``` + +Writes to fields not in the digest table do not invalidate the digest query. + +### 7. Remove `Date.now()` from queries + +Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. + +```ts +// Bad: Date.now() defeats query caching and causes frequent re-evaluation +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) + .take(100); +``` + +```ts +// Good: use a boolean field updated by a scheduled function +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_is_released", (q) => q.eq("isReleased", true)) + .take(100); +``` + +If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. + +### 8. Consider pagination strategy + +For long lists where users scroll through many pages: + +- If the data does not need live updates, use point-in-time fetching with manual "load more" +- If it does need live updates, accept the subscription cost but limit the number of loaded pages +- Consider whether older pages can be unloaded as the user scrolls forward + +### 9. Separate backend cost from UI churn + +If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. + +Treat this as a UX problem first when: + +- the underlying query is already reasonably cheap +- the complaint is flicker, loading flashes, or re-render churn +- live updates are still desirable once fresh data arrives + +## Verification + +1. Subscription count in dashboard is lower for the affected pages +2. UI responsiveness has improved +3. React profiling shows fewer unnecessary re-renders +4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily +5. Sibling pages with similar patterns were updated consistently diff --git a/.claude/skills/convex-quickstart/SKILL.md b/.claude/skills/convex-quickstart/SKILL.md new file mode 100644 index 00000000..369a6c9b --- /dev/null +++ b/.claude/skills/convex-quickstart/SKILL.md @@ -0,0 +1,337 @@ +--- +name: convex-quickstart +description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. +--- + +# Convex Quickstart + +Set up a working Convex project as fast as possible. + +## When to Use + +- Starting a brand new project with Convex +- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app +- Scaffolding a Convex app for prototyping + +## When Not to Use + +- The project already has Convex installed and `convex/` exists - just start building +- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill + +## Workflow + +1. Determine the starting point: new project or existing app +2. If new project, pick a template and scaffold with `npm create convex@latest` +3. If existing app, install `convex` and wire up the provider +4. Run `npx convex dev` to connect a deployment and start the dev loop +5. Verify the setup works + +## Path 1: New Project (Recommended) + +Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. + +### Pick a template + +| Template | Stack | +|----------|-------| +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | + +If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. + +You can also use any GitHub repo as a template: + +```bash +npm create convex@latest my-app -- -t owner/repo +npm create convex@latest my-app -- -t owner/repo#branch +``` + +### Scaffold the project + +Always pass the project name and template flag to avoid interactive prompts: + +```bash +npm create convex@latest my-app -- -t react-vite-shadcn +cd my-app +npm install +``` + +The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. + +To scaffold in the current directory (if it is empty): + +```bash +npm create convex@latest . -- -t react-vite-shadcn +npm install +``` + +### Start the dev loop + +`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. + +**Ask the user to run this themselves:** + +Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: +- Create a Convex project and dev deployment +- Write the deployment URL to `.env.local` +- Create the `convex/` directory with generated types +- Watch for changes and sync continuously + +The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. + +**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. + +### Start the frontend + +The user should also run the frontend dev server in a separate terminal: + +```bash +npm run dev +``` + +Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. + +### What you get + +After scaffolding, the project structure looks like: + +``` +my-app/ + convex/ # Backend functions and schema + _generated/ # Auto-generated types (check this into git) + schema.ts # Database schema (if template includes one) + src/ # Frontend code (or app/ for Next.js) + package.json + .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL +``` + +The template already has: +- `ConvexProvider` wired into the app root +- Correct env var names for the framework +- Tailwind and shadcn/ui ready (for shadcn templates) +- Auth provider configured (for auth templates) + +You are ready to start adding schema, functions, and UI. + +## Path 2: Add Convex to an Existing App + +Use this when the user already has a frontend project and wants to add Convex as the backend. + +### Install + +```bash +npm install convex +``` + +### Initialize and start dev loop + +Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. + +### Wire up the provider + +The Convex client must wrap the app at the root. The setup varies by framework. + +Create the `ConvexReactClient` at module scope, not inside a component: + +```tsx +// Bad: re-creates the client on every render +function App() { + const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + return ...; +} + +// Good: created once at module scope +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); +function App() { + return ...; +} +``` + +#### React (Vite) + +```tsx +// src/main.tsx +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import App from "./App"; + +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + +createRoot(document.getElementById("root")!).render( + + + + + , +); +``` + +#### Next.js (App Router) + +```tsx +// app/ConvexClientProvider.tsx +"use client"; + +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import { ReactNode } from "react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +export function ConvexClientProvider({ children }: { children: ReactNode }) { + return {children}; +} +``` + +```tsx +// app/layout.tsx +import { ConvexClientProvider } from "./ConvexClientProvider"; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} +``` + +#### Other frameworks + +For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: + +- [Vue](https://docs.convex.dev/quickstart/vue) +- [Svelte](https://docs.convex.dev/quickstart/svelte) +- [React Native](https://docs.convex.dev/quickstart/react-native) +- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) +- [Remix](https://docs.convex.dev/quickstart/remix) +- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) + +### Environment variables + +The env var name depends on the framework: + +| Framework | Variable | +|-----------|----------| +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | +| React Native | `EXPO_PUBLIC_CONVEX_URL` | + +`npx convex dev` writes the correct variable to `.env.local` automatically. + +## Agent Mode (Cloud-Based Agents) + +When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. + +Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: + +```bash +CONVEX_AGENT_MODE=anonymous npx convex dev +``` + +This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. + +## Verify the Setup + +After setup, confirm everything is working: + +1. The user confirms `npx convex dev` is running without errors +2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` +3. `.env.local` contains the deployment URL + +## Writing Your First Function + +Once the project is set up, create a schema and a query to verify the full loop works. + +`convex/schema.ts`: + +```ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + tasks: defineTable({ + text: v.string(), + completed: v.boolean(), + }), +}); +``` + +`convex/tasks.ts`: + +```ts +import { query, mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("tasks").collect(); + }, +}); + +export const create = mutation({ + args: { text: v.string() }, + handler: async (ctx, args) => { + await ctx.db.insert("tasks", { text: args.text, completed: false }); + }, +}); +``` + +Use in a React component (adjust the import path based on your file location relative to `convex/`): + +```tsx +import { useQuery, useMutation } from "convex/react"; +import { api } from "../convex/_generated/api"; + +function Tasks() { + const tasks = useQuery(api.tasks.list); + const create = useMutation(api.tasks.create); + + return ( +
+ + {tasks?.map((t) =>
{t.text}
)} +
+ ); +} +``` + +## Development vs Production + +Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. + +When ready to ship, deploy to production: + +```bash +npx convex deploy +``` + +This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. + +## Next Steps + +- Add authentication: use the `convex-setup-auth` skill +- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) +- Build components: use the `convex-create-component` skill +- Plan a migration: use the `convex-migration-helper` skill +- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) +- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) + +## Checklist + +- [ ] Determined starting point: new project or existing app +- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template +- [ ] If existing app: installed `convex` and wired up the provider +- [ ] User has `npx convex dev` running and connected to a deployment +- [ ] `convex/_generated/` directory exists with types +- [ ] `.env.local` has the deployment URL +- [ ] Verified a basic query/mutation round-trip works diff --git a/.claude/skills/convex-quickstart/agents/openai.yaml b/.claude/skills/convex-quickstart/agents/openai.yaml new file mode 100644 index 00000000..a51a6d09 --- /dev/null +++ b/.claude/skills/convex-quickstart/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Quickstart" + short_description: "Start a new Convex app or add Convex to an existing frontend." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#F97316" + default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." + +policy: + allow_implicit_invocation: true diff --git a/.claude/skills/convex-quickstart/assets/icon.svg b/.claude/skills/convex-quickstart/assets/icon.svg new file mode 100644 index 00000000..d83a73f3 --- /dev/null +++ b/.claude/skills/convex-quickstart/assets/icon.svg @@ -0,0 +1,4 @@ + diff --git a/.claude/skills/convex-setup-auth/SKILL.md b/.claude/skills/convex-setup-auth/SKILL.md new file mode 100644 index 00000000..5c0c994a --- /dev/null +++ b/.claude/skills/convex-setup-auth/SKILL.md @@ -0,0 +1,113 @@ +--- +name: convex-setup-auth +description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. +--- + +# Convex Authentication Setup + +Implement secure authentication in Convex with user management and access control. + +## When to Use + +- Setting up authentication for the first time +- Implementing user management (users table, identity mapping) +- Creating authentication helper functions +- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) + +## First Step: Choose the Auth Provider + +Convex supports multiple authentication approaches. Do not assume a provider. + +Before writing setup code: + +1. Ask the user which auth solution they want, unless the repository already makes it obvious +2. If the repo already uses a provider, continue with that provider unless the user wants to switch +3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding + +Common options: + +- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex +- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features +- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically +- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 +- Custom JWT provider - use when integrating an existing auth system not covered above + +Look for signals in the repo before asking: + +- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages +- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components +- Environment variables that clearly point at a provider + +## After Choosing a Provider + +Read the provider's official guide and the matching local reference file: + +- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` +- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` +- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` +- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` + +The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. + +Use those sources for: + +- package installation +- client provider wiring +- environment variables +- `convex/auth.config.ts` setup +- login and logout UI patterns +- framework-specific setup for React, Vite, or Next.js + +For shared auth behavior, use the official Convex docs as the source of truth: + +- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` +- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage +- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance +- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth + +Do not invent a provider-agnostic user sync pattern from memory. +For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. +For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. + +Do not invent provider-specific setup from memory when the docs are available. +Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. + +## Workflow + +1. Determine the provider, either by asking the user or inferring from the repo +2. Ask whether the user wants local-only setup or production-ready setup now +3. Read the matching provider reference file +4. Follow the official provider docs for current setup details +5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns +6. Only add app-level user storage if the docs and app requirements call for it +7. Add authorization checks for ownership, roles, or team access only where the app needs them +8. Verify login state, protected queries, environment variables, and production configuration if requested + +If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. +For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. +If the environment has browser automation tools, you can use them. +If it does not, give the user a short manual validation checklist instead. + +## Reference Files + +### Provider References + +- `references/convex-auth.md` +- `references/clerk.md` +- `references/workos-authkit.md` +- `references/auth0.md` + +## Checklist + +- [ ] Chosen the correct auth provider before writing setup code +- [ ] Read the relevant provider reference file +- [ ] Asked whether the user wants local-only setup or production-ready setup +- [ ] Used the official provider docs for provider-specific wiring +- [ ] Used the official Convex docs for shared auth behavior and authorization patterns +- [ ] Only added app-level user storage if the app actually needs it +- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth +- [ ] Added authentication checks in protected backend functions +- [ ] Added authorization checks where the app actually needs them +- [ ] Clear error messages ("Not authenticated", "Unauthorized") +- [ ] Client auth provider configured for the chosen provider +- [ ] If requested, production auth setup is covered too diff --git a/.claude/skills/convex-setup-auth/agents/openai.yaml b/.claude/skills/convex-setup-auth/agents/openai.yaml new file mode 100644 index 00000000..d1c90a14 --- /dev/null +++ b/.claude/skills/convex-setup-auth/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Setup Auth" + short_description: "Set up Convex auth, user identity mapping, and access control." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#2563EB" + default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." + +policy: + allow_implicit_invocation: true diff --git a/.claude/skills/convex-setup-auth/assets/icon.svg b/.claude/skills/convex-setup-auth/assets/icon.svg new file mode 100644 index 00000000..4917dbb4 --- /dev/null +++ b/.claude/skills/convex-setup-auth/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.claude/skills/convex-setup-auth/references/auth0.md b/.claude/skills/convex-setup-auth/references/auth0.md new file mode 100644 index 00000000..9c729c5a --- /dev/null +++ b/.claude/skills/convex-setup-auth/references/auth0.md @@ -0,0 +1,116 @@ +# Auth0 + +Official docs: + +- https://docs.convex.dev/auth/auth0 +- https://auth0.github.io/auth0-cli/ +- https://auth0.github.io/auth0-cli/auth0_apps_create.html + +Use this when the app already uses Auth0 or the user wants Auth0 specifically. + +## Workflow + +1. Confirm the user wants Auth0 +2. Determine the app framework and whether Auth0 is already partly set up +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and Auth0 guides before making changes +5. Ask whether they want the fastest setup path by installing the Auth0 CLI +6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI +7. If they do not want the CLI path, use the Auth0 dashboard path instead +8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up +9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID +10. Set environment variables for local and production environments +11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +12. Gate Convex-backed UI with Convex auth state +13. Try to verify Convex reports the user as authenticated after Auth0 login +14. If the refresh-token path fails, stop improvising and send the user back to the official docs +15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered + +## What To Do + +- Read the official Convex and Auth0 guide before writing setup code +- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet +- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" +- Make sure the app has already completed the relevant Auth0 quickstart for its frontend +- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` +- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated + +## Key Setup Areas + +- install the Auth0 SDK for the app's framework +- configure `convex/auth.config.ts` with the Auth0 domain and client ID +- set environment variables for local and production environments +- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +- use Convex auth state when gating Convex-backed UI + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- frontend app entry or provider wrapper +- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` +- Auth0 environment variables commonly include: + - `AUTH0_DOMAIN` + - `AUTH0_CLIENT_ID` + - `VITE_AUTH0_DOMAIN` + - `VITE_AUTH0_CLIENT_ID` + +## Concrete Steps + +1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework +2. Ask whether the user wants the Auth0 CLI path +3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` +4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app +5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard +6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard +7. Install the Auth0 SDK for the app's framework +8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID +9. Set frontend and backend environment variables +10. Wrap the app in `Auth0Provider` +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` +12. Run the normal Convex dev or deploy flow after backend config changes +13. Try the official provider config shown in the Convex docs +14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now +15. Only claim success if the user can sign in and Convex recognizes the authenticated session +16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too + +## Gotchas + +- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch +- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant +- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard +- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced +- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end +- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled +- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation +- Keep dev and prod tenants separate if the project uses different Auth0 environments +- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. +- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. +- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. +- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered +- Verify production environment variables and redirect settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the Auth0 login flow +- Verify Convex-authenticated UI renders only after Convex auth state is ready +- Verify protected Convex queries succeed after login +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- Verify the Auth0 app settings match the real local callback and logout URLs during development +- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully +- If production-ready setup was requested, verify the production Auth0 configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Auth0 +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Complete the relevant Auth0 frontend setup +- [ ] Configure `convex/auth.config.ts` +- [ ] Set environment variables +- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs +- [ ] If requested, configure the production deployment too diff --git a/.claude/skills/convex-setup-auth/references/clerk.md b/.claude/skills/convex-setup-auth/references/clerk.md new file mode 100644 index 00000000..7dbde194 --- /dev/null +++ b/.claude/skills/convex-setup-auth/references/clerk.md @@ -0,0 +1,113 @@ +# Clerk + +Official docs: + +- https://docs.convex.dev/auth/clerk +- https://clerk.com/docs/guides/development/integrations/databases/convex + +Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. + +## Workflow + +1. Confirm the user wants Clerk +2. Make sure the user has a Clerk account and a Clerk application +3. Determine the app framework: + - React + - Next.js + - TanStack Start +4. Ask whether the user wants local-only setup or production-ready setup now +5. Gather the Clerk keys and the Clerk Frontend API URL +6. Follow the correct framework section in the official docs +7. Complete the backend and client wiring +8. Verify Convex reports the user as authenticated after login +9. If the user wants production-ready setup, make sure the production Clerk config is also covered + +## What To Do + +- Read the official Convex and Clerk guide before writing setup code +- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application +- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active +- Match the guide to the app's framework, usually React, Next.js, or TanStack Start +- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` + +## Key Setup Areas + +- install the Clerk SDK for the framework in use +- configure `convex/auth.config.ts` with the Clerk issuer domain +- set the required Clerk environment variables +- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` +- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- React or Vite client entry such as `src/main.tsx` +- Next.js client wrapper for Convex if using App Router +- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` +- Clerk app creation page: `https://dashboard.clerk.com/apps/new` +- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` +- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` +- Clerk environment variables: + - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs + - `CLERK_FRONTEND_API_URL` in the Clerk docs + - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps + - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps + - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required + +`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. + +## Concrete Steps + +1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` +2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` +3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed +4. Open `https://dashboard.clerk.com/apps/setup/convex` +5. Activate the Convex integration in Clerk if it is not already active +6. Copy the Clerk Frontend API URL shown there +7. Install the Clerk package for the app's framework +8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens +9. Set the publishable key in the frontend environment +10. Set the issuer domain or Frontend API URL so Convex can validate the JWT +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` +12. Wrap the app in `ClerkProvider` +13. Use Convex auth helpers for authenticated rendering +14. Run the normal Convex dev or deploy flow after updating backend auth config +15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too + +## Gotchas + +- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render +- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper +- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config +- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. +- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. +- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. +- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. +- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` +- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included +- Verify production redirect URLs and any production Clerk domain values before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can sign in with Clerk +- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in +- Verify `useConvexAuth()` reaches the authenticated state after Clerk login +- Verify protected Convex queries run successfully inside authenticated UI +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- If production-ready setup was requested, verify the production Clerk configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Clerk +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Follow the correct framework section in the official guide +- [ ] Set Clerk environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify Convex authenticated state after login +- [ ] If requested, configure the production deployment too diff --git a/.claude/skills/convex-setup-auth/references/convex-auth.md b/.claude/skills/convex-setup-auth/references/convex-auth.md new file mode 100644 index 00000000..d4824d24 --- /dev/null +++ b/.claude/skills/convex-setup-auth/references/convex-auth.md @@ -0,0 +1,143 @@ +# Convex Auth + +Official docs: https://docs.convex.dev/auth/convex-auth +Setup guide: https://labs.convex.dev/auth/setup + +Use this when the user wants auth handled directly in Convex rather than through a third-party provider. + +## Workflow + +1. Confirm the user wants Convex Auth specifically +2. Determine which sign-in methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords and password reset +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the Convex Auth setup guide before writing code +5. Make sure the project has a configured Convex deployment: + - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set + - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing +6. Install the auth packages: + - `npm install @convex-dev/auth @auth/core@0.37.0` +7. Run the initialization command: + - `npx @convex-dev/auth` +8. Confirm the initializer created: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +9. Add the required `authTables` to `convex/schema.ts` +10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` +11. Configure at least one auth method in `convex/auth.ts` +12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code +13. Verify the client can sign in successfully +14. Verify Convex receives authenticated identity in backend functions +15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well +16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex + +## What This Reference Is For + +- choosing Convex Auth as the default provider for a new Convex app +- understanding whether the app wants magic links, OTPs, OAuth, or passwords +- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior + +## What To Do + +- Read the Convex Auth setup guide before writing setup code +- Follow the setup flow from the docs rather than recreating it from memory +- If the app is new, consider starting from the official starter flow instead of hand-wiring everything +- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra + +## Concrete Steps + +1. Install `@convex-dev/auth` and `@auth/core@0.37.0` +2. Run `npx convex dev` if the project does not already have a configured deployment +3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment +4. Run `npx @convex-dev/auth` +5. Confirm the generated auth setup is present before continuing: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +6. Add `authTables` to `convex/schema.ts` +7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry +8. Configure the selected auth methods in `convex/auth.ts` +9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed +10. Verify login locally +11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment + +## Expected Files and Decisions + +- `convex/schema.ts` +- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file +- generated Convex Auth setup produced by `npx @convex-dev/auth` +- an existing configured Convex deployment, or the ability to create one with `npx convex dev` +- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods + +- Decide whether the user is creating a new app or adding auth to an existing app +- For a new app, prefer the official starter flow instead of rebuilding setup by hand +- Decide which auth methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords +- Decide whether the user wants local-only setup or production-ready setup now +- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough + +## Gotchas + +- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. +- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. +- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. +- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. +- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. +- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. +- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. +- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. +- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. +- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment +- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Human Handoff + +If `npx convex dev` or deployment setup requires human input: + +- stop and explain exactly what the user needs to do +- say why that step is required +- resume the auth setup immediately after the user confirms it is done + +## Validation + +- Verify the user can complete a sign-in flow +- Offer to validate sign up, sign out, and sign back in with the configured auth method +- If browser automation is available in the environment, you can do this directly +- If browser automation is not available, give the user a short manual validation checklist instead +- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions +- Verify protected UI only renders after Convex-authenticated state is ready +- Verify environment variables and redirect settings match the current app environment +- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in +- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed +- If production-ready setup was requested, verify the production deployment is also configured correctly + +## Checklist + +- [ ] Confirm the user wants Convex Auth specifically +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Ensure a Convex deployment is configured before running auth initialization +- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` +- [ ] Run `npx convex dev` first if needed +- [ ] Run `npx @convex-dev/auth` +- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created +- [ ] Follow the setup guide for package install and wiring +- [ ] Add `authTables` to `convex/schema.ts` +- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` +- [ ] Configure at least one auth method in `convex/auth.ts` +- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes +- [ ] Confirm which sign-in methods the app needs +- [ ] Verify the client can sign in and the backend receives authenticated identity +- [ ] Offer end-to-end validation of sign up, sign out, and sign back in +- [ ] If requested, configure the production deployment too +- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.claude/skills/convex-setup-auth/references/workos-authkit.md b/.claude/skills/convex-setup-auth/references/workos-authkit.md new file mode 100644 index 00000000..038cb9f3 --- /dev/null +++ b/.claude/skills/convex-setup-auth/references/workos-authkit.md @@ -0,0 +1,114 @@ +# WorkOS AuthKit + +Official docs: + +- https://docs.convex.dev/auth/authkit/ +- https://docs.convex.dev/auth/authkit/add-to-app +- https://docs.convex.dev/auth/authkit/auto-provision + +Use this when the app already uses WorkOS or the user wants AuthKit specifically. + +## Workflow + +1. Confirm the user wants WorkOS AuthKit +2. Determine whether they want: + - a Convex-managed WorkOS team + - an existing WorkOS team +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and WorkOS AuthKit guide +5. Create or update `convex.json` for the app's framework and real local port +6. Follow the correct branch of the setup flow based on that choice +7. Configure the required WorkOS environment variables +8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs +9. Wire the client provider and callback flow +10. Verify authenticated requests reach Convex +11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too +12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex + +## What To Do + +- Read the official Convex and WorkOS AuthKit guide before writing setup code +- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team +- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra +- Follow the current setup flow from the docs instead of relying on older examples + +## Key Setup Areas + +- package installation for the app's framework +- `convex.json` with the `authKit` section for dev, and preview or prod if needed +- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration +- `convex/auth.config.ts` wiring for WorkOS-issued JWTs +- client provider setup and token flow into Convex +- login callback and redirect configuration + +## Files and Env Vars To Expect + +- `convex.json` +- `convex/auth.config.ts` +- frontend auth provider wiring +- callback or redirect route setup where the framework requires it +- WorkOS environment variables commonly include: + - `WORKOS_CLIENT_ID` + - `WORKOS_API_KEY` + - `WORKOS_COOKIE_PASSWORD` + - `VITE_WORKOS_CLIENT_ID` + - `VITE_WORKOS_REDIRECT_URI` + - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` + +For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. + +## Concrete Steps + +1. Choose Convex-managed or existing WorkOS team +2. Create or update `convex.json` with the `authKit` section for the framework in use +3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port +4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow +5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` +6. Create or update `convex/auth.config.ts` for WorkOS JWT validation +7. Run the normal Convex dev or deploy flow so backend config is synced +8. Wire the WorkOS client provider in the app +9. Configure callback and redirect handling +10. Verify the user can sign in and return to the app +11. Verify Convex sees the authenticated user after login +12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too + +## Gotchas + +- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious +- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys +- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex +- Do not mix dev and prod WorkOS credentials or redirect URIs +- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it +- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. +- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. +- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. +- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. +- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered +- Verify the production redirect and callback settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the login flow and return to the app +- Verify the callback URL matches the real frontend port in local dev +- Verify Convex receives authenticated requests after login +- Verify `convex.json` matches the framework and chosen WorkOS setup path +- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path +- Verify environment variables differ correctly between local and production where needed +- If production-ready setup was requested, verify the production WorkOS configuration is also covered + +## Checklist + +- [ ] Confirm the user wants WorkOS AuthKit +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Choose Convex-managed or existing WorkOS team +- [ ] Create or update `convex.json` +- [ ] Configure WorkOS environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify authenticated requests reach Convex after login +- [ ] If requested, configure the production deployment too diff --git a/.windsurf/skills/convex-create-component/SKILL.md b/.windsurf/skills/convex-create-component/SKILL.md new file mode 100644 index 00000000..effe01fa --- /dev/null +++ b/.windsurf/skills/convex-create-component/SKILL.md @@ -0,0 +1,411 @@ +--- +name: convex-create-component +description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. +--- + +# Convex Create Component + +Create reusable Convex components with clear boundaries and a small app-facing API. + +## When to Use + +- Creating a new Convex component in an existing app +- Extracting reusable backend logic into a component +- Building a third-party integration that should own its own tables and workflows +- Packaging Convex functionality for reuse across multiple apps + +## When Not to Use + +- One-off business logic that belongs in the main app +- Thin utilities that do not need Convex tables or functions +- App-level orchestration that should stay in `convex/` +- Cases where a normal TypeScript library is enough + +## Workflow + +1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. +2. Choose the shape using the decision tree below and read the matching reference file. +3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. +4. Make a short plan for: + - what tables the component owns + - what public functions it exposes + - what data must be passed in from the app (auth, env vars, parent IDs) + - what stays in the app as wrappers or HTTP mounts +5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. +6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. +7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. +8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. +9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. +10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. + +## Choose the Shape + +Ask the user, then pick one path: + +| Goal | Shape | Reference | +|------|-------|-----------| +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | + +Read exactly one reference file before proceeding. + +## Default Approach + +Unless the user explicitly wants an npm package, default to a local component: + +- Put it under `convex/components//` +- Define it with `defineComponent(...)` in its own `convex.config.ts` +- Install it from the app's `convex/convex.config.ts` with `app.use(...)` +- Let `npx convex dev` generate the component's own `_generated/` files + +## Component Skeleton + +A minimal local component with a table and two functions, plus the app wiring. + +```ts +// convex/components/notifications/convex.config.ts +import { defineComponent } from "convex/server"; + +export default defineComponent("notifications"); +``` + +```ts +// convex/components/notifications/schema.ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notifications: defineTable({ + userId: v.string(), + message: v.string(), + read: v.boolean(), + }).index("by_user", ["userId"]), +}); +``` + +```ts +// convex/components/notifications/lib.ts +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server.js"; + +export const send = mutation({ + args: { userId: v.string(), message: v.string() }, + returns: v.id("notifications"), + handler: async (ctx, args) => { + return await ctx.db.insert("notifications", { + userId: args.userId, + message: args.message, + read: false, + }); + }, +}); + +export const listUnread = query({ + args: { userId: v.string() }, + returns: v.array( + v.object({ + _id: v.id("notifications"), + _creationTime: v.number(), + userId: v.string(), + message: v.string(), + read: v.boolean(), + }) + ), + handler: async (ctx, args) => { + return await ctx.db + .query("notifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .filter((q) => q.eq(q.field("read"), false)) + .collect(); + }, +}); +``` + +```ts +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import notifications from "./components/notifications/convex.config.js"; + +const app = defineApp(); +app.use(notifications); + +export default app; +``` + +```ts +// convex/notifications.ts (app-side wrapper) +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server"; +import { components } from "./_generated/api"; +import { getAuthUserId } from "@convex-dev/auth/server"; + +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); + +export const myUnread = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + return await ctx.runQuery(components.notifications.lib.listUnread, { + userId, + }); + }, +}); +``` + +Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. + +## Critical Rules + +- Keep authentication in the app. `ctx.auth` is not available inside components. +- Keep environment access in the app. Component functions cannot read `process.env`. +- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. +- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. +- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. +- Do not expose component functions directly to clients. Create app wrappers when client access is needed. +- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. +- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. +- Add `args` and `returns` validators to all public component functions. + +## Patterns + +### Authentication and environment access + +```ts +// Bad: component code cannot rely on app auth or env +const identity = await ctx.auth.getUserIdentity(); +const apiKey = process.env.OPENAI_API_KEY; +``` + +```ts +// Good: the app resolves auth and env, then passes explicit values +const userId = await getAuthUserId(ctx); +if (!userId) throw new Error("Not authenticated"); + +await ctx.runAction(components.translator.translate, { + userId, + apiKey: process.env.OPENAI_API_KEY, + text: args.text, +}); +``` + +### Client-facing API + +```ts +// Bad: assuming a component function is directly callable by clients +export const send = components.notifications.send; +``` + +```ts +// Good: re-export through an app mutation or query +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); +``` + +### IDs across the boundary + +```ts +// Bad: parent app table IDs are not valid component validators +args: { userId: v.id("users") } +``` + +```ts +// Good: treat parent-owned IDs as strings at the boundary +args: { userId: v.string() } +``` + +### Function Handles for callbacks + +When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. + +```ts +// App side: create a handle and pass it to the component +import { createFunctionHandle } from "convex/server"; + +export const startJob = mutation({ + handler: async (ctx) => { + const handle = await createFunctionHandle(internal.myModule.processItem); + await ctx.runMutation(components.workpool.enqueue, { + callback: handle, + }); + }, +}); +``` + +```ts +// Component side: accept and invoke the handle +import { v } from "convex/values"; +import type { FunctionHandle } from "convex/server"; +import { mutation } from "./_generated/server.js"; + +export const enqueue = mutation({ + args: { callback: v.string() }, + handler: async (ctx, args) => { + const handle = args.callback as FunctionHandle<"mutation">; + await ctx.scheduler.runAfter(0, handle, {}); + }, +}); +``` + +### Deriving validators from schema + +Instead of manually repeating field types in return validators, extend the schema validator: + +```ts +import { v } from "convex/values"; +import schema from "./schema.js"; + +const notificationDoc = schema.tables.notifications.validator.extend({ + _id: v.id("notifications"), + _creationTime: v.number(), +}); + +export const getLatest = query({ + args: {}, + returns: v.nullable(notificationDoc), + handler: async (ctx) => { + return await ctx.db.query("notifications").order("desc").first(); + }, +}); +``` + +### Static configuration with a globals table + +A common pattern for component configuration is a single-document "globals" table: + +```ts +// schema.ts +export default defineSchema({ + globals: defineTable({ + maxRetries: v.number(), + webhookUrl: v.optional(v.string()), + }), + // ... other tables +}); +``` + +```ts +// lib.ts +export const configure = mutation({ + args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, args) => { + const existing = await ctx.db.query("globals").first(); + if (existing) { + await ctx.db.patch(existing._id, args); + } else { + await ctx.db.insert("globals", args); + } + return null; + }, +}); +``` + +### Class-based client wrappers + +For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. + +```ts +// src/client/index.ts +import type { GenericMutationCtx, GenericDataModel } from "convex/server"; +import type { ComponentApi } from "../component/_generated/component.js"; + +type MutationCtx = Pick, "runMutation">; + +export class Notifications { + constructor( + private component: ComponentApi, + private options?: { defaultChannel?: string }, + ) {} + + async send(ctx: MutationCtx, args: { userId: string; message: string }) { + return await ctx.runMutation(this.component.lib.send, { + ...args, + channel: this.options?.defaultChannel ?? "default", + }); + } +} +``` + +```ts +// App usage +import { Notifications } from "@convex-dev/notifications"; +import { components } from "./_generated/api"; + +const notifications = new Notifications(components.notifications, { + defaultChannel: "alerts", +}); + +export const send = mutation({ + args: { message: v.string() }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + await notifications.send(ctx, { userId, message: args.message }); + }, +}); +``` + +## Validation + +Try validation in this order: + +1. `npx convex codegen --component-dir convex/components/` +2. `npx convex codegen` +3. `npx convex dev` + +Important: + +- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. +- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. +- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. + +## Reference Files + +Read exactly one of these after the user confirms the goal: + +- `references/local-components.md` +- `references/packaged-components.md` +- `references/hybrid-components.md` + +Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) + +## Checklist + +- [ ] Asked the user what they want to build and confirmed the shape +- [ ] Read the matching reference file +- [ ] Confirmed a component is the right abstraction +- [ ] Planned tables, public API, boundaries, and app wrappers +- [ ] Component lives under `convex/components//` (or package layout if publishing) +- [ ] Component imports from its own `./_generated/server` +- [ ] Auth, env access, and HTTP routes stay in the app +- [ ] Parent app IDs cross the boundary as `v.string()` +- [ ] Public functions have `args` and `returns` validators +- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/.windsurf/skills/convex-create-component/agents/openai.yaml b/.windsurf/skills/convex-create-component/agents/openai.yaml new file mode 100644 index 00000000..ba9287e4 --- /dev/null +++ b/.windsurf/skills/convex-create-component/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Create Component" + short_description: "Design and build reusable Convex components with clear boundaries." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#14B8A6" + default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." + +policy: + allow_implicit_invocation: true diff --git a/.windsurf/skills/convex-create-component/assets/icon.svg b/.windsurf/skills/convex-create-component/assets/icon.svg new file mode 100644 index 00000000..10f4c2c4 --- /dev/null +++ b/.windsurf/skills/convex-create-component/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.windsurf/skills/convex-create-component/references/hybrid-components.md b/.windsurf/skills/convex-create-component/references/hybrid-components.md new file mode 100644 index 00000000..d2bb3514 --- /dev/null +++ b/.windsurf/skills/convex-create-component/references/hybrid-components.md @@ -0,0 +1,37 @@ +# Hybrid Convex Components + +Read this file only when the user explicitly wants a hybrid setup. + +## What This Means + +A hybrid component combines a local Convex component with shared library code. + +This can help when: + +- the user wants a local install but also shared package logic +- the component needs extension points or override hooks +- some logic should live in normal TypeScript code outside the component boundary + +## Default Advice + +Treat hybrid as an advanced option, not the default. + +Before choosing it, ask: + +- Why is a plain local component not enough? +- Why is a packaged component not enough? +- What exactly needs to stay overridable or shared? + +If the answer is vague, fall back to local or packaged. + +## Risks + +- More moving parts +- Harder upgrades and backwards compatibility +- Easier to blur the component boundary + +## Checklist + +- [ ] User explicitly needs hybrid behavior +- [ ] Local-only and packaged-only options were considered first +- [ ] The extension points are clearly defined before coding diff --git a/.windsurf/skills/convex-create-component/references/local-components.md b/.windsurf/skills/convex-create-component/references/local-components.md new file mode 100644 index 00000000..7fbfe21a --- /dev/null +++ b/.windsurf/skills/convex-create-component/references/local-components.md @@ -0,0 +1,38 @@ +# Local Convex Components + +Read this file when the component should live inside the current app and does not need to be published as an npm package. + +## When to Choose This + +- The user wants the simplest path +- The component only needs to work in this repo +- The goal is extracting app logic into a cleaner boundary + +## Default Layout + +Use this structure unless the repo already has a clear alternative pattern: + +```text +convex/ + convex.config.ts + components/ + / + convex.config.ts + schema.ts + .ts +``` + +## Workflow Notes + +- Define the component with `defineComponent("")` +- Install it from the app with `defineApp()` and `app.use(...)` +- Keep auth, env access, public API wrappers, and HTTP route mounting in the app +- Let the component own isolated tables and reusable backend workflows +- Add app wrappers if clients need to call into the component + +## Checklist + +- [ ] Component is inside `convex/components//` +- [ ] App installs it with `app.use(...)` +- [ ] Component owns only its own tables +- [ ] App wrappers handle client-facing calls when needed diff --git a/.windsurf/skills/convex-create-component/references/packaged-components.md b/.windsurf/skills/convex-create-component/references/packaged-components.md new file mode 100644 index 00000000..5668e7ed --- /dev/null +++ b/.windsurf/skills/convex-create-component/references/packaged-components.md @@ -0,0 +1,51 @@ +# Packaged Convex Components + +Read this file when the user wants a reusable npm package or a component shared across multiple apps. + +## When to Choose This + +- The user wants to publish the component +- The user wants a stable reusable package boundary +- The component will be shared across multiple apps or teams + +## Default Approach + +- Prefer starting from `npx create-convex@latest --component` when possible +- Keep the official authoring docs as the source of truth for package layout and exports +- Validate the bundled package through an example app, not just the source files + +## Build Flow + +When building a packaged component, make sure the bundled output exists before the example app tries to consume it. + +Recommended order: + +1. `npx convex codegen --component-dir ./path/to/component` +2. Run the package build command +3. Run `npx convex dev --typecheck-components` in the example app + +Do not assume normal app codegen is enough for packaged component workflows. + +## Package Exports + +If publishing to npm, make sure the package exposes the entry points apps need: + +- package root for client helpers, types, or classes +- `./convex.config.js` for installing the component +- `./_generated/component.js` for the app-facing `ComponentApi` type +- `./test` for testing helpers when applicable + +## Testing + +- Use `convex-test` for component logic +- Register the component schema and modules with the test instance +- Test app-side wrapper code from an example app that installs the package +- Export a small helper from `./test` if consumers need easy test registration + +## Checklist + +- [ ] Packaging is actually required +- [ ] Build order avoids bundle and codegen races +- [ ] Package exports include install and typing entry points +- [ ] Example app exercises the packaged component +- [ ] Core behavior is covered by tests diff --git a/.windsurf/skills/convex-migration-helper/SKILL.md b/.windsurf/skills/convex-migration-helper/SKILL.md new file mode 100644 index 00000000..f353678f --- /dev/null +++ b/.windsurf/skills/convex-migration-helper/SKILL.md @@ -0,0 +1,524 @@ +--- +name: convex-migration-helper +description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. +--- + +# Convex Migration Helper + +Safely migrate Convex schemas and data when making breaking changes. + +## When to Use + +- Adding new required fields to existing tables +- Changing field types or structure +- Splitting or merging tables +- Renaming or deleting fields +- Migrating from nested to relational data + +## Key Concepts + +### Schema Validation Drives the Workflow + +Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: + +- You cannot add a required field if existing documents don't have it +- You cannot change a field's type if existing documents have the old type +- You cannot remove a field from the schema if existing documents still have it + +This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. + +### Online Migrations + +Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. + +### Prefer New Fields Over Changing Types + +When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. + +### Don't Delete Data + +Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. + +## Safe Changes (No Migration Needed) + +### Adding Optional Field + +```typescript +// Before +users: defineTable({ + name: v.string(), +}) + +// After - safe, new field is optional +users: defineTable({ + name: v.string(), + bio: v.optional(v.string()), +}) +``` + +### Adding New Table + +```typescript +posts: defineTable({ + userId: v.id("users"), + title: v.string(), +}).index("by_user", ["userId"]) +``` + +### Adding Index + +```typescript +users: defineTable({ + name: v.string(), + email: v.string(), +}) + .index("by_email", ["email"]) +``` + +## Breaking Changes: The Deployment Workflow + +Every breaking migration follows the same multi-deploy pattern: + +**Deploy 1 - Widen the schema:** + +1. Update schema to allow both old and new formats (e.g., add optional new field) +2. Update code to handle both formats when reading +3. Update code to write the new format for new documents +4. Deploy + +**Between deploys - Migrate data:** + +5. Run migration to backfill existing documents +6. Verify all documents are migrated + +**Deploy 2 - Narrow the schema:** + +7. Update schema to require the new format only +8. Remove code that handles the old format +9. Deploy + +## Using the Migrations Component (Recommended) + +For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. + +### Installation + +```bash +npm install @convex-dev/migrations +``` + +### Setup + +```typescript +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import migrations from "@convex-dev/migrations/convex.config.js"; + +const app = defineApp(); +app.use(migrations); +export default app; +``` + +```typescript +// convex/migrations.ts +import { Migrations } from "@convex-dev/migrations"; +import { components } from "./_generated/api.js"; +import { DataModel } from "./_generated/dataModel.js"; + +export const migrations = new Migrations(components.migrations); +export const run = migrations.runner(); +``` + +The `DataModel` type parameter is optional but provides type safety for migration definitions. + +### Define a Migration + +The `migrateOne` function processes a single document. The component handles batching and pagination automatically. + +```typescript +// convex/migrations.ts +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); +``` + +Shorthand: if you return an object, it is applied as a patch automatically. + +```typescript +export const clearDeprecatedField = migrations.define({ + table: "users", + migrateOne: () => ({ legacyField: undefined }), +}); +``` + +### Run a Migration + +From the CLI: + +```bash +# Define a one-off runner in convex/migrations.ts: +# export const runIt = migrations.runner(internal.migrations.addDefaultRole); +npx convex run migrations:runIt + +# Or use the general-purpose runner +npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' +``` + +Programmatically from another Convex function: + +```typescript +await migrations.runOne(ctx, internal.migrations.addDefaultRole); +``` + +### Run Multiple Migrations in Order + +```typescript +export const runAll = migrations.runner([ + internal.migrations.addDefaultRole, + internal.migrations.clearDeprecatedField, + internal.migrations.normalizeEmails, +]); +``` + +```bash +npx convex run migrations:runAll +``` + +If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. + +### Dry Run + +Test a migration before committing changes: + +```bash +npx convex run migrations:runIt '{"dryRun": true}' +``` + +This runs one batch and then rolls back, so you can see what it would do without changing any data. + +### Check Migration Status + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +### Cancel a Running Migration + +```bash +npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' +``` + +Or programmatically: + +```typescript +await migrations.cancel(ctx, internal.migrations.addDefaultRole); +``` + +### Run Migrations on Deploy + +Chain migration execution after deploying: + +```bash +npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod +``` + +### Configuration Options + +#### Custom Batch Size + +If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: + +```typescript +export const migrateHeavyTable = migrations.define({ + table: "largeDocuments", + batchSize: 10, + migrateOne: async (ctx, doc) => { + // migration logic + }, +}); +``` + +#### Migrate a Subset Using an Index + +Process only matching documents instead of the full table: + +```typescript +export const fixEmptyNames = migrations.define({ + table: "users", + customRange: (query) => + query.withIndex("by_name", (q) => q.eq("name", "")), + migrateOne: () => ({ name: "" }), +}); +``` + +#### Parallelize Within a Batch + +By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: + +```typescript +export const clearField = migrations.define({ + table: "myTable", + parallelize: true, + migrateOne: () => ({ optionalField: undefined }), +}); +``` + +## Common Migration Patterns + +### Adding a Required Field + +```typescript +// Deploy 1: Schema allows both states +users: defineTable({ + name: v.string(), + role: v.optional(v.union(v.literal("user"), v.literal("admin"))), +}) + +// Migration: backfill the field +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); + +// Deploy 2: After migration completes, make it required +users: defineTable({ + name: v.string(), + role: v.union(v.literal("user"), v.literal("admin")), +}) +``` + +### Deleting a Field + +Mark the field optional first, migrate data to remove it, then remove from schema: + +```typescript +// Deploy 1: Make optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()) + +// Migration +export const removeIsPro = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.isPro !== undefined) { + await ctx.db.patch(team._id, { isPro: undefined }); + } + }, +}); + +// Deploy 2: Remove isPro from schema entirely +``` + +### Changing a Field Type + +Prefer creating a new field. You can combine adding and deleting in one migration: + +```typescript +// Deploy 1: Add new field, keep old field optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) + +// Migration: convert old field to new field +export const convertToEnum = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.plan === undefined) { + await ctx.db.patch(team._id, { + plan: team.isPro ? "pro" : "basic", + isPro: undefined, + }); + } + }, +}); + +// Deploy 2: Remove isPro from schema, make plan required +``` + +### Splitting Nested Data Into a Separate Table + +```typescript +export const extractPreferences = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.preferences === undefined) return; + + const existing = await ctx.db + .query("userPreferences") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .first(); + + if (!existing) { + await ctx.db.insert("userPreferences", { + userId: user._id, + ...user.preferences, + }); + } + + await ctx.db.patch(user._id, { preferences: undefined }); + }, +}); +``` + +Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. + +### Cleaning Up Orphaned Documents + +```typescript +export const deleteOrphanedEmbeddings = migrations.define({ + table: "embeddings", + migrateOne: async (ctx, doc) => { + const chunk = await ctx.db + .query("chunks") + .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) + .first(); + + if (!chunk) { + await ctx.db.delete(doc._id); + } + }, +}); +``` + +## Migration Strategies for Zero Downtime + +During the migration window, your app must handle both old and new data formats. There are two main strategies. + +### Dual Write (Preferred) + +Write to both old and new structures. Read from the old structure until migration is complete. + +1. Deploy code that writes both formats, reads old format +2. Run migration on existing data +3. Deploy code that reads new format, still writes both +4. Deploy code that only reads and writes new format + +This is preferred because you can safely roll back at any point, the old format is always up to date. + +```typescript +// Bad: only writing to new structure before migration is done +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + await ctx.db.insert("teams", { + name: args.name, + plan: args.isPro ? "pro" : "basic", + }); + }, +}); + +// Good: writing to both structures during migration +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + const plan = args.isPro ? "pro" : "basic"; + await ctx.db.insert("teams", { + name: args.name, + isPro: args.isPro, + plan, + }); + }, +}); +``` + +### Dual Read + +Read both formats. Write only the new format. + +1. Deploy code that reads both formats (preferring new), writes only new format +2. Run migration on existing data +3. Deploy code that reads and writes only new format + +This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. + +```typescript +// Good: reading both formats, preferring new +function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { + if (team.plan !== undefined) return team.plan; + return team.isPro ? "pro" : "basic"; +} +``` + +## Small Table Shortcut + +For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: + +```typescript +import { internalMutation } from "./_generated/server"; + +export const backfillSmallTable = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("smallConfig").collect(); + for (const doc of docs) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: "default" }); + } + } + }, +}); +``` + +```bash +npx convex run migrations:backfillSmallTable +``` + +Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. + +## Verifying a Migration + +Query to check remaining unmigrated documents: + +```typescript +import { query } from "./_generated/server"; + +export const verifyMigration = query({ + handler: async (ctx) => { + const remaining = await ctx.db + .query("users") + .filter((q) => q.eq(q.field("role"), undefined)) + .take(10); + + return { + complete: remaining.length === 0, + sampleRemaining: remaining.map((u) => u._id), + }; + }, +}); +``` + +Or use the component's built-in status monitoring: + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +## Migration Checklist + +- [ ] Identify the breaking change and plan the multi-deploy workflow +- [ ] Update schema to allow both old and new formats +- [ ] Update code to handle both formats when reading +- [ ] Update code to write the new format for new documents +- [ ] Deploy widened schema and updated code +- [ ] Define migration using the `@convex-dev/migrations` component +- [ ] Test with `dryRun: true` +- [ ] Run migration and monitor status +- [ ] Verify all documents are migrated +- [ ] Update schema to require new format only +- [ ] Clean up code that handled old format +- [ ] Deploy final schema and code +- [ ] Remove migration code once confirmed stable + +## Common Pitfalls + +1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. +2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. +3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. +4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. +5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. +6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/.windsurf/skills/convex-migration-helper/agents/openai.yaml b/.windsurf/skills/convex-migration-helper/agents/openai.yaml new file mode 100644 index 00000000..c2a7fcc5 --- /dev/null +++ b/.windsurf/skills/convex-migration-helper/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Migration Helper" + short_description: "Plan and run safe Convex schema and data migrations." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#8B5CF6" + default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." + +policy: + allow_implicit_invocation: true diff --git a/.windsurf/skills/convex-migration-helper/assets/icon.svg b/.windsurf/skills/convex-migration-helper/assets/icon.svg new file mode 100644 index 00000000..fba7241a --- /dev/null +++ b/.windsurf/skills/convex-migration-helper/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.windsurf/skills/convex-performance-audit/SKILL.md b/.windsurf/skills/convex-performance-audit/SKILL.md new file mode 100644 index 00000000..6ee0417f --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/SKILL.md @@ -0,0 +1,143 @@ +--- +name: convex-performance-audit +description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. +--- + +# Convex Performance Audit + +Diagnose and fix performance problems in Convex applications, one problem class at a time. + +## When to Use + +- A Convex page or feature feels slow or expensive +- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts +- Low-freshness read paths are using reactivity where point-in-time reads would do +- OCC conflict errors or excessive mutation retries +- High subscription count or slow UI updates +- Functions approaching execution or transaction limits +- The same performance pattern needs fixing across sibling functions + +## When Not to Use + +- Initial Convex setup, auth setup, or component extraction +- Pure schema migrations with no performance goal +- One-off micro-optimizations without a user-visible or deployment-visible problem + +## Guardrails + +- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak +- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path +- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale + +## First Step: Gather Signals + +Start with the strongest signal available: + +1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. +2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. + - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. +3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. +4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. + +## Signal Routing + +After gathering signals, identify the problem class and read the matching reference file. + +| Signal | Reference | +|---|---| +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | + +Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. + +## Escalate Larger Fixes + +If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. + +Examples: + +- introducing digest or summary tables across multiple flows +- splitting documents to isolate frequently-updated fields +- reworking pagination or fetch strategy across several screens +- switching to a new index or denormalized field that needs migration-safe rollout + +When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. + +## Workflow + +### 1. Scope the problem + +Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. + +Write down: + +- entrypoint functions +- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` +- tables read +- tables written +- whether the path is high-read, high-write, or both + +### 2. Trace the full read and write set + +For each function in the path: + +1. Trace every `ctx.db.get()` and `ctx.db.query()` +2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` +3. Note foreign-key lookups, JS-side filtering, and full-document reads +4. Identify all sibling functions touching the same tables +5. Identify reactive stats, aggregates, or widgets rendered on the same page + +In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. + +### 3. Apply fixes from the relevant reference + +Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. + +Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. + +### 4. Fix sibling functions together + +When one function touching a table has a performance bug, audit sibling functions for the same pattern. + +After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. + +Examples: + +- If one list query switches from full docs to a digest table, inspect the other list queries for that table +- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk + +Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. + +### 5. Verify before finishing + +Confirm all of these: + +1. Results are the same as before, no dropped records +2. Eliminated reads or writes are no longer in the path where expected +3. Fallback behavior works when denormalized or indexed fields are missing +4. New writes avoid unnecessary invalidation when data is unchanged +5. Every relevant sibling reader and writer was inspected, not just the original function + +## Reference Files + +- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables +- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting +- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads +- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size + +Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. + +## Checklist + +- [ ] Gathered signals from insights, dashboard, or code audit +- [ ] Identified the problem class and read the matching reference +- [ ] Scoped one concrete user flow or function path +- [ ] Traced every read and write in that path +- [ ] Identified sibling functions touching the same tables +- [ ] Applied fixes from the reference, following the recommended fix order +- [ ] Fixed sibling functions consistently +- [ ] Verified behavior and confirmed no regressions diff --git a/.windsurf/skills/convex-performance-audit/agents/openai.yaml b/.windsurf/skills/convex-performance-audit/agents/openai.yaml new file mode 100644 index 00000000..9a21f387 --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Performance Audit" + short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#EF4444" + default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." + +policy: + allow_implicit_invocation: true diff --git a/.windsurf/skills/convex-performance-audit/assets/icon.svg b/.windsurf/skills/convex-performance-audit/assets/icon.svg new file mode 100644 index 00000000..7ab9e09c --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.windsurf/skills/convex-performance-audit/references/function-budget.md b/.windsurf/skills/convex-performance-audit/references/function-budget.md new file mode 100644 index 00000000..c71d14cb --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/references/function-budget.md @@ -0,0 +1,232 @@ +# Function Budget + +Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. + +## Core Principle + +Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. + +## Limits to Know + +These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. + +| Resource | Limit | +|---|---| +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | +| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | + +## Symptoms + +- "Function execution took too long" errors +- "Transaction too large" or read/write set size errors +- Slow queries that read many documents +- Client receiving large payloads that slow down page load +- `npx convex insights --details` showing high bytes read + +## Common Causes + +### Unbounded collection + +A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. + +### Large document reads on hot paths + +Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. + +### Mutation doing too much work + +A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. + +### Returning too much data to the client + +A query returning full documents when the client only needs a few fields. + +## Fix Order + +### 1. Bound your reads + +Never `.collect()` without a limit on a table that can grow unbounded. + +```ts +// Bad: unbounded read, breaks as the table grows +const messages = await ctx.db.query("messages").collect(); +``` + +```ts +// Good: paginate or limit +const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", channelId)) + .order("desc") + .take(50); +``` + +### 2. Read smaller shapes + +If the list page only needs title, author, and date, do not read full documents with rich content fields. + +Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. + +### 3. Break large mutations into batches + +If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. + +```ts +// Bad: one mutation updating every row +export const backfillAll = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("items").collect(); + for (const doc of docs) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + }, +}); +``` + +```ts +// Good: cursor-based batch processing +export const backfillBatch = internalMutation({ + args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, + handler: async (ctx, args) => { + const batchSize = args.batchSize ?? 100; + const result = await ctx.db + .query("items") + .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); + + for (const doc of result.page) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + } + + if (!result.isDone) { + await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { + cursor: result.continueCursor, + batchSize, + }); + } + }, +}); +``` + +### 4. Move heavy work to actions + +Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. + +Actions run outside the transaction and can call mutations to write results back. + +```ts +// Bad: heavy computation inside a mutation +export const processUpload = mutation({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.db.insert("results", result); + }, +}); +``` + +```ts +// Good: action for heavy work, mutation for the write +export const processUpload = action({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.runMutation(internal.results.store, { result }); + }, +}); +``` + +### 5. Trim return values + +Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. + +```ts +// Bad: returns full documents including large content fields +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("articles").take(20); + }, +}); +``` + +```ts +// Good: project to only the fields the client needs +export const list = query({ + handler: async (ctx) => { + const articles = await ctx.db.query("articles").take(20); + return articles.map((a) => ({ + _id: a._id, + title: a.title, + author: a.author, + createdAt: a._creationTime, + })); + }, +}); +``` + +### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions + +Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. + +```ts +// Bad: unnecessary overhead from ctx.runQuery inside a mutation +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await ctx.runQuery(api.users.getCurrentUser); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +```ts +// Good: plain helper function, no extra overhead +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await getCurrentUser(ctx); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. + +### 7. Avoid unnecessary `runAction` calls + +`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). + +```ts +// Bad: runAction overhead for no reason +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await ctx.runAction(internal.items.processOne, { item }); + } + }, +}); +``` + +```ts +// Good: plain function call +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await processOneItem(ctx, { item }); + } + }, +}); +``` + +## Verification + +1. No function execution or transaction size errors +2. `npx convex insights --details` shows reduced bytes read +3. Large mutations are batched and self-scheduling +4. Client payloads are reasonably sized for the UI they serve +5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible +6. Sibling functions with similar patterns were checked diff --git a/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md b/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md new file mode 100644 index 00000000..96a7b94e --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/references/hot-path-rules.md @@ -0,0 +1,359 @@ +# Hot Path Rules + +Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. + +## Core Principle + +Every byte read or written multiplies with concurrency. + +Think: + +`cost x calls_per_second x 86400` + +In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. + +## Consistency Rule + +If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. + +Do this especially for: + +- multiple list queries over the same table +- multiple writers to the same table +- public browse and search queries over the same records +- helper functions reused by more than one endpoint + +## 1. Push Filters To Storage + +Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. + +Prefer: + +- `withIndex(...)` +- `.withSearchIndex(...)` for text search +- narrower tables +- summary tables + +before accepting a scan-plus-filter pattern. + +```ts +// Bad: scans then filters in JavaScript +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + const tasks = await ctx.db.query("tasks").collect(); + return tasks.filter((task) => task.status === "open"); + }, +}); +``` + +```ts +// Also bad: Convex .filter() does not push to storage either +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .filter((q) => q.eq(q.field("status"), "open")) + .collect(); + }, +}); +``` + +```ts +// Good: use an index so storage does the filtering +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .withIndex("by_status", (q) => q.eq("status", "open")) + .collect(); + }, +}); +``` + +### Migration rule for indexes + +New indexes on partially backfilled fields can create correctness bugs during rollout. + +Important Convex detail: + +`undefined !== false` + +If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. + +Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. + +If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. + +```ts +// Bad: optional booleans can miss older rows where the field is undefined +const projects = await ctx.db + .query("projects") + .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) + .order("desc") + .take(20); +``` + +```ts +// Good: switch hot-path reads only after the rollout is migration-safe +// See the migration helper skill for dual-read / backfill / cutover patterns. +``` + +### Check for redundant indexes + +Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. + +```ts +// Bad: two indexes where one would do +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team", ["team"]) + .index("by_team_and_user", ["team", "user"]) +``` + +```ts +// Good: single compound index serves both query patterns +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team_and_user", ["team", "user"]) +``` + +Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. + +## 2. Minimize Data Sources + +Trace every read. + +If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. + +### When to denormalize + +Denormalize when all of these are true: + +- the path is hot +- the joined document is much larger than the field you need +- many readers are paying that join cost repeatedly + +Useful mental model: + +`join_cost = rows_per_page x foreign_doc_size x pages_per_second` + +Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. + +### Fallback rule + +Denormalized data is an optimization. Live data is the correctness path. + +Rules: + +- If the denormalized field is missing or null, fall back to the live read +- Do not show placeholders instead of falling back +- In lookup maps, only include fully populated entries + +```ts +// Bad: missing denormalized data becomes a placeholder and blocks correctness +const ownerName = project.ownerName ?? "Unknown owner"; +``` + +```ts +// Good: denormalized data is an optimization, not the only source of truth +const ownerName = + project.ownerName ?? + (await ctx.db.get(project.ownerId))?.name ?? + null; +``` + +Bad lookup map pattern: + +```ts +const ownersById = { + [project.ownerId]: { ownerName: null }, +}; +``` + +That blocks fallback because the map says "I have data" when it does not. + +Good lookup map pattern: + +```ts +const ownersById = + project.ownerName !== undefined && project.ownerName !== null + ? { [project.ownerId]: { ownerName: project.ownerName } } + : {}; +``` + +### No denormalized copy yet + +Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. + +If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. + +Rollout order: + +1. Update schema +2. Update write path +3. Backfill +4. Switch read path + +## 3. Minimize Row Size + +Hot list pages should read the smallest document shape that still answers the UI. + +Prefer summary or digest tables over full source tables when: + +- the list page only needs a subset of fields +- source documents are large +- the query is high volume + +An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. + +Digest tables are a tradeoff, not a default: + +- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost +- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit + +```ts +// Bad: list page reads source docs, then joins owner data per row +const projects = await ctx.db + .query("projects") + .withIndex("by_public", (q) => q.eq("isPublic", true)) + .collect(); +``` + +```ts +// Good: list page reads the smaller digest shape first +const projects = await ctx.db + .query("projectDigests") + .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) + .order("desc") + .take(20); +``` + +## 4. Skip No-Op Writes + +No-op writes still cost work in Convex: + +- invalidation +- replication +- trigger execution +- downstream sync + +Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. + +Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. + +```ts +// Bad: patching unchanged values still triggers invalidation and downstream work +await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, +}); +``` + +```ts +// Good: only write when something actually changed +if (settings.theme !== args.theme || settings.locale !== args.locale) { + await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, + }); +} +``` + +## 5. Match Consistency To Read Patterns + +Choose read strategy based on traffic shape. + +### High-read, low-write + +Examples: + +- public browse pages +- search results +- landing pages +- directory listings + +Prefer: + +- point-in-time reads where appropriate +- explicit refresh +- local state for pagination +- caching where appropriate + +Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. + +### High-read, high-write + +Examples: + +- collaborative editors +- live dashboards +- presence-heavy views + +Reactive queries may be worth the ongoing cost. + +## Convex-Specific Notes + +### Reactive queries + +Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. + +On the client: + +- `useQuery` creates a live subscription +- `usePaginatedQuery` creates a live subscription per page + +For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. + +### Point-in-time reads + +Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. + +Use them for: + +- aggregate snapshots +- reports +- low-churn listings +- pages where explicit refresh is fine + +### Triggers and fan-out + +Triggers fire on every write, including writes that did not materially change the document. + +When a write exists only to keep derived state in sync: + +- diff before patching +- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate + +### Aggregates + +Reactive global counts invalidate frequently on busy tables. + +Prefer: + +- one-shot aggregate fetches +- periodic recomputation +- precomputed summary rows + +for global stats that do not need live updates every second. + +### Backfills + +For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. + +Deploy code that can handle both states before running the backfill. + +During the gap: + +- writes should populate the new shape +- reads should fall back safely + +## Verification + +Before closing the audit, confirm: + +1. Same results as before, no dropped records +2. The removed table or lookup is no longer in the hot-path read set +3. Tests or validation cover fallback behavior +4. Migration safety is preserved while fields or indexes are unbackfilled +5. Sibling functions were fixed consistently diff --git a/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md b/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md new file mode 100644 index 00000000..a96d0466 --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/references/occ-conflicts.md @@ -0,0 +1,126 @@ +# OCC Conflict Resolution + +Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. + +## Core Principle + +Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. + +## Symptoms + +- OCC conflict errors in deployment logs or health page +- Mutations retrying multiple times before succeeding +- User-visible latency spikes on write-heavy pages +- `npx convex insights --details` showing high conflict rates + +## Common Causes + +### Hot documents + +Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. + +### Broad read sets causing false conflicts + +A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. + +### Fan-out from triggers or cascading writes + +A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. + +Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. + +### Write-then-read chains + +A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. + +## Fix Order + +### 1. Reduce read set size + +Narrower reads mean fewer false conflicts. + +```ts +// Bad: broad scan creates a wide conflict surface +const allTasks = await ctx.db.query("tasks").collect(); +const mine = allTasks.filter((t) => t.ownerId === userId); +``` + +```ts +// Good: indexed query touches only relevant documents +const mine = await ctx.db + .query("tasks") + .withIndex("by_owner", (q) => q.eq("ownerId", userId)) + .collect(); +``` + +### 2. Split hot documents + +When many writers target the same document, split the contention point. + +```ts +// Bad: every vote increments the same counter document +const counter = await ctx.db.get(pollCounterId); +await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); +``` + +```ts +// Good: shard the counter across multiple documents, aggregate on read +const shardIndex = Math.floor(Math.random() * SHARD_COUNT); +const shardId = shardIds[shardIndex]; +const shard = await ctx.db.get(shardId); +await ctx.db.patch(shardId, { count: shard!.count + 1 }); +``` + +Aggregate the shards in a query or scheduled job when you need the total. + +### 3. Skip no-op writes + +Writes that do not change data still participate in conflict detection and trigger invalidation. + +```ts +// Bad: patches even when nothing changed +await ctx.db.patch(doc._id, { status: args.status }); +``` + +```ts +// Good: only write when the value actually differs +if (doc.status !== args.status) { + await ctx.db.patch(doc._id, { status: args.status }); +} +``` + +### 4. Move non-critical work to scheduled functions + +If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. + +```ts +// Bad: analytics update in the same transaction as the user action +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +``` + +```ts +// Good: schedule the bookkeeping so the primary transaction is smaller +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { + event: "action", + userId, +}); +``` + +### 5. Combine competing writes + +If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. + +Do not introduce artificial locks or queues unless the above steps have been tried first. + +## Related: Invalidation Scope + +Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. + +## Verification + +1. OCC conflict rate has dropped in insights or dashboard +2. Mutation latency is lower and more consistent +3. No data correctness regressions from splitting or scheduling changes +4. Sibling writers to the same hot documents were fixed consistently diff --git a/.windsurf/skills/convex-performance-audit/references/subscription-cost.md b/.windsurf/skills/convex-performance-audit/references/subscription-cost.md new file mode 100644 index 00000000..ae7d1adb --- /dev/null +++ b/.windsurf/skills/convex-performance-audit/references/subscription-cost.md @@ -0,0 +1,252 @@ +# Subscription Cost + +Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. + +## Core Principle + +Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: + +`subscriptions x invalidation_frequency x query_cost` + +Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. + +## Symptoms + +- Dashboard shows high active subscription count +- UI feels sluggish or laggy despite fast individual queries +- React profiling shows frequent re-renders from Convex state +- Pages with many components each running their own `useQuery` +- Paginated lists where every loaded page stays subscribed + +## Common Causes + +### Reactive queries on low-freshness flows + +Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. + +### Overly broad queries + +A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. + +### Too many subscriptions per page + +A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. + +### Paginated queries keeping all pages live + +`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. + +### Frequently-updated fields on widely-read documents + +A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. + +## Fix Order + +### 1. Use point-in-time reads when live updates are not valuable + +Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. + +Consider a point-in-time read instead when all of these are true: + +- the flow is high-read +- the underlying data changes less often than users need to see +- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable + +Possible implementations depend on environment: + +- a server-rendered fetch +- a framework helper like `fetchQuery` +- a point-in-time client read such as `ConvexHttpClient.query()` + +```ts +// Reactive by default when fresh live data matters +function TeamPresence() { + const presence = useQuery(api.teams.livePresence, { teamId }); + return ; +} +``` + +```ts +// Point-in-time read when explicit refresh is acceptable +import { ConvexHttpClient } from "convex/browser"; + +const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); + +function SnapshotView() { + const [items, setItems] = useState([]); + + useEffect(() => { + client.query(api.items.snapshot).then(setItems); + }, []); + + return ; +} +``` + +Good candidates for point-in-time reads: + +- aggregate snapshots +- reports +- low-churn listings +- flows where explicit refresh is already acceptable + +Keep reactive for: + +- collaborative editing +- live dashboards +- presence-heavy views +- any surface where users expect fresh changes to appear automatically + +### 2. Batch related data into fewer queries + +Instead of N components each fetching their own related data, fetch it in a single query. + +```ts +// Bad: each card fetches its own author +function ProjectCard({ project }: { project: Project }) { + const author = useQuery(api.users.get, { id: project.authorId }); + return ; +} +``` + +```ts +// Good: parent query returns projects with author names included +function ProjectList() { + const projects = useQuery(api.projects.listWithAuthors); + return projects?.map((p) => ( + + )); +} +``` + +This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. + +This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. + +### 3. Use skip to avoid unnecessary subscriptions + +The `"skip"` value prevents a subscription from being created when the arguments are not ready. + +```ts +// Bad: subscribes with undefined args, wastes a subscription slot +const profile = useQuery(api.users.getProfile, { userId: selectedId! }); +``` + +```ts +// Good: skip when there is nothing to fetch +const profile = useQuery( + api.users.getProfile, + selectedId ? { userId: selectedId } : "skip", +); +``` + +### 4. Isolate frequently-updated fields into separate documents + +If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. + +```ts +// Bad: lastSeen lives on the user doc, every heartbeat invalidates +// every query that reads this user +const users = defineTable({ + name: v.string(), + email: v.string(), + lastSeen: v.number(), +}); +``` + +```ts +// Good: lastSeen lives in a separate heartbeat doc +const users = defineTable({ + name: v.string(), + email: v.string(), + heartbeatId: v.id("heartbeats"), +}); + +const heartbeats = defineTable({ + lastSeen: v.number(), +}); +``` + +Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. + +For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. + +### 5. Use the aggregate component for counts and sums + +Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. + +Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. + +If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. + +### 6. Narrow query read sets + +Queries that return less data and touch fewer documents invalidate less often. + +```ts +// Bad: returns all fields, invalidates on any field change +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("projects").collect(); + }, +}); +``` + +```ts +// Good: use a digest table with only the fields the list needs +export const listDigests = query({ + handler: async (ctx) => { + return await ctx.db.query("projectDigests").collect(); + }, +}); +``` + +Writes to fields not in the digest table do not invalidate the digest query. + +### 7. Remove `Date.now()` from queries + +Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. + +```ts +// Bad: Date.now() defeats query caching and causes frequent re-evaluation +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) + .take(100); +``` + +```ts +// Good: use a boolean field updated by a scheduled function +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_is_released", (q) => q.eq("isReleased", true)) + .take(100); +``` + +If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. + +### 8. Consider pagination strategy + +For long lists where users scroll through many pages: + +- If the data does not need live updates, use point-in-time fetching with manual "load more" +- If it does need live updates, accept the subscription cost but limit the number of loaded pages +- Consider whether older pages can be unloaded as the user scrolls forward + +### 9. Separate backend cost from UI churn + +If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. + +Treat this as a UX problem first when: + +- the underlying query is already reasonably cheap +- the complaint is flicker, loading flashes, or re-render churn +- live updates are still desirable once fresh data arrives + +## Verification + +1. Subscription count in dashboard is lower for the affected pages +2. UI responsiveness has improved +3. React profiling shows fewer unnecessary re-renders +4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily +5. Sibling pages with similar patterns were updated consistently diff --git a/.windsurf/skills/convex-quickstart/SKILL.md b/.windsurf/skills/convex-quickstart/SKILL.md new file mode 100644 index 00000000..369a6c9b --- /dev/null +++ b/.windsurf/skills/convex-quickstart/SKILL.md @@ -0,0 +1,337 @@ +--- +name: convex-quickstart +description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. +--- + +# Convex Quickstart + +Set up a working Convex project as fast as possible. + +## When to Use + +- Starting a brand new project with Convex +- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app +- Scaffolding a Convex app for prototyping + +## When Not to Use + +- The project already has Convex installed and `convex/` exists - just start building +- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill + +## Workflow + +1. Determine the starting point: new project or existing app +2. If new project, pick a template and scaffold with `npm create convex@latest` +3. If existing app, install `convex` and wire up the provider +4. Run `npx convex dev` to connect a deployment and start the dev loop +5. Verify the setup works + +## Path 1: New Project (Recommended) + +Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. + +### Pick a template + +| Template | Stack | +|----------|-------| +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | + +If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. + +You can also use any GitHub repo as a template: + +```bash +npm create convex@latest my-app -- -t owner/repo +npm create convex@latest my-app -- -t owner/repo#branch +``` + +### Scaffold the project + +Always pass the project name and template flag to avoid interactive prompts: + +```bash +npm create convex@latest my-app -- -t react-vite-shadcn +cd my-app +npm install +``` + +The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. + +To scaffold in the current directory (if it is empty): + +```bash +npm create convex@latest . -- -t react-vite-shadcn +npm install +``` + +### Start the dev loop + +`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. + +**Ask the user to run this themselves:** + +Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: +- Create a Convex project and dev deployment +- Write the deployment URL to `.env.local` +- Create the `convex/` directory with generated types +- Watch for changes and sync continuously + +The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. + +**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. + +### Start the frontend + +The user should also run the frontend dev server in a separate terminal: + +```bash +npm run dev +``` + +Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. + +### What you get + +After scaffolding, the project structure looks like: + +``` +my-app/ + convex/ # Backend functions and schema + _generated/ # Auto-generated types (check this into git) + schema.ts # Database schema (if template includes one) + src/ # Frontend code (or app/ for Next.js) + package.json + .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL +``` + +The template already has: +- `ConvexProvider` wired into the app root +- Correct env var names for the framework +- Tailwind and shadcn/ui ready (for shadcn templates) +- Auth provider configured (for auth templates) + +You are ready to start adding schema, functions, and UI. + +## Path 2: Add Convex to an Existing App + +Use this when the user already has a frontend project and wants to add Convex as the backend. + +### Install + +```bash +npm install convex +``` + +### Initialize and start dev loop + +Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. + +### Wire up the provider + +The Convex client must wrap the app at the root. The setup varies by framework. + +Create the `ConvexReactClient` at module scope, not inside a component: + +```tsx +// Bad: re-creates the client on every render +function App() { + const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + return ...; +} + +// Good: created once at module scope +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); +function App() { + return ...; +} +``` + +#### React (Vite) + +```tsx +// src/main.tsx +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import App from "./App"; + +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + +createRoot(document.getElementById("root")!).render( + + + + + , +); +``` + +#### Next.js (App Router) + +```tsx +// app/ConvexClientProvider.tsx +"use client"; + +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import { ReactNode } from "react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +export function ConvexClientProvider({ children }: { children: ReactNode }) { + return {children}; +} +``` + +```tsx +// app/layout.tsx +import { ConvexClientProvider } from "./ConvexClientProvider"; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} +``` + +#### Other frameworks + +For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: + +- [Vue](https://docs.convex.dev/quickstart/vue) +- [Svelte](https://docs.convex.dev/quickstart/svelte) +- [React Native](https://docs.convex.dev/quickstart/react-native) +- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) +- [Remix](https://docs.convex.dev/quickstart/remix) +- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) + +### Environment variables + +The env var name depends on the framework: + +| Framework | Variable | +|-----------|----------| +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | +| React Native | `EXPO_PUBLIC_CONVEX_URL` | + +`npx convex dev` writes the correct variable to `.env.local` automatically. + +## Agent Mode (Cloud-Based Agents) + +When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. + +Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: + +```bash +CONVEX_AGENT_MODE=anonymous npx convex dev +``` + +This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. + +## Verify the Setup + +After setup, confirm everything is working: + +1. The user confirms `npx convex dev` is running without errors +2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` +3. `.env.local` contains the deployment URL + +## Writing Your First Function + +Once the project is set up, create a schema and a query to verify the full loop works. + +`convex/schema.ts`: + +```ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + tasks: defineTable({ + text: v.string(), + completed: v.boolean(), + }), +}); +``` + +`convex/tasks.ts`: + +```ts +import { query, mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("tasks").collect(); + }, +}); + +export const create = mutation({ + args: { text: v.string() }, + handler: async (ctx, args) => { + await ctx.db.insert("tasks", { text: args.text, completed: false }); + }, +}); +``` + +Use in a React component (adjust the import path based on your file location relative to `convex/`): + +```tsx +import { useQuery, useMutation } from "convex/react"; +import { api } from "../convex/_generated/api"; + +function Tasks() { + const tasks = useQuery(api.tasks.list); + const create = useMutation(api.tasks.create); + + return ( +
+ + {tasks?.map((t) =>
{t.text}
)} +
+ ); +} +``` + +## Development vs Production + +Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. + +When ready to ship, deploy to production: + +```bash +npx convex deploy +``` + +This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. + +## Next Steps + +- Add authentication: use the `convex-setup-auth` skill +- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) +- Build components: use the `convex-create-component` skill +- Plan a migration: use the `convex-migration-helper` skill +- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) +- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) + +## Checklist + +- [ ] Determined starting point: new project or existing app +- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template +- [ ] If existing app: installed `convex` and wired up the provider +- [ ] User has `npx convex dev` running and connected to a deployment +- [ ] `convex/_generated/` directory exists with types +- [ ] `.env.local` has the deployment URL +- [ ] Verified a basic query/mutation round-trip works diff --git a/.windsurf/skills/convex-quickstart/agents/openai.yaml b/.windsurf/skills/convex-quickstart/agents/openai.yaml new file mode 100644 index 00000000..a51a6d09 --- /dev/null +++ b/.windsurf/skills/convex-quickstart/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Quickstart" + short_description: "Start a new Convex app or add Convex to an existing frontend." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#F97316" + default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." + +policy: + allow_implicit_invocation: true diff --git a/.windsurf/skills/convex-quickstart/assets/icon.svg b/.windsurf/skills/convex-quickstart/assets/icon.svg new file mode 100644 index 00000000..d83a73f3 --- /dev/null +++ b/.windsurf/skills/convex-quickstart/assets/icon.svg @@ -0,0 +1,4 @@ + diff --git a/.windsurf/skills/convex-setup-auth/SKILL.md b/.windsurf/skills/convex-setup-auth/SKILL.md new file mode 100644 index 00000000..5c0c994a --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/SKILL.md @@ -0,0 +1,113 @@ +--- +name: convex-setup-auth +description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. +--- + +# Convex Authentication Setup + +Implement secure authentication in Convex with user management and access control. + +## When to Use + +- Setting up authentication for the first time +- Implementing user management (users table, identity mapping) +- Creating authentication helper functions +- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) + +## First Step: Choose the Auth Provider + +Convex supports multiple authentication approaches. Do not assume a provider. + +Before writing setup code: + +1. Ask the user which auth solution they want, unless the repository already makes it obvious +2. If the repo already uses a provider, continue with that provider unless the user wants to switch +3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding + +Common options: + +- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex +- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features +- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically +- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 +- Custom JWT provider - use when integrating an existing auth system not covered above + +Look for signals in the repo before asking: + +- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages +- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components +- Environment variables that clearly point at a provider + +## After Choosing a Provider + +Read the provider's official guide and the matching local reference file: + +- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` +- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` +- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` +- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` + +The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. + +Use those sources for: + +- package installation +- client provider wiring +- environment variables +- `convex/auth.config.ts` setup +- login and logout UI patterns +- framework-specific setup for React, Vite, or Next.js + +For shared auth behavior, use the official Convex docs as the source of truth: + +- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` +- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage +- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance +- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth + +Do not invent a provider-agnostic user sync pattern from memory. +For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. +For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. + +Do not invent provider-specific setup from memory when the docs are available. +Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. + +## Workflow + +1. Determine the provider, either by asking the user or inferring from the repo +2. Ask whether the user wants local-only setup or production-ready setup now +3. Read the matching provider reference file +4. Follow the official provider docs for current setup details +5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns +6. Only add app-level user storage if the docs and app requirements call for it +7. Add authorization checks for ownership, roles, or team access only where the app needs them +8. Verify login state, protected queries, environment variables, and production configuration if requested + +If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. +For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. +If the environment has browser automation tools, you can use them. +If it does not, give the user a short manual validation checklist instead. + +## Reference Files + +### Provider References + +- `references/convex-auth.md` +- `references/clerk.md` +- `references/workos-authkit.md` +- `references/auth0.md` + +## Checklist + +- [ ] Chosen the correct auth provider before writing setup code +- [ ] Read the relevant provider reference file +- [ ] Asked whether the user wants local-only setup or production-ready setup +- [ ] Used the official provider docs for provider-specific wiring +- [ ] Used the official Convex docs for shared auth behavior and authorization patterns +- [ ] Only added app-level user storage if the app actually needs it +- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth +- [ ] Added authentication checks in protected backend functions +- [ ] Added authorization checks where the app actually needs them +- [ ] Clear error messages ("Not authenticated", "Unauthorized") +- [ ] Client auth provider configured for the chosen provider +- [ ] If requested, production auth setup is covered too diff --git a/.windsurf/skills/convex-setup-auth/agents/openai.yaml b/.windsurf/skills/convex-setup-auth/agents/openai.yaml new file mode 100644 index 00000000..d1c90a14 --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Setup Auth" + short_description: "Set up Convex auth, user identity mapping, and access control." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#2563EB" + default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." + +policy: + allow_implicit_invocation: true diff --git a/.windsurf/skills/convex-setup-auth/assets/icon.svg b/.windsurf/skills/convex-setup-auth/assets/icon.svg new file mode 100644 index 00000000..4917dbb4 --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/.windsurf/skills/convex-setup-auth/references/auth0.md b/.windsurf/skills/convex-setup-auth/references/auth0.md new file mode 100644 index 00000000..9c729c5a --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/references/auth0.md @@ -0,0 +1,116 @@ +# Auth0 + +Official docs: + +- https://docs.convex.dev/auth/auth0 +- https://auth0.github.io/auth0-cli/ +- https://auth0.github.io/auth0-cli/auth0_apps_create.html + +Use this when the app already uses Auth0 or the user wants Auth0 specifically. + +## Workflow + +1. Confirm the user wants Auth0 +2. Determine the app framework and whether Auth0 is already partly set up +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and Auth0 guides before making changes +5. Ask whether they want the fastest setup path by installing the Auth0 CLI +6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI +7. If they do not want the CLI path, use the Auth0 dashboard path instead +8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up +9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID +10. Set environment variables for local and production environments +11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +12. Gate Convex-backed UI with Convex auth state +13. Try to verify Convex reports the user as authenticated after Auth0 login +14. If the refresh-token path fails, stop improvising and send the user back to the official docs +15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered + +## What To Do + +- Read the official Convex and Auth0 guide before writing setup code +- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet +- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" +- Make sure the app has already completed the relevant Auth0 quickstart for its frontend +- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` +- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated + +## Key Setup Areas + +- install the Auth0 SDK for the app's framework +- configure `convex/auth.config.ts` with the Auth0 domain and client ID +- set environment variables for local and production environments +- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +- use Convex auth state when gating Convex-backed UI + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- frontend app entry or provider wrapper +- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` +- Auth0 environment variables commonly include: + - `AUTH0_DOMAIN` + - `AUTH0_CLIENT_ID` + - `VITE_AUTH0_DOMAIN` + - `VITE_AUTH0_CLIENT_ID` + +## Concrete Steps + +1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework +2. Ask whether the user wants the Auth0 CLI path +3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` +4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app +5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard +6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard +7. Install the Auth0 SDK for the app's framework +8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID +9. Set frontend and backend environment variables +10. Wrap the app in `Auth0Provider` +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` +12. Run the normal Convex dev or deploy flow after backend config changes +13. Try the official provider config shown in the Convex docs +14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now +15. Only claim success if the user can sign in and Convex recognizes the authenticated session +16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too + +## Gotchas + +- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch +- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant +- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard +- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced +- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end +- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled +- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation +- Keep dev and prod tenants separate if the project uses different Auth0 environments +- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. +- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. +- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. +- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered +- Verify production environment variables and redirect settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the Auth0 login flow +- Verify Convex-authenticated UI renders only after Convex auth state is ready +- Verify protected Convex queries succeed after login +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- Verify the Auth0 app settings match the real local callback and logout URLs during development +- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully +- If production-ready setup was requested, verify the production Auth0 configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Auth0 +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Complete the relevant Auth0 frontend setup +- [ ] Configure `convex/auth.config.ts` +- [ ] Set environment variables +- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs +- [ ] If requested, configure the production deployment too diff --git a/.windsurf/skills/convex-setup-auth/references/clerk.md b/.windsurf/skills/convex-setup-auth/references/clerk.md new file mode 100644 index 00000000..7dbde194 --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/references/clerk.md @@ -0,0 +1,113 @@ +# Clerk + +Official docs: + +- https://docs.convex.dev/auth/clerk +- https://clerk.com/docs/guides/development/integrations/databases/convex + +Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. + +## Workflow + +1. Confirm the user wants Clerk +2. Make sure the user has a Clerk account and a Clerk application +3. Determine the app framework: + - React + - Next.js + - TanStack Start +4. Ask whether the user wants local-only setup or production-ready setup now +5. Gather the Clerk keys and the Clerk Frontend API URL +6. Follow the correct framework section in the official docs +7. Complete the backend and client wiring +8. Verify Convex reports the user as authenticated after login +9. If the user wants production-ready setup, make sure the production Clerk config is also covered + +## What To Do + +- Read the official Convex and Clerk guide before writing setup code +- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application +- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active +- Match the guide to the app's framework, usually React, Next.js, or TanStack Start +- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` + +## Key Setup Areas + +- install the Clerk SDK for the framework in use +- configure `convex/auth.config.ts` with the Clerk issuer domain +- set the required Clerk environment variables +- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` +- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- React or Vite client entry such as `src/main.tsx` +- Next.js client wrapper for Convex if using App Router +- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` +- Clerk app creation page: `https://dashboard.clerk.com/apps/new` +- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` +- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` +- Clerk environment variables: + - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs + - `CLERK_FRONTEND_API_URL` in the Clerk docs + - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps + - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps + - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required + +`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. + +## Concrete Steps + +1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` +2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` +3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed +4. Open `https://dashboard.clerk.com/apps/setup/convex` +5. Activate the Convex integration in Clerk if it is not already active +6. Copy the Clerk Frontend API URL shown there +7. Install the Clerk package for the app's framework +8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens +9. Set the publishable key in the frontend environment +10. Set the issuer domain or Frontend API URL so Convex can validate the JWT +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` +12. Wrap the app in `ClerkProvider` +13. Use Convex auth helpers for authenticated rendering +14. Run the normal Convex dev or deploy flow after updating backend auth config +15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too + +## Gotchas + +- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render +- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper +- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config +- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. +- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. +- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. +- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. +- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` +- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included +- Verify production redirect URLs and any production Clerk domain values before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can sign in with Clerk +- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in +- Verify `useConvexAuth()` reaches the authenticated state after Clerk login +- Verify protected Convex queries run successfully inside authenticated UI +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- If production-ready setup was requested, verify the production Clerk configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Clerk +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Follow the correct framework section in the official guide +- [ ] Set Clerk environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify Convex authenticated state after login +- [ ] If requested, configure the production deployment too diff --git a/.windsurf/skills/convex-setup-auth/references/convex-auth.md b/.windsurf/skills/convex-setup-auth/references/convex-auth.md new file mode 100644 index 00000000..d4824d24 --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/references/convex-auth.md @@ -0,0 +1,143 @@ +# Convex Auth + +Official docs: https://docs.convex.dev/auth/convex-auth +Setup guide: https://labs.convex.dev/auth/setup + +Use this when the user wants auth handled directly in Convex rather than through a third-party provider. + +## Workflow + +1. Confirm the user wants Convex Auth specifically +2. Determine which sign-in methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords and password reset +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the Convex Auth setup guide before writing code +5. Make sure the project has a configured Convex deployment: + - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set + - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing +6. Install the auth packages: + - `npm install @convex-dev/auth @auth/core@0.37.0` +7. Run the initialization command: + - `npx @convex-dev/auth` +8. Confirm the initializer created: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +9. Add the required `authTables` to `convex/schema.ts` +10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` +11. Configure at least one auth method in `convex/auth.ts` +12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code +13. Verify the client can sign in successfully +14. Verify Convex receives authenticated identity in backend functions +15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well +16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex + +## What This Reference Is For + +- choosing Convex Auth as the default provider for a new Convex app +- understanding whether the app wants magic links, OTPs, OAuth, or passwords +- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior + +## What To Do + +- Read the Convex Auth setup guide before writing setup code +- Follow the setup flow from the docs rather than recreating it from memory +- If the app is new, consider starting from the official starter flow instead of hand-wiring everything +- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra + +## Concrete Steps + +1. Install `@convex-dev/auth` and `@auth/core@0.37.0` +2. Run `npx convex dev` if the project does not already have a configured deployment +3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment +4. Run `npx @convex-dev/auth` +5. Confirm the generated auth setup is present before continuing: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +6. Add `authTables` to `convex/schema.ts` +7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry +8. Configure the selected auth methods in `convex/auth.ts` +9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed +10. Verify login locally +11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment + +## Expected Files and Decisions + +- `convex/schema.ts` +- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file +- generated Convex Auth setup produced by `npx @convex-dev/auth` +- an existing configured Convex deployment, or the ability to create one with `npx convex dev` +- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods + +- Decide whether the user is creating a new app or adding auth to an existing app +- For a new app, prefer the official starter flow instead of rebuilding setup by hand +- Decide which auth methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords +- Decide whether the user wants local-only setup or production-ready setup now +- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough + +## Gotchas + +- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. +- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. +- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. +- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. +- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. +- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. +- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. +- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. +- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. +- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment +- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Human Handoff + +If `npx convex dev` or deployment setup requires human input: + +- stop and explain exactly what the user needs to do +- say why that step is required +- resume the auth setup immediately after the user confirms it is done + +## Validation + +- Verify the user can complete a sign-in flow +- Offer to validate sign up, sign out, and sign back in with the configured auth method +- If browser automation is available in the environment, you can do this directly +- If browser automation is not available, give the user a short manual validation checklist instead +- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions +- Verify protected UI only renders after Convex-authenticated state is ready +- Verify environment variables and redirect settings match the current app environment +- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in +- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed +- If production-ready setup was requested, verify the production deployment is also configured correctly + +## Checklist + +- [ ] Confirm the user wants Convex Auth specifically +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Ensure a Convex deployment is configured before running auth initialization +- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` +- [ ] Run `npx convex dev` first if needed +- [ ] Run `npx @convex-dev/auth` +- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created +- [ ] Follow the setup guide for package install and wiring +- [ ] Add `authTables` to `convex/schema.ts` +- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` +- [ ] Configure at least one auth method in `convex/auth.ts` +- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes +- [ ] Confirm which sign-in methods the app needs +- [ ] Verify the client can sign in and the backend receives authenticated identity +- [ ] Offer end-to-end validation of sign up, sign out, and sign back in +- [ ] If requested, configure the production deployment too +- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/.windsurf/skills/convex-setup-auth/references/workos-authkit.md b/.windsurf/skills/convex-setup-auth/references/workos-authkit.md new file mode 100644 index 00000000..038cb9f3 --- /dev/null +++ b/.windsurf/skills/convex-setup-auth/references/workos-authkit.md @@ -0,0 +1,114 @@ +# WorkOS AuthKit + +Official docs: + +- https://docs.convex.dev/auth/authkit/ +- https://docs.convex.dev/auth/authkit/add-to-app +- https://docs.convex.dev/auth/authkit/auto-provision + +Use this when the app already uses WorkOS or the user wants AuthKit specifically. + +## Workflow + +1. Confirm the user wants WorkOS AuthKit +2. Determine whether they want: + - a Convex-managed WorkOS team + - an existing WorkOS team +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and WorkOS AuthKit guide +5. Create or update `convex.json` for the app's framework and real local port +6. Follow the correct branch of the setup flow based on that choice +7. Configure the required WorkOS environment variables +8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs +9. Wire the client provider and callback flow +10. Verify authenticated requests reach Convex +11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too +12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex + +## What To Do + +- Read the official Convex and WorkOS AuthKit guide before writing setup code +- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team +- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra +- Follow the current setup flow from the docs instead of relying on older examples + +## Key Setup Areas + +- package installation for the app's framework +- `convex.json` with the `authKit` section for dev, and preview or prod if needed +- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration +- `convex/auth.config.ts` wiring for WorkOS-issued JWTs +- client provider setup and token flow into Convex +- login callback and redirect configuration + +## Files and Env Vars To Expect + +- `convex.json` +- `convex/auth.config.ts` +- frontend auth provider wiring +- callback or redirect route setup where the framework requires it +- WorkOS environment variables commonly include: + - `WORKOS_CLIENT_ID` + - `WORKOS_API_KEY` + - `WORKOS_COOKIE_PASSWORD` + - `VITE_WORKOS_CLIENT_ID` + - `VITE_WORKOS_REDIRECT_URI` + - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` + +For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. + +## Concrete Steps + +1. Choose Convex-managed or existing WorkOS team +2. Create or update `convex.json` with the `authKit` section for the framework in use +3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port +4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow +5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` +6. Create or update `convex/auth.config.ts` for WorkOS JWT validation +7. Run the normal Convex dev or deploy flow so backend config is synced +8. Wire the WorkOS client provider in the app +9. Configure callback and redirect handling +10. Verify the user can sign in and return to the app +11. Verify Convex sees the authenticated user after login +12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too + +## Gotchas + +- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious +- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys +- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex +- Do not mix dev and prod WorkOS credentials or redirect URIs +- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it +- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. +- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. +- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. +- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. +- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered +- Verify the production redirect and callback settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the login flow and return to the app +- Verify the callback URL matches the real frontend port in local dev +- Verify Convex receives authenticated requests after login +- Verify `convex.json` matches the framework and chosen WorkOS setup path +- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path +- Verify environment variables differ correctly between local and production where needed +- If production-ready setup was requested, verify the production WorkOS configuration is also covered + +## Checklist + +- [ ] Confirm the user wants WorkOS AuthKit +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Choose Convex-managed or existing WorkOS team +- [ ] Create or update `convex.json` +- [ ] Configure WorkOS environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify authenticated requests reach Convex after login +- [ ] If requested, configure the production deployment too diff --git a/AGENTS.md b/AGENTS.md index 0c8ff483..3cb60907 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,3 +19,11 @@ A Flutter desktop app for creating interactive Valorant game strategies. See `RE - **No automated tests exist** in this codebase. `flutter test` will find nothing. - **Lint.** `fvm flutter analyze` — expect ~70 pre-existing warnings/infos (unused imports, deprecated APIs). No errors. - **Build.** `fvm flutter build linux --debug` produces the binary at `build/linux/x64/debug/bundle/icarus`. + + +This project uses [Convex](https://convex.dev) as its backend. + +When working on Convex code, **always read `convex/_generated/ai/guidelines.md` first** for important guidelines on how to correctly use Convex APIs and patterns. The file contains rules that override what you may have learned about Convex from training data. + +Convex agent skills for common tasks can be installed by running `npx convex ai-files install`. + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..ba211633 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,7 @@ + +This project uses [Convex](https://convex.dev) as its backend. + +When working on Convex code, **always read `convex/_generated/ai/guidelines.md` first** for important guidelines on how to correctly use Convex APIs and patterns. The file contains rules that override what you may have learned about Convex from training data. + +Convex agent skills for common tasks can be installed by running `npx convex ai-files install`. + diff --git a/convex/_generated/ai/ai-files.state.json b/convex/_generated/ai/ai-files.state.json new file mode 100644 index 00000000..eb4c8eb0 --- /dev/null +++ b/convex/_generated/ai/ai-files.state.json @@ -0,0 +1,13 @@ +{ + "guidelinesHash": "deca8f973b701e27f65ab9d2b189201fcbcefcf524e9bc44c413ab3109e35993", + "agentsMdSectionHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2", + "claudeMdHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2", + "agentSkillsSha": "cd697e02ca46ccbc445418785e03ad87a35617c9", + "installedSkillNames": [ + "convex-create-component", + "convex-migration-helper", + "convex-performance-audit", + "convex-quickstart", + "convex-setup-auth" + ] +} diff --git a/convex/_generated/ai/guidelines.md b/convex/_generated/ai/guidelines.md new file mode 100644 index 00000000..5b872554 --- /dev/null +++ b/convex/_generated/ai/guidelines.md @@ -0,0 +1,303 @@ +# Convex guidelines +## Function guidelines +### Http endpoint syntax +- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example: +```typescript +import { httpRouter } from "convex/server"; +import { httpAction } from "./_generated/server"; +const http = httpRouter(); +http.route({ + path: "/echo", + method: "POST", + handler: httpAction(async (ctx, req) => { + const body = await req.bytes(); + return new Response(body, { status: 200 }); + }), +}); +``` +- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`. + +### Validators +- Below is an example of an array validator: +```typescript +import { mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export default mutation({ +args: { + simpleArray: v.array(v.union(v.string(), v.number())), +}, +handler: async (ctx, args) => { + //... +}, +}); +``` +- Below is an example of a schema with validators that codify a discriminated union type: +```typescript +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + results: defineTable( + v.union( + v.object({ + kind: v.literal("error"), + errorMessage: v.string(), + }), + v.object({ + kind: v.literal("success"), + value: v.number(), + }), + ), + ) +}); +``` +- Here are the valid Convex types along with their respective validators: +Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes | +| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Id | string | `doc._id` | `v.id(tableName)` | | +| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. | +| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. | +| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. | +| Boolean | boolean | `true` | `v.boolean()` | +| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. | +| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. | +| Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. | +| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". | +| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". | + +### Function registration +- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`. +- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private. +- You CANNOT register a function through the `api` or `internal` objects. +- ALWAYS include argument validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. + +### Function calling +- Use `ctx.runQuery` to call a query from a query, mutation, or action. +- Use `ctx.runMutation` to call a mutation from a mutation or action. +- Use `ctx.runAction` to call an action from an action. +- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead. +- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions. +- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls. +- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example, +``` +export const f = query({ + args: { name: v.string() }, + handler: async (ctx, args) => { + return "Hello " + args.name; + }, +}); + +export const g = query({ + args: {}, + handler: async (ctx, args) => { + const result: string = await ctx.runQuery(api.example.f, { name: "Bob" }); + return null; + }, +}); +``` + +### Function references +- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`. +- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`. +- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`. +- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`. +- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`. + +### Pagination +- Define pagination using the following syntax: + +```ts +import { v } from "convex/values"; +import { query, mutation } from "./_generated/server"; +import { paginationOptsValidator } from "convex/server"; +export const listWithExtraArg = query({ + args: { paginationOpts: paginationOptsValidator, author: v.string() }, + handler: async (ctx, args) => { + return await ctx.db + .query("messages") + .withIndex("by_author", (q) => q.eq("author", args.author)) + .order("desc") + .paginate(args.paginationOpts); + }, +}); +``` +Note: `paginationOpts` is an object with the following properties: +- `numItems`: the maximum number of documents to return (the validator is `v.number()`) +- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`) +- A query that ends in `.paginate()` returns an object that has the following properties: +- page (contains an array of documents that you fetches) +- isDone (a boolean that represents whether or not this is the last page of documents) +- continueCursor (a string that represents the cursor to use to fetch the next page of documents) + + +## Schema guidelines +- Always define your schema in `convex/schema.ts`. +- Always import the schema definition functions from `convex/server`. +- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`. +- Always include all index fields in the index name. For example, if an index is defined as `["field1", "field2"]`, the index name should be "by_field1_and_field2". +- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes. +- Do not store unbounded lists as an array field inside a document (e.g. `v.array(v.object({...}))`). As the array grows it will hit the 1MB document size limit, and every update rewrites the entire document. Instead, create a separate table for the child items with a foreign key back to the parent. + +## Authentication guidelines +- Convex supports JWT-based authentication through `convex/auth.config.ts`. ALWAYS create this file when using authentication. Without it, `ctx.auth.getUserIdentity()` will always return `null`. +- Example `convex/auth.config.ts`: +```typescript +export default { + providers: [ + { + domain: "https://your-auth-provider.com", + applicationID: "convex", + }, + ], +}; +``` +The `domain` must be the issuer URL of the JWT provider. Convex fetches `{domain}/.well-known/openid-configuration` to discover the JWKS endpoint. The `applicationID` is checked against the JWT `aud` (audience) claim. +- Use `ctx.auth.getUserIdentity()` to get the authenticated user's identity in any query, mutation, or action. This returns `null` if the user is not authenticated, or a `UserIdentity` object with fields like `subject`, `issuer`, `name`, `email`, etc. The `subject` field is the unique user identifier. +- In Convex `UserIdentity`, `tokenIdentifier` is guaranteed and is the canonical stable identifier for the authenticated identity. For any auth-linked database lookup or ownership check, prefer `identity.tokenIdentifier` over `identity.subject`. Do NOT use `identity.subject` alone as a global identity key. +- NEVER accept a `userId` or any user identifier as a function argument for authorization purposes. Always derive the user identity server-side via `ctx.auth.getUserIdentity()`. +- When using an external auth provider with Convex on the client, use `ConvexProviderWithAuth` instead of `ConvexProvider`: +```tsx +import { ConvexProviderWithAuth, ConvexReactClient } from "convex/react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +function App({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} +``` +The `useAuth` prop must return `{ isLoading, isAuthenticated, fetchAccessToken }`. Do NOT use plain `ConvexProvider` when authentication is needed — it will not send tokens with requests. + +## Typescript guidelines +- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table. +- Use `Doc<"tableName">` from `./_generated/dataModel` to get the full document type for a table. +- Use `QueryCtx`, `MutationCtx`, `ActionCtx` from `./_generated/server` for typing function contexts. NEVER use `any` for ctx parameters — always use the proper context type. +- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record, string>`. Below is an example of using `Record` with an `Id` type in a query: +```ts +import { query } from "./_generated/server"; +import { Doc, Id } from "./_generated/dataModel"; + +export const exampleQuery = query({ + args: { userIds: v.array(v.id("users")) }, + handler: async (ctx, args) => { + const idToUsername: Record, string> = {}; + for (const userId of args.userIds) { + const user = await ctx.db.get("users", userId); + if (user) { + idToUsername[user._id] = user.username; + } + } + + return idToUsername; + }, +}); +``` +- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`. + +## Full text search guidelines +- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like: + +const messages = await ctx.db + .query("messages") + .withSearchIndex("search_body", (q) => + q.search("body", "hello hi").eq("channel", "#general"), + ) + .take(10); + +## Query guidelines +- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead. +- If the user does not explicitly tell you to return all results from a query you should ALWAYS return a bounded collection instead. So that is instead of using `.collect()` you should use `.take()` or paginate on database queries. This prevents future performance issues when tables grow in an unbounded way. +- Never use `.collect().length` to count rows. Convex has no built-in count operator, so if you need a count that stays efficient at scale, maintain a denormalized counter in a separate document and update it in your mutations. +- Convex queries do NOT support `.delete()`. If you need to delete all documents matching a query, use `.take(n)` to read them in batches, iterate over each batch calling `ctx.db.delete(row._id)`, and repeat until no more results are returned. +- Convex mutations are transactions with limits on the number of documents read and written. If a mutation needs to process more documents than fit in a single transaction (e.g. bulk deletion on a large table), process a batch with `.take(n)` and then call `ctx.scheduler.runAfter(0, api.myModule.myMutation, args)` to schedule itself to continue. This way each invocation stays within transaction limits. +- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query. +- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax. +### Ordering +- By default Convex always returns documents in ascending `_creationTime` order. +- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending. +- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans. + + +## Mutation guidelines +- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })` +- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })` + +## Action guidelines +- Always add `"use node";` to the top of files containing actions that use Node.js built-in modules. +- Never add `"use node";` to a file that also exports queries or mutations. Only actions can run in the Node.js runtime; queries and mutations must stay in the default Convex runtime. If you need Node.js built-ins alongside queries or mutations, put the action in a separate file. +- `fetch()` is available in the default Convex runtime. You do NOT need `"use node";` just to use `fetch()`. +- Never use `ctx.db` inside of an action. Actions don't have access to the database. +- Below is an example of the syntax for an action: +```ts +import { action } from "./_generated/server"; + +export const exampleAction = action({ + args: {}, + handler: async (ctx, args) => { + console.log("This action does not return anything"); + return null; + }, +}); +``` + +## Scheduling guidelines +### Cron guidelines +- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers. +- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods. +- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example, +```ts +import { cronJobs } from "convex/server"; +import { internal } from "./_generated/api"; +import { internalAction } from "./_generated/server"; + +const empty = internalAction({ + args: {}, + handler: async (ctx, args) => { + console.log("empty"); + }, +}); + +const crons = cronJobs(); + +// Run `internal.crons.empty` every two hours. +crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {}); + +export default crons; +``` +- You can register Convex functions within `crons.ts` just like any other file. +- If a cron calls an internal function, always import the `internal` object from '_generated/api', even if the internal function is registered in the same file. + + +## File storage guidelines +- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist. +- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata. + +Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`. +``` +import { query } from "./_generated/server"; +import { Id } from "./_generated/dataModel"; + +type FileMetadata = { + _id: Id<"_storage">; + _creationTime: number; + contentType?: string; + sha256: string; + size: number; +} + +export const exampleQuery = query({ + args: { fileId: v.id("_storage") }, + handler: async (ctx, args) => { + const metadata: FileMetadata | null = await ctx.db.system.get("_storage", args.fileId); + console.log(metadata); + return null; + }, +}); +``` +- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage. + + diff --git a/convex/folders.ts b/convex/folders.ts index 76ba4b55..65c807af 100644 --- a/convex/folders.ts +++ b/convex/folders.ts @@ -3,6 +3,101 @@ import { v } from "convex/values"; import { requireCurrentUser } from "./lib/auth"; import { getFolderByPublicId } from "./lib/entities"; +async function deleteStrategyCascade(ctx: any, strategy: any) { + const pages = await ctx.db + .query("pages") + .withIndex("by_strategyId", (q: any) => q.eq("strategyId", strategy._id)) + .collect(); + + for (const page of pages) { + const pageElements = await ctx.db + .query("elements") + .withIndex("by_pageId", (q: any) => q.eq("pageId", page._id)) + .collect(); + for (const element of pageElements) { + await ctx.db.delete(element._id); + } + + const pageLineups = await ctx.db + .query("lineups") + .withIndex("by_pageId", (q: any) => q.eq("pageId", page._id)) + .collect(); + for (const lineup of pageLineups) { + await ctx.db.delete(lineup._id); + } + + const assets = await ctx.db + .query("imageAssets") + .withIndex("by_pageId", (q: any) => q.eq("pageId", page._id)) + .collect(); + for (const asset of assets) { + await ctx.db.delete(asset._id); + } + + await ctx.db.delete(page._id); + } + + const collaborators = await ctx.db + .query("strategyCollaborators") + .withIndex("by_strategyId", (q: any) => q.eq("strategyId", strategy._id)) + .collect(); + for (const collaborator of collaborators) { + await ctx.db.delete(collaborator._id); + } + + const invites = await ctx.db + .query("inviteTokens") + .withIndex("by_strategyId", (q: any) => q.eq("strategyId", strategy._id)) + .collect(); + for (const invite of invites) { + await ctx.db.delete(invite._id); + } + + await ctx.db.delete(strategy._id); +} + +async function deleteFolderCascade(ctx: any, folder: any) { + const childFolders = await ctx.db + .query("folders") + .withIndex("by_parentFolderId", (q: any) => q.eq("parentFolderId", folder._id)) + .collect(); + + for (const child of childFolders) { + await deleteFolderCascade(ctx, child); + } + + const strategies = await ctx.db + .query("strategies") + .withIndex("by_folderId", (q: any) => q.eq("folderId", folder._id)) + .collect(); + for (const strategy of strategies) { + await deleteStrategyCascade(ctx, strategy); + } + + await ctx.db.delete(folder._id); +} + +async function assertFolderParentIsValid(ctx: any, folder: any, parentFolderId: any) { + if (parentFolderId === undefined) { + return; + } + + if (folder._id === parentFolderId) { + throw new Error("Cannot move folder into itself"); + } + + let current = await ctx.db.get(parentFolderId); + while (current !== null) { + if (current._id === folder._id) { + throw new Error("Cannot move folder into its descendant"); + } + if (current.parentFolderId === undefined) { + break; + } + current = await ctx.db.get(current.parentFolderId); + } +} + export const listForParent = query({ args: { parentFolderPublicId: v.optional(v.string()), @@ -30,6 +125,9 @@ export const listForParent = query({ .map((f) => ({ publicId: f.publicId, name: f.name, + iconIndex: f.iconIndex ?? null, + colorKey: f.colorKey ?? null, + customColorValue: f.customColorValue ?? null, parentFolderPublicId: f.parentFolderId === undefined ? null @@ -45,6 +143,9 @@ export const create = mutation({ publicId: v.string(), name: v.string(), parentFolderPublicId: v.optional(v.string()), + iconIndex: v.optional(v.number()), + colorKey: v.optional(v.string()), + customColorValue: v.optional(v.number()), }, handler: async (ctx, args) => { const user = await requireCurrentUser(ctx); @@ -76,6 +177,9 @@ export const create = mutation({ ownerId: user._id, name: args.name, parentFolderId, + iconIndex: args.iconIndex, + colorKey: args.colorKey, + customColorValue: args.customColorValue, createdAt: now, updatedAt: now, }); @@ -88,6 +192,10 @@ export const update = mutation({ args: { folderPublicId: v.string(), name: v.optional(v.string()), + iconIndex: v.optional(v.number()), + colorKey: v.optional(v.string()), + customColorValue: v.optional(v.number()), + clearCustomColorValue: v.optional(v.boolean()), }, handler: async (ctx, args) => { const user = await requireCurrentUser(ctx); @@ -97,13 +205,30 @@ export const update = mutation({ throw new Error("Forbidden"); } - const patch: { name?: string; updatedAt: number } = { + const patch: { + name?: string; + iconIndex?: number; + colorKey?: string; + customColorValue?: number | undefined; + updatedAt: number; + } = { updatedAt: Date.now(), }; if (args.name !== undefined) { patch.name = args.name; } + if (args.iconIndex !== undefined) { + patch.iconIndex = args.iconIndex; + } + if (args.colorKey !== undefined) { + patch.colorKey = args.colorKey; + } + if (args.clearCustomColorValue === true) { + patch.customColorValue = undefined; + } else if (args.customColorValue !== undefined) { + patch.customColorValue = args.customColorValue; + } await ctx.db.patch(folder._id, patch); return { ok: true }; @@ -132,6 +257,8 @@ export const move = mutation({ parentFolderId = parent._id; } + await assertFolderParentIsValid(ctx, folder, parentFolderId); + await ctx.db.patch(folder._id, { parentFolderId, updatedAt: Date.now(), @@ -153,25 +280,54 @@ export const deleteFolder = mutation({ throw new Error("Forbidden"); } - const children = await ctx.db - .query("folders") - .withIndex("by_parentFolderId", (q) => q.eq("parentFolderId", folder._id)) - .collect(); - if (children.length > 0) { - throw new Error("Folder has children"); + await deleteFolderCascade(ctx, folder); + return { ok: true }; + }, +}); + +export const getPath = query({ + args: { + folderPublicId: v.optional(v.string()), + }, + handler: async (ctx, args) => { + const user = await requireCurrentUser(ctx); + if (args.folderPublicId === undefined) { + return []; } - const strategies = await ctx.db - .query("strategies") - .withIndex("by_folderId", (q) => q.eq("folderId", folder._id)) - .collect(); - if (strategies.length > 0) { - throw new Error("Folder has strategies"); + const path = []; + let current = await getFolderByPublicId(ctx, args.folderPublicId); + + while (current !== null) { + if (current.ownerId !== user._id) { + throw new Error("Forbidden"); + } + + path.unshift({ + publicId: current.publicId, + name: current.name, + iconIndex: current.iconIndex ?? null, + colorKey: current.colorKey ?? null, + customColorValue: current.customColorValue ?? null, + createdAt: current.createdAt, + updatedAt: current.updatedAt, + parentFolderPublicId: null, + }); + + if (current.parentFolderId === undefined) { + break; + } + + current = await ctx.db.get(current.parentFolderId); } - await ctx.db.delete(folder._id); - return { ok: true }; + for (let i = 0; i < path.length; i += 1) { + path[i].parentFolderPublicId = i === 0 ? null : path[i - 1].publicId; + } + + return path; }, }); +export { deleteFolder as deleteRecursive }; export { deleteFolder as delete }; diff --git a/convex/schema.ts b/convex/schema.ts index ee8e375b..5e6c1b48 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -15,6 +15,9 @@ export default defineSchema({ ownerId: v.id("users"), name: v.string(), parentFolderId: v.optional(v.id("folders")), + iconIndex: v.optional(v.number()), + colorKey: v.optional(v.string()), + customColorValue: v.optional(v.number()), createdAt: v.number(), updatedAt: v.number(), }) diff --git a/convex/strategies.ts b/convex/strategies.ts index ca203528..575225f4 100644 --- a/convex/strategies.ts +++ b/convex/strategies.ts @@ -1,6 +1,10 @@ import { mutation, query } from "./_generated/server"; import { v } from "convex/values"; -import { assertStrategyRole, requireCurrentUser } from "./lib/auth"; +import { + assertStrategyRole, + getStrategyRoleForUser, + requireCurrentUser, +} from "./lib/auth"; import { getFolderByPublicId, getStrategyByPublicId } from "./lib/entities"; async function listAccessibleStrategies(ctx: any, userId: any) { @@ -58,10 +62,12 @@ export const listForFolder = query({ } } - return all + const filtered = all .filter((s) => s.folderId === folderId) - .sort((a, b) => b.updatedAt - a.updatedAt) - .map((s) => ({ + .sort((a, b) => b.updatedAt - a.updatedAt); + + return Promise.all( + filtered.map(async (s) => ({ publicId: s.publicId, name: s.name, mapData: s.mapData, @@ -69,10 +75,14 @@ export const listForFolder = query({ createdAt: s.createdAt, updatedAt: s.updatedAt, folderPublicId: - s.folderId === undefined ? null : folderIdToPublicId.get(s.folderId) ?? null, + s.folderId === undefined + ? null + : folderIdToPublicId.get(s.folderId) ?? null, themeProfileId: s.themeProfileId ?? null, themeOverridePalette: s.themeOverridePalette ?? null, - })); + role: await getStrategyRoleForUser(ctx, s, user._id), + })), + ); }, }); diff --git a/lib/collab/collab_models.dart b/lib/collab/collab_models.dart index 70270e36..f949f3c5 100644 --- a/lib/collab/collab_models.dart +++ b/lib/collab/collab_models.dart @@ -312,6 +312,7 @@ class CloudStrategySummary { required this.sequence, required this.createdAt, required this.updatedAt, + this.role, }); final String publicId; @@ -320,6 +321,7 @@ class CloudStrategySummary { final int sequence; final DateTime createdAt; final DateTime updatedAt; + final String? role; factory CloudStrategySummary.fromJson(Map json) { return CloudStrategySummary( @@ -333,6 +335,7 @@ class CloudStrategySummary { updatedAt: DateTime.fromMillisecondsSinceEpoch( (json['updatedAt'] as num?)?.toInt() ?? 0, ), + role: json['role'] as String?, ); } } @@ -344,6 +347,9 @@ class CloudFolderSummary { required this.createdAt, required this.updatedAt, this.parentFolderPublicId, + this.iconIndex, + this.colorKey, + this.customColorValue, }); final String publicId; @@ -351,6 +357,9 @@ class CloudFolderSummary { final DateTime createdAt; final DateTime updatedAt; final String? parentFolderPublicId; + final int? iconIndex; + final String? colorKey; + final int? customColorValue; factory CloudFolderSummary.fromJson(Map json) { return CloudFolderSummary( @@ -363,6 +372,9 @@ class CloudFolderSummary { (json['updatedAt'] as num?)?.toInt() ?? 0, ), parentFolderPublicId: json['parentFolderPublicId'] as String?, + iconIndex: (json['iconIndex'] as num?)?.toInt(), + colorKey: json['colorKey'] as String?, + customColorValue: (json['customColorValue'] as num?)?.toInt(), ); } } diff --git a/lib/collab/convex_strategy_repository.dart b/lib/collab/convex_strategy_repository.dart index f0291928..9bc217d0 100644 --- a/lib/collab/convex_strategy_repository.dart +++ b/lib/collab/convex_strategy_repository.dart @@ -100,6 +100,24 @@ class ConvexStrategyRepository { return controller.stream; } + Future> fetchFolderPath( + String? folderPublicId) async { + if (folderPublicId == null) { + return const []; + } + + final response = await _client.query('folders:getPath', { + 'folderPublicId': folderPublicId, + }); + + return decodeConvexList(response) + .whereType() + .map((item) => CloudFolderSummary.fromJson( + Map.from(item), + )) + .toList(growable: false); + } + Stream watchStrategyHeader(String strategyPublicId) { final controller = StreamController.broadcast(); dynamic subscription; @@ -216,6 +234,9 @@ class ConvexStrategyRepository { required String publicId, required String name, String? parentFolderPublicId, + int? iconIndex, + String? colorKey, + int? customColorValue, }) async { await _client.mutation( name: 'folders:create', @@ -224,6 +245,9 @@ class ConvexStrategyRepository { 'name': name, if (parentFolderPublicId != null) 'parentFolderPublicId': parentFolderPublicId, + if (iconIndex != null) 'iconIndex': iconIndex, + if (colorKey != null) 'colorKey': colorKey, + if (customColorValue != null) 'customColorValue': customColorValue, }, ); } diff --git a/lib/providers/collab/remote_library_provider.dart b/lib/providers/collab/remote_library_provider.dart index 707051db..ac180cbf 100644 --- a/lib/providers/collab/remote_library_provider.dart +++ b/lib/providers/collab/remote_library_provider.dart @@ -45,6 +45,40 @@ final cloudStrategiesProvider = ); }); +final cloudFolderPathProvider = + FutureProvider.autoDispose>((ref) async { + final isCloud = ref.watch(isCloudCollabEnabledProvider); + final auth = ref.watch(authProvider); + if (!isCloud || auth.hasActiveAuthIncident) { + return const []; + } + + final folderId = ref.watch(folderProvider); + if (folderId == null) { + return const []; + } + + try { + return await ref + .watch(convexStrategyRepositoryProvider) + .fetchFolderPath(folderId); + } catch (error, stackTrace) { + if (_isInvalidFolderError(error)) { + ref.read(folderProvider.notifier).clearID(); + return const []; + } + if (isConvexUnauthenticatedError(error)) { + await ref.read(authProvider.notifier).reportConvexUnauthenticated( + source: 'remote_library:folder_path', + error: error, + stackTrace: stackTrace, + ); + return const []; + } + rethrow; + } +}); + Stream _recoverInvalidFolderScope({ required Ref ref, required String? folderId, diff --git a/lib/providers/folder_provider.dart b/lib/providers/folder_provider.dart index fcc9f3f8..a65123d8 100644 --- a/lib/providers/folder_provider.dart +++ b/lib/providers/folder_provider.dart @@ -104,6 +104,41 @@ class Folder extends HiveObject { Icons.psychology, ]; + static int folderIconIndex(IconData icon) { + final index = folderIcons.indexOf(icon); + return index >= 0 ? index : 0; + } + + static IconData iconFromIndex(int? index) { + if (index == null || index < 0 || index >= folderIcons.length) { + return folderIcons[0]; + } + return folderIcons[index]; + } + + static String colorKey(FolderColor color) => color.name; + + static FolderColor colorFromKey(String? key) { + if (key == null) { + return FolderColor.generic; + } + + for (final value in FolderColor.values) { + if (value.name == key) { + return value; + } + } + + return FolderColor.generic; + } + + static Color? customColorFromValue(int? value) { + if (value == null) { + return null; + } + return Color(value); + } + bool get isRoot => parentID == null; } @@ -133,6 +168,9 @@ class FolderProvider extends Notifier { publicId: newFolder.id, name: name, parentFolderPublicId: state, + iconIndex: Folder.folderIconIndex(icon), + colorKey: Folder.colorKey(color), + customColorValue: customColor?.toARGB32(), ); } catch (error, stackTrace) { await _maybeReportCloudUnauthenticated( @@ -144,7 +182,8 @@ class FolderProvider extends Notifier { return; } - await Hive.box(HiveBoxNames.foldersBox).put(newFolder.id, newFolder); + await Hive.box(HiveBoxNames.foldersBox) + .put(newFolder.id, newFolder); } void updateID(String? id) { @@ -191,9 +230,12 @@ class FolderProvider extends Notifier { void deleteFolder(String folderID) async { if (ref.read(isCloudCollabEnabledProvider)) { try { - await ConvexClient.instance.mutation(name: 'folders:delete', args: { - 'folderPublicId': folderID, - }); + await ConvexClient.instance.mutation( + name: 'folders:deleteRecursive', + args: { + 'folderPublicId': folderID, + }, + ); } catch (error, stackTrace) { await _maybeReportCloudUnauthenticated( source: 'folder:delete', @@ -230,7 +272,7 @@ class FolderProvider extends Notifier { } void editFolder({ - required Folder folder, + required String folderID, required String newName, required IconData newIcon, required FolderColor newColor, @@ -239,8 +281,13 @@ class FolderProvider extends Notifier { if (ref.read(isCloudCollabEnabledProvider)) { try { await ConvexClient.instance.mutation(name: 'folders:update', args: { - 'folderPublicId': folder.id, + 'folderPublicId': folderID, 'name': newName, + 'iconIndex': Folder.folderIconIndex(newIcon), + 'colorKey': Folder.colorKey(newColor), + if (newCustomColor != null) + 'customColorValue': newCustomColor.toARGB32(), + if (newCustomColor == null) 'clearCustomColorValue': true, }); } catch (error, stackTrace) { await _maybeReportCloudUnauthenticated( @@ -252,6 +299,10 @@ class FolderProvider extends Notifier { return; } + final folder = findFolderByID(folderID); + if (folder == null) { + return; + } folder.name = newName; folder.icon = newIcon; folder.customColor = newCustomColor; diff --git a/lib/providers/strategy_provider.dart b/lib/providers/strategy_provider.dart index 30571020..773a65ca 100644 --- a/lib/providers/strategy_provider.dart +++ b/lib/providers/strategy_provider.dart @@ -426,7 +426,95 @@ class StrategyProvider extends Notifier { (p) => p.publicId == pagePublicId, orElse: () => snapshot.pages.first, ); + final hydratedPage = _strategyPageFromRemote(snapshot, page); + final overridePalette = _decodeRemoteThemeOverride(snapshot); + activePageID = page.publicId; + + _skipQueueingDuringHydration = true; + try { + ref.read(actionProvider.notifier).clearAllActions(); + ref.read(agentProvider.notifier).fromHive(hydratedPage.agentData); + ref.read(abilityProvider.notifier).fromHive(hydratedPage.abilityData); + ref.read(drawingProvider.notifier).fromHive(hydratedPage.drawingData); + ref.read(textProvider.notifier).fromHive(hydratedPage.textData); + ref.read(placedImageProvider.notifier).fromHive(hydratedPage.imageData); + ref.read(utilityProvider.notifier).fromHive(hydratedPage.utilityData); + ref.read(lineUpProvider.notifier).fromHive(hydratedPage.lineUps); + + ref.read(mapProvider.notifier).fromHive( + _mapValueFromName(snapshot.header.mapData), + hydratedPage.isAttack, + ); + ref + .read(strategySettingsProvider.notifier) + .fromHive(hydratedPage.settings); + ref.read(strategyThemeProvider.notifier).fromStrategy( + profileId: snapshot.header.themeProfileId ?? + MapThemeProfilesProvider.immutableDefaultProfileId, + overridePalette: overridePalette, + ); + + state = state.copyWith( + id: snapshot.header.publicId, + stratName: snapshot.header.name, + activePageId: page.publicId, + isSaved: true, + storageDirectory: null, + ); + _lastHydratedRemoteStrategyId = snapshot.header.publicId; + _lastHydratedRemoteSequence = snapshot.header.sequence; + _lastHydratedRemotePageId = page.publicId; + } finally { + _skipQueueingDuringHydration = false; + } + } + + MapValue _mapValueFromName(String mapName) { + final match = + Maps.mapNames.entries.where((entry) => entry.value == mapName); + if (match.isEmpty) { + return MapValue.ascent; + } + return match.first.key; + } + + StrategySettings _decodeRemotePageSettings(RemotePage page) { + if (page.settings == null || page.settings!.isEmpty) { + return StrategySettings(); + } + + try { + return ref + .read(strategySettingsProvider.notifier) + .fromJson(page.settings!); + } catch (_) { + return StrategySettings(); + } + } + + MapThemePalette? _decodeRemoteThemeOverride(RemoteStrategySnapshot snapshot) { + if (snapshot.header.themeOverridePalette == null || + snapshot.header.themeOverridePalette!.isEmpty) { + return null; + } + + try { + final decoded = jsonDecode(snapshot.header.themeOverridePalette!); + if (decoded is Map) { + return MapThemePalette.fromJson(decoded); + } + if (decoded is Map) { + return MapThemePalette.fromJson(Map.from(decoded)); + } + } catch (_) {} + return null; + } + + StrategyPage _strategyPageFromRemote( + RemoteStrategySnapshot snapshot, + RemotePage page, + ) { final pageElements = snapshot.elementsByPage[page.publicId] ?? const []; final pageLineups = snapshot.lineupsByPage[page.publicId] ?? const []; @@ -483,68 +571,20 @@ class StrategyProvider extends Notifier { } catch (_) {} } - final mapEntry = Maps.mapNames.entries.firstWhere( - (entry) => entry.value == snapshot.header.mapData, - orElse: () => const MapEntry(MapValue.ascent, 'ascent'), + return StrategyPage( + id: page.publicId, + name: page.name, + drawingData: drawings, + agentData: agents, + abilityData: abilities, + textData: texts, + imageData: images, + utilityData: utilities, + sortIndex: page.sortIndex, + isAttack: page.isAttack, + settings: _decodeRemotePageSettings(page), + lineUps: lineUps, ); - - StrategySettings pageSettings = StrategySettings(); - if (page.settings != null && page.settings!.isNotEmpty) { - try { - pageSettings = ref - .read(strategySettingsProvider.notifier) - .fromJson(page.settings!); - } catch (_) {} - } - - MapThemePalette? overridePalette; - if (snapshot.header.themeOverridePalette != null && - snapshot.header.themeOverridePalette!.isNotEmpty) { - try { - final decoded = jsonDecode(snapshot.header.themeOverridePalette!); - if (decoded is Map) { - overridePalette = MapThemePalette.fromJson(decoded); - } else if (decoded is Map) { - overridePalette = - MapThemePalette.fromJson(Map.from(decoded)); - } - } catch (_) {} - } - - activePageID = page.publicId; - - _skipQueueingDuringHydration = true; - try { - ref.read(actionProvider.notifier).clearAllActions(); - ref.read(agentProvider.notifier).fromHive(agents); - ref.read(abilityProvider.notifier).fromHive(abilities); - ref.read(drawingProvider.notifier).fromHive(drawings); - ref.read(textProvider.notifier).fromHive(texts); - ref.read(placedImageProvider.notifier).fromHive(images); - ref.read(utilityProvider.notifier).fromHive(utilities); - ref.read(lineUpProvider.notifier).fromHive(lineUps); - - ref.read(mapProvider.notifier).fromHive(mapEntry.key, page.isAttack); - ref.read(strategySettingsProvider.notifier).fromHive(pageSettings); - ref.read(strategyThemeProvider.notifier).fromStrategy( - profileId: snapshot.header.themeProfileId ?? - MapThemeProfilesProvider.immutableDefaultProfileId, - overridePalette: overridePalette, - ); - - state = state.copyWith( - id: snapshot.header.publicId, - stratName: snapshot.header.name, - activePageId: page.publicId, - isSaved: true, - storageDirectory: null, - ); - _lastHydratedRemoteStrategyId = snapshot.header.publicId; - _lastHydratedRemoteSequence = snapshot.header.sequence; - _lastHydratedRemotePageId = page.publicId; - } finally { - _skipQueueingDuringHydration = false; - } } String? _resolveHydrationTargetPage(RemoteStrategySnapshot snapshot) { @@ -1608,6 +1648,141 @@ class StrategyProvider extends Notifier { await setActivePageAnimated(newPage.id); } + Future renamePage(String pageId, String newName) async { + final trimmedName = newName.trim(); + if (trimmedName.isEmpty) { + return; + } + + if (_isCloudMode()) { + try { + await ConvexClient.instance.mutation(name: "pages:rename", args: { + "strategyPublicId": state.id, + "pagePublicId": pageId, + "name": trimmedName, + }); + } catch (error, stackTrace) { + final handled = await _reportCloudUnauthenticated( + source: 'strategy:pages_rename', + error: error, + stackTrace: stackTrace, + ); + if (!handled) rethrow; + return; + } + await ref.read(remoteStrategySnapshotProvider.notifier).refresh(); + return; + } + + final box = Hive.box(HiveBoxNames.strategiesBox); + final strategy = box.get(state.id); + if (strategy == null) { + return; + } + + final updatedPages = [ + for (final page in strategy.pages) + if (page.id == pageId) page.copyWith(name: trimmedName) else page, + ]; + + await box.put( + strategy.id, + strategy.copyWith( + pages: updatedPages, + lastEdited: DateTime.now(), + ), + ); + } + + Future deletePage(String pageId) async { + if (_isCloudMode()) { + final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; + if (snapshot == null || snapshot.pages.length <= 1) { + return; + } + + final orderedPages = [...snapshot.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final deleteIndex = + orderedPages.indexWhere((page) => page.publicId == pageId); + if (deleteIndex < 0) { + return; + } + + final remainingPages = [ + for (final page in orderedPages) + if (page.publicId != pageId) page, + ]; + final nextActivePageId = + activePageID == pageId ? remainingPages.first.publicId : activePageID; + + try { + await ConvexClient.instance.mutation(name: "pages:delete", args: { + "strategyPublicId": state.id, + "pagePublicId": pageId, + }); + } catch (error, stackTrace) { + final handled = await _reportCloudUnauthenticated( + source: 'strategy:pages_delete', + error: error, + stackTrace: stackTrace, + ); + if (!handled) rethrow; + return; + } + + await ref.read(remoteStrategySnapshotProvider.notifier).refresh(); + final refreshed = ref.read(remoteStrategySnapshotProvider).valueOrNull; + if (refreshed == null || refreshed.pages.isEmpty) { + return; + } + + final targetPageId = nextActivePageId != null && + refreshed.pages.any((page) => page.publicId == nextActivePageId) + ? nextActivePageId + : refreshed.pages.first.publicId; + await _hydrateFromRemotePage(refreshed, targetPageId); + return; + } + + await _syncCurrentPageToHive(); + + final box = Hive.box(HiveBoxNames.strategiesBox); + final strategy = box.get(state.id); + if (strategy == null || strategy.pages.length <= 1) { + return; + } + + final orderedPages = [...strategy.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final remainingPages = [ + for (final page in orderedPages) + if (page.id != pageId) page, + ]; + if (remainingPages.isEmpty) { + return; + } + + final reindexedPages = [ + for (var i = 0; i < remainingPages.length; i++) + remainingPages[i].copyWith(sortIndex: i), + ]; + final nextActivePageId = + activePageID == pageId ? reindexedPages.first.id : activePageID; + + await box.put( + strategy.id, + strategy.copyWith( + pages: reindexedPages, + lastEdited: DateTime.now(), + ), + ); + + if (nextActivePageId != null && nextActivePageId != activePageID) { + await setActivePageAnimated(nextActivePageId); + } + } + Future loadFromHive(String id) async { if (_isCloudMode()) { await openStrategy(id); @@ -2116,6 +2291,18 @@ class StrategyProvider extends Notifier { return; } + await _zipStrategyData( + strategy: strategy, + saveDir: saveDir, + outputFilePath: outputFilePath, + ); + } + + Future _zipStrategyData({ + required StrategyData strategy, + Directory? saveDir, + String? outputFilePath, + }) async { final pages = strategy.pages.map((p) => p.toJson(strategy.id)).toList(); final pageJson = jsonEncode(pages); final exportPalette = _resolveThemePaletteForExport(strategy); @@ -2172,6 +2359,27 @@ class StrategyProvider extends Notifier { await zipEncoder.close(); } + StrategyData _strategyDataFromRemoteSnapshot( + RemoteStrategySnapshot snapshot) { + final orderedPages = [...snapshot.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + + return StrategyData( + id: snapshot.header.publicId, + name: snapshot.header.name, + mapData: _mapValueFromName(snapshot.header.mapData), + versionNumber: Settings.versionNumber, + lastEdited: snapshot.header.updatedAt, + createdAt: snapshot.header.createdAt, + folderID: null, + themeProfileId: snapshot.header.themeProfileId, + themeOverridePalette: _decodeRemoteThemeOverride(snapshot), + pages: orderedPages + .map((page) => _strategyPageFromRemote(snapshot, page)) + .toList(growable: false), + ); + } + Future exportFile(String id) async { await forceSaveNow(id); @@ -2186,6 +2394,42 @@ class StrategyProvider extends Notifier { await zipStrategy(id: id, outputFilePath: outputFile); } + Future exportStrategy(String strategyID) async { + if (kIsWeb) { + Settings.showToast( + message: 'This feature is only supported in the Windows version.', + backgroundColor: Settings.tacticalVioletTheme.destructive, + ); + return; + } + + if (_isCloudMode()) { + final snapshot = await ref + .read(convexStrategyRepositoryProvider) + .fetchSnapshot(strategyID); + final strategy = _strategyDataFromRemoteSnapshot(snapshot); + final outputFile = await FilePicker.platform.saveFile( + type: FileType.custom, + dialogTitle: 'Please select an output file:', + fileName: "${sanitizeFileName(strategy.name)}.ica", + allowedExtensions: [".ica"], + ); + + if (outputFile == null) { + return; + } + + await _zipStrategyData( + strategy: strategy, + outputFilePath: outputFile, + ); + return; + } + + await loadFromHive(strategyID); + await exportFile(strategyID); + } + Future renameStrategy(String strategyID, String newName) async { if (_isCloudMode()) { try { diff --git a/lib/widgets/cloud_library_widgets.dart b/lib/widgets/cloud_library_widgets.dart deleted file mode 100644 index 2d5e8c9a..00000000 --- a/lib/widgets/cloud_library_widgets.dart +++ /dev/null @@ -1,380 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:icarus/collab/collab_models.dart'; -import 'package:icarus/const/settings.dart'; -import 'package:icarus/providers/folder_provider.dart'; -import 'package:icarus/providers/strategy_provider.dart'; -import 'package:icarus/strategy_view.dart'; -import 'package:icarus/widgets/strategy_tile/strategy_tile_sections.dart'; -import 'package:shadcn_ui/shadcn_ui.dart'; - -class CloudFolderPill extends ConsumerStatefulWidget { - const CloudFolderPill({ - super.key, - required this.folder, - }); - - final CloudFolderSummary folder; - - @override - ConsumerState createState() => _CloudFolderPillState(); -} - -class _CloudFolderPillState extends ConsumerState - with SingleTickerProviderStateMixin { - late final AnimationController _animationController; - late final Animation _scaleAnimation; - bool _isHovered = false; - - @override - void initState() { - super.initState(); - _animationController = AnimationController( - duration: const Duration(milliseconds: 150), - vsync: this, - ); - _scaleAnimation = Tween( - begin: 1.0, - end: 1.03, - ).animate(CurvedAnimation( - parent: _animationController, - curve: Curves.easeOut, - )); - } - - @override - void dispose() { - _animationController.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final pillColor = Color.lerp( - Settings.tacticalVioletTheme.card, - Settings.tacticalVioletTheme.primary, - 0.55, - )!; - - return MouseRegion( - cursor: SystemMouseCursors.click, - onEnter: (_) { - setState(() => _isHovered = true); - _animationController.forward(); - }, - onExit: (_) { - setState(() => _isHovered = false); - _animationController.reverse(); - }, - child: GestureDetector( - onTap: () => - ref.read(folderProvider.notifier).updateID(widget.folder.publicId), - child: AnimatedBuilder( - animation: _scaleAnimation, - builder: (context, child) { - return Transform.scale( - scale: _scaleAnimation.value, - child: AnimatedContainer( - duration: const Duration(milliseconds: 150), - height: 44, - padding: const EdgeInsets.symmetric(horizontal: 14), - decoration: BoxDecoration( - color: pillColor, - borderRadius: BorderRadius.circular(22), - border: Border.all( - color: _isHovered - ? Colors.white.withValues(alpha: 0.55) - : Colors.white.withValues(alpha: 0.18), - ), - boxShadow: [ - BoxShadow( - color: pillColor.withValues(alpha: 0.35), - blurRadius: _isHovered ? 10 : 6, - offset: const Offset(0, 3), - ), - ], - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon( - Icons.folder_rounded, - color: Colors.white, - size: 20, - ), - const SizedBox(width: 10), - ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 160), - child: Text( - widget.folder.name, - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600, - ), - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ), - ); - }, - ), - ), - ); - } -} - -class CloudStrategyTile extends ConsumerStatefulWidget { - const CloudStrategyTile({ - super.key, - required this.strategy, - }); - - final CloudStrategySummary strategy; - - @override - ConsumerState createState() => _CloudStrategyTileState(); -} - -class _CloudStrategyTileState extends ConsumerState { - Color _highlightColor = Settings.tacticalVioletTheme.border; - bool _isLoading = false; - - @override - Widget build(BuildContext context) { - final data = _CloudStrategyTileViewData.fromSummary(widget.strategy); - - return MouseRegion( - cursor: SystemMouseCursors.click, - onEnter: (_) => - setState(() => _highlightColor = Settings.tacticalVioletTheme.ring), - onExit: (_) => - setState(() => _highlightColor = Settings.tacticalVioletTheme.border), - child: AbsorbPointer( - absorbing: _isLoading, - child: GestureDetector( - onTap: () => _openStrategy(context), - child: Stack( - children: [ - AnimatedContainer( - duration: const Duration(milliseconds: 100), - decoration: BoxDecoration( - color: ShadTheme.of(context).colorScheme.card, - borderRadius: BorderRadius.circular(16), - border: Border.all(color: _highlightColor, width: 2), - ), - padding: const EdgeInsets.all(8), - child: Column( - children: [ - Expanded( - child: - StrategyTileThumbnail(assetPath: data.thumbnailAsset), - ), - const SizedBox(height: 10), - Expanded(child: _CloudStrategyTileDetails(data: data)), - ], - ), - ), - const Align( - alignment: Alignment.topRight, - child: Padding( - padding: EdgeInsets.all(16), - child: Icon( - Icons.cloud_done_outlined, - color: Colors.white70, - size: 22, - ), - ), - ), - ], - ), - ), - ), - ); - } - - Future _openStrategy(BuildContext context) async { - if (_isLoading) { - return; - } - - setState(() => _isLoading = true); - _showLoadingOverlay(); - var dismissedOverlay = false; - - try { - await ref - .read(strategyProvider.notifier) - .openStrategy(widget.strategy.publicId); - if (!context.mounted) { - return; - } - Navigator.pop(context); - dismissedOverlay = true; - await Navigator.push( - context, - PageRouteBuilder( - transitionDuration: const Duration(milliseconds: 200), - reverseTransitionDuration: const Duration(milliseconds: 200), - pageBuilder: (context, animation, _) => const StrategyView(), - transitionsBuilder: (context, animation, _, child) { - return FadeTransition( - opacity: animation, - child: ScaleTransition( - scale: Tween(begin: 0.9, end: 1.0) - .chain(CurveTween(curve: Curves.easeOut)) - .animate(animation), - child: child, - ), - ); - }, - ), - ); - } finally { - if (!dismissedOverlay && context.mounted) { - Navigator.pop(context); - } - if (mounted) { - setState(() => _isLoading = false); - } - } - } - - void _showLoadingOverlay() { - showDialog( - context: context, - barrierDismissible: false, - builder: (_) => const Center(child: CircularProgressIndicator()), - ); - } -} - -class _CloudStrategyTileViewData { - const _CloudStrategyTileViewData({ - required this.name, - required this.mapName, - required this.thumbnailAsset, - required this.updatedLabel, - }); - - factory _CloudStrategyTileViewData.fromSummary(CloudStrategySummary summary) { - final mapName = summary.mapData.trim(); - final normalizedMap = mapName.isEmpty - ? 'unknown' - : mapName.toLowerCase().replaceAll(' ', '_'); - return _CloudStrategyTileViewData( - name: summary.name, - mapName: mapName.isEmpty - ? 'Unknown' - : mapName[0].toUpperCase() + mapName.substring(1), - thumbnailAsset: 'assets/maps/thumbnails/${normalizedMap}_thumbnail.webp', - updatedLabel: _timeAgo(summary.updatedAt), - ); - } - - final String name; - final String mapName; - final String thumbnailAsset; - final String updatedLabel; - - static String _timeAgo(DateTime date) { - final difference = DateTime.now().difference(date); - if (difference.inMinutes < 1) return 'Just now'; - if (difference.inMinutes < 60) { - final minutes = difference.inMinutes; - return '$minutes min${minutes == 1 ? '' : 's'} ago'; - } - if (difference.inHours < 24) { - final hours = difference.inHours; - return '$hours hour${hours == 1 ? '' : 's'} ago'; - } - if (difference.inDays < 30) { - final days = difference.inDays; - return '$days day${days == 1 ? '' : 's'} ago'; - } - final months = (difference.inDays / 30).floor(); - return '$months month${months == 1 ? '' : 's'} ago'; - } -} - -class _CloudStrategyTileDetails extends StatelessWidget { - const _CloudStrategyTileDetails({ - required this.data, - }); - - final _CloudStrategyTileViewData data; - - @override - Widget build(BuildContext context) { - return Container( - decoration: BoxDecoration( - color: ShadTheme.of(context).colorScheme.card, - borderRadius: BorderRadius.circular(16), - border: Border.all(color: Settings.tacticalVioletTheme.border), - boxShadow: const [Settings.cardForegroundBackdrop], - ), - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 130), - child: Text( - data.name, - style: const TextStyle( - fontWeight: FontWeight.w500, - overflow: TextOverflow.ellipsis, - ), - ), - ), - const SizedBox(height: 5), - Text(data.mapName), - const SizedBox(height: 8), - Container( - padding: - const EdgeInsets.symmetric(horizontal: 10, vertical: 4), - decoration: BoxDecoration( - color: Settings.tacticalVioletTheme.primary - .withValues(alpha: 0.22), - borderRadius: BorderRadius.circular(999), - border: Border.all( - color: Settings.tacticalVioletTheme.primary - .withValues(alpha: 0.5), - ), - ), - child: const Text( - 'Online', - style: TextStyle( - color: Colors.white, - fontSize: 12, - fontWeight: FontWeight.w600, - ), - ), - ), - ], - ), - ), - Column( - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - const Text( - 'Synced', - style: TextStyle(color: Colors.deepPurpleAccent), - ), - const SizedBox(height: 5), - Text(data.updatedLabel, overflow: TextOverflow.ellipsis), - ], - ), - ], - ), - ); - } -} diff --git a/lib/widgets/current_path_bar.dart b/lib/widgets/current_path_bar.dart index 1ba667f9..2dfd363a 100644 --- a/lib/widgets/current_path_bar.dart +++ b/lib/widgets/current_path_bar.dart @@ -1,9 +1,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/settings.dart'; +import 'package:icarus/providers/collab/cloud_collab_provider.dart'; +import 'package:icarus/providers/collab/remote_library_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; -import 'package:icarus/widgets/folder_navigator.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; class CurrentPathBar extends ConsumerWidget { @@ -11,87 +13,107 @@ class CurrentPathBar extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + final isCloud = ref.watch(isCloudCollabEnabledProvider); final currentFolderId = ref.watch(folderProvider); - final currentFolder = currentFolderId != null - ? ref.read(folderProvider.notifier).findFolderByID(currentFolderId) - : null; - final pathIds = - ref.read(folderProvider.notifier).getFullPathIDs(currentFolder); + final pathItems = [ + const LibraryPathItemData(id: null, name: 'Home'), + ]; - return Container( - padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 8), - // ignore: prefer_const_constructors - child: Row( - children: [ - Expanded( - child: ShadBreadcrumb( - lastItemTextColor: Settings.tacticalVioletTheme.foreground, - textStyle: ShadTheme.of(context).textTheme.lead, - children: [ + if (isCloud) { + final cloudPath = + ref.watch(cloudFolderPathProvider).valueOrNull ?? const []; + pathItems.addAll( + cloudPath.map( + (folder) => LibraryPathItemData( + id: folder.publicId, + name: folder.name, + ), + ), + ); + } else { + final currentFolder = currentFolderId != null + ? ref.read(folderProvider.notifier).findFolderByID(currentFolderId) + : null; + final pathIds = + ref.read(folderProvider.notifier).getFullPathIDs(currentFolder); + + for (final pathId in pathIds) { + final folder = ref.read(folderProvider.notifier).findFolderByID(pathId); + if (folder == null) { + continue; + } + pathItems.add( + LibraryPathItemData( + id: folder.id, + name: folder.name, + ), + ); + } + } + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + Expanded( + child: ShadBreadcrumb( + lastItemTextColor: Settings.tacticalVioletTheme.foreground, + textStyle: ShadTheme.of(context).textTheme.lead, + children: [ + for (var i = 0; i < pathItems.length; i++) FolderTab( - folder: null, // Represents root - isActive: currentFolder == null, + item: pathItems[i], + isActive: i == pathItems.length - 1, ), - - // Path folders - for (int i = 0; i < pathIds.length; i++) ...[ - FolderTab( - folder: ref - .read(folderProvider.notifier) - .findFolderByID(pathIds[i]), - isActive: i == pathIds.length - 1, - ), - ], - ], - ), + ], ), - ], - )); + ), + ], + ), + ); } } class FolderTab extends ConsumerWidget { const FolderTab({ super.key, - required this.folder, + required this.item, this.isActive = false, }); - final Folder? folder; // null for root + final LibraryPathItemData item; final bool isActive; @override Widget build(BuildContext context, WidgetRef ref) { - final displayName = folder?.name ?? "Home"; - return ShadBreadcrumbLink( textStyle: ShadTheme.of(context).textTheme.lead, normalColor: isActive ? Settings.tacticalVioletTheme.foreground : null, - child: DragTarget( + child: DragTarget( builder: (context, candidateData, rejectedData) { - return Container( + return Padding( padding: const EdgeInsets.symmetric(vertical: 4), - child: Text(displayName), + child: Text(item.name), ); }, onAcceptWithDetails: (details) { - final item = details.data; - if (item is StrategyItem) { - // Move strategy to this folder + final dragItem = details.data; + if (dragItem is StrategyDragItem) { ref.read(strategyProvider.notifier).moveToFolder( - strategyID: item.strategy.id, parentID: folder?.id); - } else if (item is FolderItem) { - // Move folder to this folder - - ref - .read(folderProvider.notifier) - .moveToFolder(folderID: item.folder.id, parentID: folder?.id); + strategyID: dragItem.id, + parentID: item.id, + ); + } else if (dragItem is FolderDragItem) { + ref.read(folderProvider.notifier).moveToFolder( + folderID: dragItem.id, + parentID: item.id, + ); } }, ), onPressed: () { - ref.read(folderProvider.notifier).updateID(folder?.id); + ref.read(folderProvider.notifier).updateID(item.id); }, ); } diff --git a/lib/widgets/folder_content.dart b/lib/widgets/folder_content.dart deleted file mode 100644 index d1ecc4ae..00000000 --- a/lib/widgets/folder_content.dart +++ /dev/null @@ -1,450 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:hive_ce_flutter/adapters.dart'; -import 'package:icarus/collab/collab_models.dart'; -import 'package:icarus/const/hive_boxes.dart'; -import 'package:icarus/const/maps.dart'; -import 'package:icarus/const/settings.dart'; -import 'package:icarus/providers/collab/cloud_collab_provider.dart'; -import 'package:icarus/providers/collab/remote_library_provider.dart'; -import 'package:icarus/providers/folder_provider.dart'; -import 'package:icarus/providers/strategy_filter_provider.dart'; -import 'package:icarus/providers/strategy_provider.dart'; -import 'package:icarus/strategy_view.dart'; -import 'package:icarus/widgets/strategy_tile/strategy_tile.dart'; -import 'package:icarus/widgets/custom_search_field.dart'; -import 'package:icarus/widgets/ica_drop_target.dart'; -import 'package:icarus/widgets/dot_painter.dart'; -import 'package:icarus/widgets/folder_pill.dart'; -import 'package:shadcn_ui/shadcn_ui.dart'; -// ... your existing imports - -class FolderContent extends ConsumerWidget { - FolderContent({super.key, this.folder}); - - final Folder? folder; // null for root - final strategiesListenable = - Provider>>((ref) { - return Hive.box(HiveBoxNames.strategiesBox).listenable(); - }); - - final foldersListenable = Provider>>((ref) { - return Hive.box(HiveBoxNames.foldersBox).listenable(); - }); - - final TextEditingController searchController = TextEditingController(); - - @override - Widget build(BuildContext context, WidgetRef ref) { - // Move all your existing grid logic here from FolderView - // Filter by folder?.id instead of folder.id - final strategiesBoxListenable = ref.watch(strategiesListenable); - final isCloud = ref.watch(isCloudCollabEnabledProvider); - - if (isCloud) { - final foldersAsync = ref.watch(cloudFoldersProvider); - final strategiesAsync = ref.watch(cloudStrategiesProvider); - final search = - ref.watch(strategySearchQueryProvider).trim().toLowerCase(); - final filter = ref.watch(strategyFilterProvider); - - final folders = foldersAsync.valueOrNull ?? const []; - var strategies = strategiesAsync.valueOrNull ?? const []; - - if (search.isNotEmpty) { - strategies = strategies - .where((strategy) => strategy.name.toLowerCase().contains(search)) - .toList(growable: false); - } - - Comparator sortByComparator = - switch (filter.sortBy) { - SortBy.alphabetical => - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), - SortBy.dateCreated => (a, b) => a.createdAt.compareTo(b.createdAt), - SortBy.dateUpdated => (a, b) => a.updatedAt.compareTo(b.updatedAt), - }; - final direction = - filter.sortOrder == SortOrder.ascending ? 1 : -1; - strategies = [...strategies]..sort((a, b) => direction * sortByComparator(a, b)); - - return Stack( - children: [ - const Positioned.fill( - child: Padding( - padding: EdgeInsets.all(4.0), - child: DotGrid(), - ), - ), - Positioned.fill( - child: Column( - children: [ - Padding( - padding: const EdgeInsets.only(top: 4.0, left: 16, right: 16), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - spacing: 8, - children: [ - ShadSelect( - decoration: ShadDecoration( - color: Settings.tacticalVioletTheme.card, - shadows: const [Settings.cardForegroundBackdrop], - ), - initialValue: ref.watch(strategyFilterProvider).sortBy, - selectedOptionBuilder: (context, value) => - Text(StrategyFilterProvider.sortByLabels[value]!), - options: [ - for (final sb in SortBy.values) - ShadOption( - value: sb, - child: Text(StrategyFilterProvider.sortByLabels[sb]!), - ), - ], - onChanged: (value) { - ref.read(strategyFilterProvider.notifier).setSortBy(value!); - }, - ), - ShadSelect( - decoration: ShadDecoration( - color: Settings.tacticalVioletTheme.card, - shadows: const [Settings.cardForegroundBackdrop], - ), - initialValue: ref.watch(strategyFilterProvider).sortOrder, - selectedOptionBuilder: (context, value) => - Text(StrategyFilterProvider.sortOrderLabels[value]!), - options: [ - for (final so in SortOrder.values) - ShadOption( - value: so, - child: Text(StrategyFilterProvider.sortOrderLabels[so]!), - ), - ], - onChanged: (value) { - ref - .read(strategyFilterProvider.notifier) - .setSortOrder(value!); - }, - ), - ], - ), - SizedBox( - height: 40, - child: SearchTextField( - controller: searchController, - collapsedWidth: 40, - expandedWidth: 250, - compact: true, - onChanged: (value) {}, - ), - ), - ], - ), - ), - Expanded( - child: IcaDropTarget( - child: ListView( - padding: const EdgeInsets.all(16), - children: [ - if (folders.isNotEmpty) - Wrap( - spacing: 10, - runSpacing: 10, - children: [ - for (final cloudFolder in folders) - ActionChip( - label: Text(cloudFolder.name), - onPressed: () { - ref - .read(folderProvider.notifier) - .updateID(cloudFolder.publicId); - }, - ), - ], - ), - if (folders.isNotEmpty) const SizedBox(height: 16), - if (strategies.isEmpty) - const Padding( - padding: EdgeInsets.only(top: 24), - child: Center( - child: Text('No cloud strategies in this folder'), - ), - ), - for (final strategy in strategies) - Card( - color: Settings.tacticalVioletTheme.card, - margin: const EdgeInsets.only(bottom: 12), - child: ListTile( - title: Text(strategy.name), - subtitle: Text( - '${strategy.mapData} • Updated ${strategy.updatedAt.toLocal()}', - ), - trailing: const Icon(Icons.chevron_right), - onTap: () async { - await ref - .read(strategyProvider.notifier) - .openStrategy(strategy.publicId); - if (!context.mounted) return; - await Navigator.push( - context, - MaterialPageRoute( - builder: (_) => const StrategyView(), - ), - ); - }, - ), - ), - ], - ), - ), - ), - ], - ), - ), - ], - ); - } - - return Stack( - children: [ - const Positioned.fill( - child: Padding( - padding: EdgeInsets.all(4.0), - child: DotGrid(), - ), - ), - Positioned.fill( - child: Column( - children: [ - Padding( - padding: const EdgeInsets.only(top: 4.0, left: 16, right: 16), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - spacing: 8, - children: [ - ShadSelect( - decoration: ShadDecoration( - color: Settings.tacticalVioletTheme.card, - shadows: const [Settings.cardForegroundBackdrop], - ), - initialValue: - ref.watch(strategyFilterProvider).sortBy, - selectedOptionBuilder: (context, value) => - Text(StrategyFilterProvider.sortByLabels[value]!), - options: [ - for (final sb in SortBy.values) - ShadOption( - value: sb, - child: Text( - StrategyFilterProvider.sortByLabels[sb]!), - ), - ], - onChanged: (value) { - ref - .read(strategyFilterProvider.notifier) - .setSortBy(value!); - }, - ), - ShadSelect( - decoration: ShadDecoration( - color: Settings.tacticalVioletTheme.card, - shadows: const [Settings.cardForegroundBackdrop], - ), - initialValue: - ref.watch(strategyFilterProvider).sortOrder, - selectedOptionBuilder: (context, value) => Text( - StrategyFilterProvider.sortOrderLabels[value]!), - options: [ - for (final so in SortOrder.values) - ShadOption( - value: so, - child: Text(StrategyFilterProvider - .sortOrderLabels[so]!), - ), - ], - onChanged: (value) { - ref - .read(strategyFilterProvider.notifier) - .setSortOrder(value!); - }, - ), - ], - ), - SizedBox( - height: 40, - child: SearchTextField( - controller: searchController, - collapsedWidth: 40, - expandedWidth: 250, - compact: true, - onChanged: (value) {}, - ), - ), - ], - ), - ), - Expanded( - child: ValueListenableBuilder>( - valueListenable: strategiesBoxListenable, - builder: (context, strategyBox, _) { - final foldersBoxListenable = ref.watch(foldersListenable); - return ValueListenableBuilder>( - valueListenable: foldersBoxListenable, - builder: (context, folderBox, _) { - final folders = folderBox.values.toList(); - - final strategies = strategyBox.values.toList(); - - final search = ref - .watch(strategySearchQueryProvider) - .trim() - .toLowerCase(); - // Filter strategies and folders by the current folder - strategies.removeWhere( - (strategy) => strategy.folderID != folder?.id); - folders.removeWhere( - (listFolder) => listFolder.parentID != folder?.id); - - if (search.isNotEmpty) { - strategies.retainWhere( - (strategy) => - strategy.name.toLowerCase().contains(search), - ); - folders.retainWhere( - (listFolder) => - listFolder.name.toLowerCase().contains(search), - ); - } - final filter = ref.watch(strategyFilterProvider); - - // Pick the comparator once based on sortBy - Comparator sortByComparator = - switch (filter.sortBy) { - SortBy.alphabetical => (a, b) => a.name - .toLowerCase() - .compareTo(b.name.toLowerCase()), - SortBy.dateCreated => (a, b) => - a.createdAt.compareTo(b.createdAt), - SortBy.dateUpdated => (a, b) => - a.lastEdited.compareTo(b.lastEdited), - }; - - final direction = - filter.sortOrder == SortOrder.ascending ? 1 : -1; - - strategies.sort( - (a, b) => direction * sortByComparator(a, b), - ); - folders.sort( - (a, b) => a.dateCreated.compareTo(b.dateCreated)); - - // Check if both folders and strategies are empty - if (folders.isEmpty && strategies.isEmpty) { - return const IcaDropTarget( - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('No strategies available'), - Text( - "Create a new strategy or drop an .ica file") - ], - ), - ), - ); - } - - return IcaDropTarget( - child: LayoutBuilder(builder: (context, constraints) { - // Calculate how many columns can fit with minimum width - const double minTileWidth = - 250; // Your minimum width - const double spacing = 20; - const double padding = 32; // 16 * 2 - - int crossAxisCount = - ((constraints.maxWidth - padding + spacing) / - (minTileWidth + spacing)) - .floor(); - crossAxisCount = crossAxisCount - .clamp(1, double.infinity) - .toInt(); - - return CustomScrollView( - slivers: [ - // Folder pills section (wrap row) - if (folders.isNotEmpty) - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.fromLTRB( - 16, 16, 16, 8), - child: Wrap( - spacing: 10, - runSpacing: 10, - children: folders - .map((f) => FolderPill(folder: f)) - .toList(), - ), - ), - ), - - // Strategies grid - if (strategies.isNotEmpty) - SliverPadding( - padding: const EdgeInsets.all(16), - sliver: SliverGrid( - gridDelegate: - SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: crossAxisCount, - mainAxisExtent: 250, - crossAxisSpacing: 20, - mainAxisSpacing: 20, - ), - delegate: SliverChildBuilderDelegate( - (context, index) { - return StrategyTile( - strategyData: strategies[index]); - }, - childCount: strategies.length, - ), - ), - ) - else if (folders.isNotEmpty) - // Show placeholder when only folders exist - const SliverFillRemaining( - hasScrollBody: false, - child: Center( - child: Padding( - padding: EdgeInsets.only(top: 48), - child: Text( - 'No strategies in this folder', - style: TextStyle( - color: Colors.grey, - ), - ), - ), - ), - ), - ], - ); - }), - ); - }, - ); - }, - ), - ), - ], - ), - ), - ], - ); - } -} - - - diff --git a/lib/widgets/folder_edit_dialog.dart b/lib/widgets/folder_edit_dialog.dart index e982e8e2..e54d24ef 100644 --- a/lib/widgets/folder_edit_dialog.dart +++ b/lib/widgets/folder_edit_dialog.dart @@ -7,6 +7,7 @@ import 'package:icarus/widgets/color_picker_button.dart'; import 'package:icarus/widgets/custom_text_field.dart'; import 'package:icarus/widgets/dot_painter.dart'; import 'package:icarus/widgets/folder_pill.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:icarus/widgets/sidebar_widgets/color_buttons.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; @@ -14,8 +15,18 @@ class FolderEditDialog extends ConsumerStatefulWidget { const FolderEditDialog({ super.key, this.folder, + this.folderId, + this.initialName, + this.initialIcon, + this.initialColor, + this.initialCustomColor, }); final Folder? folder; + final String? folderId; + final String? initialName; + final IconData? initialIcon; + final FolderColor? initialColor; + final Color? initialCustomColor; @override ConsumerState createState() => _FolderEditDialogState(); @@ -37,12 +48,13 @@ class _FolderEditDialogState extends ConsumerState { void initState() { super.initState(); // Listen to text changes and rebuild - _selectedColor = widget.folder?.color ?? FolderColor.generic; - if (widget.folder != null) { - _folderNameController.text = widget.folder!.name; - _selectedIcon = widget.folder!.icon; - _customColor = widget.folder!.customColor; - } + _selectedColor = + widget.folder?.color ?? widget.initialColor ?? FolderColor.generic; + _folderNameController.text = + widget.folder?.name ?? widget.initialName ?? ''; + _selectedIcon = + widget.folder?.icon ?? widget.initialIcon ?? Folder.folderIcons[0]; + _customColor = widget.folder?.customColor ?? widget.initialCustomColor; _folderNameController.addListener(() { setState(() {}); }); @@ -66,9 +78,10 @@ class _FolderEditDialogState extends ConsumerState { child: ShadButton( leading: const Icon(Icons.check), onPressed: () async { - if (widget.folder != null) { + final editFolderId = widget.folder?.id ?? widget.folderId; + if (editFolderId != null) { ref.read(folderProvider.notifier).editFolder( - folder: widget.folder!, + folderID: editFolderId, newName: _folderNameController.text.isEmpty ? "New Folder" : _folderNameController.text, @@ -128,15 +141,16 @@ class _FolderEditDialogState extends ConsumerState { child: Material( color: Colors.transparent, child: FolderPill( - folder: Folder( - icon: _selectedIcon, + data: LibraryFolderItemData( + id: 'preview', name: _folderNameController.text, - id: "null", - dateCreated: DateTime.now(), - color: _selectedColor, - customColor: _customColor, + icon: _selectedIcon, + backgroundColor: _customColor ?? + Folder.folderColorMap[_selectedColor] ?? + Colors.grey, ), isDemo: true, + enableDragAndDrop: false, ), ), ), diff --git a/lib/widgets/folder_navigator.dart b/lib/widgets/folder_navigator.dart index 307ba99f..4b4c5639 100644 --- a/lib/widgets/folder_navigator.dart +++ b/lib/widgets/folder_navigator.dart @@ -1,40 +1,41 @@ import 'dart:async'; -import 'dart:developer'; import 'dart:io'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:hive_ce_flutter/adapters.dart'; +import 'package:icarus/collab/collab_models.dart'; import 'package:icarus/const/coordinate_system.dart'; +import 'package:icarus/const/hive_boxes.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/const/update_checker.dart'; import 'package:icarus/main.dart'; -import 'package:icarus/providers/collab/cloud_migration_provider.dart'; import 'package:icarus/providers/auth_provider.dart'; +import 'package:icarus/providers/collab/cloud_collab_provider.dart'; +import 'package:icarus/providers/collab/cloud_migration_provider.dart'; +import 'package:icarus/providers/collab/remote_library_provider.dart'; import 'package:icarus/providers/folder_provider.dart'; +import 'package:icarus/providers/strategy_filter_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/providers/update_status_provider.dart'; import 'package:icarus/strategy_view.dart'; import 'package:icarus/widgets/current_path_bar.dart'; +import 'package:icarus/widgets/custom_search_field.dart'; import 'package:icarus/widgets/demo_dialog.dart'; import 'package:icarus/widgets/demo_tag.dart'; +import 'package:icarus/widgets/dialogs/auth/auth_dialog.dart'; +import 'package:icarus/widgets/dialogs/confirm_alert_dialog.dart'; import 'package:icarus/widgets/dialogs/strategy/create_strategy_dialog.dart'; import 'package:icarus/widgets/dialogs/web_view_dialog.dart'; -import 'package:icarus/widgets/dialogs/auth/auth_dialog.dart'; -import 'package:icarus/widgets/folder_edit_dialog.dart'; -import 'package:shadcn_ui/shadcn_ui.dart'; -import 'package:hive_ce_flutter/adapters.dart'; -import 'package:icarus/collab/collab_models.dart'; -import 'package:icarus/const/hive_boxes.dart'; -import 'package:icarus/providers/collab/cloud_collab_provider.dart'; -import 'package:icarus/providers/collab/remote_library_provider.dart'; -import 'package:icarus/providers/strategy_filter_provider.dart'; -import 'package:icarus/widgets/custom_search_field.dart'; -import 'package:icarus/widgets/cloud_library_widgets.dart'; import 'package:icarus/widgets/dot_painter.dart'; +import 'package:icarus/widgets/folder_edit_dialog.dart'; import 'package:icarus/widgets/folder_pill.dart'; import 'package:icarus/widgets/ica_drop_target.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:icarus/widgets/strategy_tile/strategy_tile.dart'; +import 'package:icarus/widgets/strategy_tile/strategy_tile_sections.dart'; +import 'package:shadcn_ui/shadcn_ui.dart'; class FolderNavigator extends ConsumerStatefulWidget { const FolderNavigator({super.key}); @@ -52,39 +53,34 @@ class _FolderNavigatorState extends ConsumerState { void initState() { super.initState(); - // Show the demo warning only once after the first frame on web. WidgetsBinding.instance.addPostFrameCallback((_) { unawaited(ref.read(cloudMigrationProvider.notifier).maybeMigrate()); - if (!_warnedOnce) { - _warnedOnce = true; - - log("Warning webview"); - _warnWebView(); - - _warnDemo(); + if (_warnedOnce) { + return; } + _warnedOnce = true; + _warnWebView(); + _warnDemo(); }); } void _warnWebView() async { - if (kIsWeb) return; - if (!Platform.isWindows) return; - if (isWebViewInitialized) return; + if (kIsWeb || !Platform.isWindows || isWebViewInitialized) { + return; + } await showShadDialog( context: context, - builder: (context) { - return const WebViewDialog(); - }, + builder: (_) => const WebViewDialog(), ); } void _warnDemo() async { - if (!kIsWeb) return; + if (!kIsWeb) { + return; + } await showShadDialog( context: context, - builder: (context) { - return const DemoDialog(); - }, + builder: (_) => const DemoDialog(), ); } @@ -98,7 +94,9 @@ class _FolderNavigatorState extends ConsumerState { } _hasPromptedUpdateDialog = true; WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) return; + if (!mounted) { + return; + } UpdateChecker.showUpdateDialog(context, result); }); }); @@ -107,27 +105,22 @@ class _FolderNavigatorState extends ConsumerState { final double height = MediaQuery.sizeOf(context).height - 90; final Size playAreaSize = Size(height * (16 / 9), height); CoordinateSystem(playAreaSize: playAreaSize); - final currentFolderId = ref.watch(folderProvider); - final currentFolder = currentFolderId != null - ? ref.read(folderProvider.notifier).findFolderByID(currentFolderId) - : null; final authState = ref.watch(authProvider); - Future navigateWithLoading( - BuildContext context, String strategyId) async { - // Show loading overlay - // showLoadingOverlay(context); + Future navigateWithLoading( + BuildContext context, + String strategyId, + ) async { try { await ref.read(strategyProvider.notifier).openStrategy(strategyId); - - if (!context.mounted) return; - + if (!context.mounted) { + return; + } Navigator.push( context, PageRouteBuilder( transitionDuration: const Duration(milliseconds: 200), - reverseTransitionDuration: - const Duration(milliseconds: 200), // pop duration + reverseTransitionDuration: const Duration(milliseconds: 200), pageBuilder: (context, animation, secondaryAnimation) => const StrategyView(), transitionsBuilder: @@ -144,22 +137,19 @@ class _FolderNavigatorState extends ConsumerState { }, ), ); - } catch (e) { - // Handle errors - // Show error message - } + } catch (_) {} } void showCreateDialog() async { final String? strategyId = await showDialog( context: context, - builder: (context) { - return const CreateStrategyDialog(); - }, + builder: (_) => const CreateStrategyDialog(), ); if (strategyId != null) { - if (!context.mounted) return; + if (!context.mounted) { + return; + } await navigateWithLoading(context, strategyId); } } @@ -169,11 +159,10 @@ class _FolderNavigatorState extends ConsumerState { title: const CurrentPathBar(), toolbarHeight: 70, actionsPadding: const EdgeInsets.only(right: 24), - actions: [ if (kIsWeb) const Padding( - padding: EdgeInsets.symmetric(horizontal: 8.0), + padding: EdgeInsets.symmetric(horizontal: 8), child: DemoTag(), ), Row( @@ -231,9 +220,7 @@ class _FolderNavigatorState extends ConsumerState { onPressed: () async { await showDialog( context: context, - builder: (context) { - return const FolderEditDialog(); - }, + builder: (_) => const FolderEditDialog(), ); }, ), @@ -243,62 +230,47 @@ class _FolderNavigatorState extends ConsumerState { child: const Text('Create Strategy'), ), ], - ) + ), ], - // ... your existing actions ), - body: FolderContent(folder: currentFolder), + body: const FolderContent(), ); } } -sealed class GridItem {} - -class FolderItem extends GridItem { - final Folder folder; - - FolderItem(this.folder); -} - -class StrategyItem extends GridItem { - final StrategyData strategy; - - StrategyItem(this.strategy); -} - class FolderContent extends ConsumerWidget { - const FolderContent({super.key, this.folder}); - - final Folder? folder; + const FolderContent({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final isCloud = ref.watch(isCloudCollabEnabledProvider); if (isCloud) { - return _CloudFolderContent(folder: folder); + return const _CloudFolderContent(); } - return _LocalFolderContent(folder: folder); + return const _LocalFolderContent(); } } class _CloudFolderContent extends ConsumerWidget { - const _CloudFolderContent({this.folder}); - - final Folder? folder; + const _CloudFolderContent(); @override Widget build(BuildContext context, WidgetRef ref) { - final foldersAsync = ref.watch(cloudFoldersProvider); - final strategiesAsync = ref.watch(cloudStrategiesProvider); + final folders = ref.watch(cloudFoldersProvider).valueOrNull ?? const []; + final strategies = + ref.watch(cloudStrategiesProvider).valueOrNull ?? const []; + final currentFolderId = ref.watch(folderProvider); final search = ref.watch(strategySearchQueryProvider).trim().toLowerCase(); final filter = ref.watch(strategyFilterProvider); - final folders = foldersAsync.valueOrNull ?? const []; - var strategies = - strategiesAsync.valueOrNull ?? const []; + var visibleFolders = folders; + var visibleStrategies = strategies; if (search.isNotEmpty) { - strategies = strategies + visibleFolders = visibleFolders + .where((folder) => folder.name.toLowerCase().contains(search)) + .toList(growable: false); + visibleStrategies = visibleStrategies .where((strategy) => strategy.name.toLowerCase().contains(search)) .toList(growable: false); } @@ -311,8 +283,188 @@ class _CloudFolderContent extends ConsumerWidget { }; final direction = filter.sortOrder == SortOrder.ascending ? 1 : -1; - strategies = [...strategies]..sort((a, b) => direction * comparator(a, b)); + visibleStrategies = [...visibleStrategies] + ..sort((a, b) => direction * comparator(a, b)); + visibleFolders = [...visibleFolders] + ..sort((a, b) => a.createdAt.compareTo(b.createdAt)); + + final folderEntries = visibleFolders + .map( + (folder) => _FolderEntry( + data: LibraryFolderItemData( + id: folder.publicId, + name: folder.name, + icon: Folder.iconFromIndex(folder.iconIndex), + backgroundColor: Folder.customColorFromValue( + folder.customColorValue) ?? + Folder.folderColorMap[Folder.colorFromKey(folder.colorKey)] ?? + Colors.grey, + ), + onOpen: () => + ref.read(folderProvider.notifier).updateID(folder.publicId), + onEdit: () => showDialog( + context: context, + builder: (_) => FolderEditDialog( + folderId: folder.publicId, + initialName: folder.name, + initialIcon: Folder.iconFromIndex(folder.iconIndex), + initialColor: Folder.colorFromKey(folder.colorKey), + initialCustomColor: + Folder.customColorFromValue(folder.customColorValue), + ), + ), + onDelete: () => _confirmDeleteFolder( + context, ref, folder.name, folder.publicId), + ), + ) + .toList(growable: false); + + final strategyEntries = visibleStrategies + .map( + (strategy) => _StrategyEntry( + strategyId: strategy.publicId, + currentName: strategy.name, + data: StrategyTileDataFactory.fromCloud( + id: strategy.publicId, + name: strategy.name, + mapData: strategy.mapData, + updatedAt: strategy.updatedAt, + ), + canRename: strategy.role == 'editor' || strategy.role == 'owner', + canDuplicate: true, + canExport: true, + canDelete: strategy.role == 'owner', + ), + ) + .toList(growable: false); + + return _SharedFolderContent( + folderEntries: folderEntries, + strategyEntries: strategyEntries, + isRoot: currentFolderId == null, + ); + } +} + +class _LocalFolderContent extends ConsumerWidget { + const _LocalFolderContent(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final strategyBox = Hive.box(HiveBoxNames.strategiesBox); + final folderBox = Hive.box(HiveBoxNames.foldersBox); + final currentFolderId = ref.watch(folderProvider); + + return ValueListenableBuilder>( + valueListenable: strategyBox.listenable(), + builder: (context, strategiesListenable, _) { + return ValueListenableBuilder>( + valueListenable: folderBox.listenable(), + builder: (context, foldersListenable, __) { + final search = + ref.watch(strategySearchQueryProvider).trim().toLowerCase(); + final filter = ref.watch(strategyFilterProvider); + + var folders = foldersListenable.values + .where((folder) => folder.parentID == currentFolderId) + .toList(growable: false); + + var strategies = strategiesListenable.values + .where((strategy) => strategy.folderID == currentFolderId) + .toList(growable: false); + + if (search.isNotEmpty) { + folders = folders + .where((folder) => folder.name.toLowerCase().contains(search)) + .toList(growable: false); + strategies = strategies + .where((strategy) => + strategy.name.toLowerCase().contains(search)) + .toList(growable: false); + } + + Comparator comparator = switch (filter.sortBy) { + SortBy.alphabetical => (a, b) => + a.name.toLowerCase().compareTo(b.name.toLowerCase()), + SortBy.dateCreated => (a, b) => + a.createdAt.compareTo(b.createdAt), + SortBy.dateUpdated => (a, b) => + a.lastEdited.compareTo(b.lastEdited), + }; + + final direction = filter.sortOrder == SortOrder.ascending ? 1 : -1; + strategies = [...strategies] + ..sort((a, b) => direction * comparator(a, b)); + folders = [...folders] + ..sort((a, b) => a.dateCreated.compareTo(b.dateCreated)); + + final folderEntries = folders + .map( + (folder) => _FolderEntry( + data: LibraryFolderItemData( + id: folder.id, + name: folder.name, + icon: folder.icon, + backgroundColor: folder.customColor ?? + Folder.folderColorMap[folder.color] ?? + Colors.grey, + ), + onOpen: () => + ref.read(folderProvider.notifier).updateID(folder.id), + onEdit: () => showDialog( + context: context, + builder: (_) => FolderEditDialog(folder: folder), + ), + onExport: () async { + await ref + .read(strategyProvider.notifier) + .exportFolder(folder.id); + }, + onDelete: () => _confirmDeleteFolder( + context, ref, folder.name, folder.id), + ), + ) + .toList(growable: false); + + final strategyEntries = strategies + .map( + (strategy) => _StrategyEntry( + strategyId: strategy.id, + currentName: strategy.name, + data: StrategyTileDataFactory.fromLocal(strategy), + canRename: true, + canDuplicate: true, + canExport: true, + canDelete: true, + ), + ) + .toList(growable: false); + + return _SharedFolderContent( + folderEntries: folderEntries, + strategyEntries: strategyEntries, + isRoot: currentFolderId == null, + ); + }, + ); + }, + ); + } +} + +class _SharedFolderContent extends StatelessWidget { + const _SharedFolderContent({ + required this.folderEntries, + required this.strategyEntries, + required this.isRoot, + }); + + final List<_FolderEntry> folderEntries; + final List<_StrategyEntry> strategyEntries; + final bool isRoot; + @override + Widget build(BuildContext context) { return Stack( children: [ const Positioned.fill( @@ -329,7 +481,7 @@ class _CloudFolderContent extends ConsumerWidget { child: IcaDropTarget( child: CustomScrollView( slivers: [ - if (folders.isNotEmpty) + if (folderEntries.isNotEmpty) SliverToBoxAdapter( child: Padding( padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), @@ -337,13 +489,19 @@ class _CloudFolderContent extends ConsumerWidget { spacing: 10, runSpacing: 10, children: [ - for (final cloudFolder in folders) - CloudFolderPill(folder: cloudFolder), + for (final folder in folderEntries) + FolderPill( + data: folder.data, + onOpen: folder.onOpen, + onEdit: folder.onEdit, + onExport: folder.onExport, + onDelete: folder.onDelete, + ), ], ), ), ), - if (strategies.isNotEmpty) + if (strategyEntries.isNotEmpty) SliverPadding( padding: const EdgeInsets.all(16), sliver: SliverGrid( @@ -356,19 +514,35 @@ class _CloudFolderContent extends ConsumerWidget { ), delegate: SliverChildBuilderDelegate( (context, index) { - return CloudStrategyTile( - strategy: strategies[index], + final entry = strategyEntries[index]; + return StrategyTile( + strategyId: entry.strategyId, + currentName: entry.currentName, + data: entry.data, + canRename: entry.canRename, + canDuplicate: entry.canDuplicate, + canExport: entry.canExport, + canDelete: entry.canDelete, ); }, - childCount: strategies.length, + childCount: strategyEntries.length, ), ), ) else - const SliverFillRemaining( + SliverFillRemaining( hasScrollBody: false, child: Center( - child: Text('No cloud strategies in this folder'), + child: isRoot + ? const Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('No strategies available'), + Text( + 'Create a new strategy or drop an .ica file'), + ], + ) + : const Text('No strategies in this folder'), ), ), ], @@ -383,131 +557,6 @@ class _CloudFolderContent extends ConsumerWidget { } } -class _LocalFolderContent extends ConsumerWidget { - const _LocalFolderContent({this.folder}); - - final Folder? folder; - - @override - Widget build(BuildContext context, WidgetRef ref) { - final strategyBox = Hive.box(HiveBoxNames.strategiesBox); - final folderBox = Hive.box(HiveBoxNames.foldersBox); - - return Stack( - children: [ - const Positioned.fill( - child: Padding( - padding: EdgeInsets.all(4), - child: DotGrid(), - ), - ), - Positioned.fill( - child: Column( - children: [ - const _FolderToolbar(), - Expanded( - child: ValueListenableBuilder>( - valueListenable: strategyBox.listenable(), - builder: (context, strategiesListenable, _) { - return ValueListenableBuilder>( - valueListenable: folderBox.listenable(), - builder: (context, foldersListenable, __) { - final search = ref - .watch(strategySearchQueryProvider) - .trim() - .toLowerCase(); - final filter = ref.watch(strategyFilterProvider); - - final folders = foldersListenable.values - .where((f) => f.parentID == folder?.id) - .toList(growable: false); - - var strategies = strategiesListenable.values - .where((s) => s.folderID == folder?.id) - .toList(growable: false); - - if (search.isNotEmpty) { - strategies = strategies - .where( - (s) => s.name.toLowerCase().contains(search)) - .toList(growable: false); - } - - Comparator comparator = - switch (filter.sortBy) { - SortBy.alphabetical => (a, b) => a.name - .toLowerCase() - .compareTo(b.name.toLowerCase()), - SortBy.dateCreated => (a, b) => - a.createdAt.compareTo(b.createdAt), - SortBy.dateUpdated => (a, b) => - a.lastEdited.compareTo(b.lastEdited), - }; - final direction = - filter.sortOrder == SortOrder.ascending ? 1 : -1; - strategies = [...strategies] - ..sort((a, b) => direction * comparator(a, b)); - - return IcaDropTarget( - child: CustomScrollView( - slivers: [ - if (folders.isNotEmpty) - SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.fromLTRB( - 16, 16, 16, 8), - child: Wrap( - spacing: 10, - runSpacing: 10, - children: folders - .map((f) => FolderPill(folder: f)) - .toList(growable: false), - ), - ), - ), - if (strategies.isNotEmpty) - SliverPadding( - padding: const EdgeInsets.all(16), - sliver: SliverGrid( - gridDelegate: - const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 320, - mainAxisExtent: 250, - crossAxisSpacing: 20, - mainAxisSpacing: 20, - ), - delegate: SliverChildBuilderDelegate( - (context, index) { - return StrategyTile( - strategyData: strategies[index]); - }, - childCount: strategies.length, - ), - ), - ) - else - const SliverFillRemaining( - hasScrollBody: false, - child: Center( - child: Text('No strategies in this folder'), - ), - ), - ], - ), - ); - }, - ); - }, - ), - ), - ], - ), - ), - ], - ); - } -} - class _FolderToolbar extends ConsumerWidget { const _FolderToolbar(); @@ -574,3 +623,58 @@ class _FolderToolbar extends ConsumerWidget { ); } } + +class _FolderEntry { + const _FolderEntry({ + required this.data, + required this.onOpen, + this.onEdit, + this.onExport, + this.onDelete, + }); + + final LibraryFolderItemData data; + final VoidCallback onOpen; + final VoidCallback? onEdit; + final VoidCallback? onExport; + final VoidCallback? onDelete; +} + +class _StrategyEntry { + const _StrategyEntry({ + required this.strategyId, + required this.currentName, + required this.data, + required this.canRename, + required this.canDuplicate, + required this.canExport, + required this.canDelete, + }); + + final String strategyId; + final String currentName; + final LibraryStrategyItemData data; + final bool canRename; + final bool canDuplicate; + final bool canExport; + final bool canDelete; +} + +Future _confirmDeleteFolder( + BuildContext context, + WidgetRef ref, + String folderName, + String folderId, +) async { + final confirmed = await ConfirmAlertDialog.show( + context: context, + title: "Are you sure you want to delete '$folderName' folder?", + content: 'This will also delete all strategies and subfolders within it.', + confirmText: 'Delete', + isDestructive: true, + ); + + if (confirmed == true) { + ref.read(folderProvider.notifier).deleteFolder(folderId); + } +} diff --git a/lib/widgets/folder_pill.dart b/lib/widgets/folder_pill.dart index 5afab198..214b9a2e 100644 --- a/lib/widgets/folder_pill.dart +++ b/lib/widgets/folder_pill.dart @@ -2,20 +2,28 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/providers/folder_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; -import 'package:icarus/widgets/dialogs/confirm_alert_dialog.dart'; -import 'package:icarus/widgets/folder_edit_dialog.dart'; -import 'package:icarus/widgets/folder_navigator.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; class FolderPill extends ConsumerStatefulWidget { const FolderPill({ super.key, - required this.folder, + required this.data, this.isDemo = false, + this.enableDragAndDrop = true, + this.onOpen, + this.onEdit, + this.onExport, + this.onDelete, }); - final Folder folder; + final LibraryFolderItemData data; final bool isDemo; + final bool enableDragAndDrop; + final VoidCallback? onOpen; + final VoidCallback? onEdit; + final VoidCallback? onExport; + final VoidCallback? onDelete; @override ConsumerState createState() => _FolderPillState(); @@ -23,13 +31,14 @@ class FolderPill extends ConsumerStatefulWidget { class _FolderPillState extends ConsumerState with SingleTickerProviderStateMixin { - late AnimationController _animationController; - late Animation _scaleAnimation; + late final AnimationController _animationController; + late final Animation _scaleAnimation; bool _isHovered = false; final ShadContextMenuController _contextMenuController = ShadContextMenuController(); final ShadContextMenuController _rightClickMenuController = ShadContextMenuController(); + @override void initState() { super.initState(); @@ -50,121 +59,131 @@ class _FolderPillState extends ConsumerState @override void dispose() { _animationController.dispose(); + _contextMenuController.dispose(); + _rightClickMenuController.dispose(); super.dispose(); } - Color get _folderColor => - widget.folder.customColor ?? - Folder.folderColorMap[widget.folder.color] ?? - Colors.grey; - @override Widget build(BuildContext context) { - return Draggable( + final content = _buildInteractiveContent(); + if (!widget.enableDragAndDrop || widget.isDemo) { + return content; + } + + return Draggable( feedback: _buildDragFeedback(), dragAnchorStrategy: pointerDragAnchorStrategy, - data: FolderItem(widget.folder), - child: DragTarget( + data: FolderDragItem(widget.data.id), + child: DragTarget( onWillAcceptWithDetails: (details) { final item = details.data; - if (widget.isDemo) return false; - if (item is FolderItem) { - return item.folder.id != widget.folder.id && - !_isParentFolder(item.folder.id); + if (item is FolderDragItem) { + return item.id != widget.data.id; } return true; }, onAcceptWithDetails: (details) { - if (widget.isDemo) return; final item = details.data; - if (item is StrategyItem) { + if (item is StrategyDragItem) { ref.read(strategyProvider.notifier).moveToFolder( - strategyID: item.strategy.id, parentID: widget.folder.id); - } else if (item is FolderItem) { + strategyID: item.id, + parentID: widget.data.id, + ); + } else if (item is FolderDragItem) { ref.read(folderProvider.notifier).moveToFolder( - folderID: item.folder.id, parentID: widget.folder.id); + folderID: item.id, + parentID: widget.data.id, + ); } }, builder: (context, candidateData, rejectedData) { - final isDropTarget = candidateData.isNotEmpty; - return MouseRegion( - onEnter: (_) { - setState(() => _isHovered = true); - _animationController.forward(); - }, - onExit: (_) { - setState(() => _isHovered = false); - _animationController.reverse(); - }, - cursor: SystemMouseCursors.click, - child: ShadContextMenuRegion( - controller: _rightClickMenuController, - items: _buildMenuItems(), - child: GestureDetector( - onTap: () { - if (widget.isDemo) return; - ref.read(folderProvider.notifier).updateID(widget.folder.id); - }, - child: AnimatedBuilder( - animation: _scaleAnimation, - builder: (context, child) { - return Transform.scale( - scale: _scaleAnimation.value, - child: Container( - height: 44, - padding: const EdgeInsets.only(left: 14, right: 6), - decoration: BoxDecoration( - color: _folderColor, - borderRadius: BorderRadius.circular(22), - border: Border.all( - color: isDropTarget - ? Colors.white - : (_isHovered - ? Colors.white.withValues(alpha: 0.5) - : Colors.white.withValues(alpha: 0.15)), - width: isDropTarget ? 2 : 1, + return _buildInteractiveContent( + isDropTarget: candidateData.isNotEmpty, + ); + }, + ), + ); + } + + Widget _buildInteractiveContent({bool isDropTarget = false}) { + return MouseRegion( + onEnter: (_) { + setState(() => _isHovered = true); + _animationController.forward(); + }, + onExit: (_) { + setState(() => _isHovered = false); + _animationController.reverse(); + }, + cursor: widget.onOpen == null + ? SystemMouseCursors.basic + : SystemMouseCursors.click, + child: ShadContextMenuRegion( + controller: _rightClickMenuController, + items: _buildMenuItems(), + child: GestureDetector( + onTap: widget.isDemo ? null : widget.onOpen, + child: AnimatedBuilder( + animation: _scaleAnimation, + builder: (context, child) { + return Transform.scale( + scale: _scaleAnimation.value, + child: Container( + height: 44, + padding: const EdgeInsets.only(left: 14, right: 6), + decoration: BoxDecoration( + color: widget.data.backgroundColor, + borderRadius: BorderRadius.circular(22), + border: Border.all( + color: isDropTarget + ? Colors.white + : (_isHovered + ? Colors.white.withValues(alpha: 0.5) + : Colors.white.withValues(alpha: 0.15)), + width: isDropTarget ? 2 : 1, + ), + boxShadow: [ + BoxShadow( + color: + widget.data.backgroundColor.withValues(alpha: 0.3), + blurRadius: _isHovered ? 8 : 4, + offset: const Offset(0, 2), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + widget.data.icon, + color: Colors.white, + size: 20, + ), + const SizedBox(width: 10), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 140), + child: Text( + widget.data.name, + style: const TextStyle( + color: Colors.white, + fontSize: 14, + fontWeight: FontWeight.w600, ), - boxShadow: [ - BoxShadow( - color: _folderColor.withValues(alpha: 0.3), - blurRadius: _isHovered ? 8 : 4, - offset: const Offset(0, 2), - ), - ], - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - widget.folder.icon, - color: Colors.white, - size: 20, - ), - const SizedBox(width: 10), - ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 140), - child: Text( - widget.folder.name, - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600, - ), - overflow: TextOverflow.ellipsis, - ), - ), - const SizedBox(width: 4), - _buildMenuButton(), - ], + overflow: TextOverflow.ellipsis, ), ), - ); - }, + if (_buildMenuItems().isNotEmpty) ...[ + const SizedBox(width: 4), + _buildMenuButton(), + ], + ], + ), ), - ), - ), - ); - }, + ); + }, + ), + ), ), ); } @@ -179,7 +198,7 @@ class _FolderPillState extends ConsumerState _contextMenuController.toggle(); }, child: Padding( - padding: const EdgeInsets.all(4.0), + padding: const EdgeInsets.all(4), child: Icon( Icons.more_vert, color: Colors.white.withValues(alpha: 0.8), @@ -191,50 +210,40 @@ class _FolderPillState extends ConsumerState } List _buildMenuItems() { - return [ - ShadContextMenuItem( - leading: const Icon(Icons.text_fields), - child: const Text('Edit'), - onPressed: () async { - if (widget.isDemo) return; - await showDialog( - context: context, - builder: (context) { - return FolderEditDialog(folder: widget.folder); - }, - ); - }, - ), - ShadContextMenuItem( - leading: const Icon(Icons.file_upload), - child: const Text('Export'), - onPressed: () async { - await ref - .read(strategyProvider.notifier) - .exportFolder(widget.folder.id); - }, - ), - ShadContextMenuItem( - leading: const Icon(Icons.delete, color: Colors.redAccent), - child: const Text('Delete', style: TextStyle(color: Colors.redAccent)), - onPressed: () async { - ConfirmAlertDialog.show( - context: context, - title: - "Are you sure you want to delete '${widget.folder.name}' folder?", - content: - "This will also delete all strategies and subfolders within it.", - confirmText: "Delete", - isDestructive: true, - ).then((confirmed) { - if (confirmed) { - if (widget.isDemo) return; - ref.read(folderProvider.notifier).deleteFolder(widget.folder.id); - } - }); - }, - ), - ]; + final items = []; + + if (widget.onEdit != null) { + items.add( + ShadContextMenuItem( + leading: const Icon(Icons.text_fields), + onPressed: widget.onEdit, + child: const Text('Edit'), + ), + ); + } + + if (widget.onExport != null) { + items.add( + ShadContextMenuItem( + leading: const Icon(Icons.file_upload), + onPressed: widget.onExport, + child: const Text('Export'), + ), + ); + } + + if (widget.onDelete != null) { + items.add( + ShadContextMenuItem( + leading: const Icon(Icons.delete, color: Colors.redAccent), + onPressed: widget.onDelete, + child: + const Text('Delete', style: TextStyle(color: Colors.redAccent)), + ), + ); + } + + return items; } Widget _buildDragFeedback() { @@ -246,7 +255,7 @@ class _FolderPillState extends ConsumerState height: 44, padding: const EdgeInsets.symmetric(horizontal: 14), decoration: BoxDecoration( - color: _folderColor, + color: widget.data.backgroundColor, borderRadius: BorderRadius.circular(22), border: Border.all(color: Colors.white, width: 2), ), @@ -254,13 +263,13 @@ class _FolderPillState extends ConsumerState mainAxisSize: MainAxisSize.min, children: [ Icon( - widget.folder.icon, + widget.data.icon, color: Colors.white, size: 20, ), const SizedBox(width: 10), Text( - widget.folder.name, + widget.data.name, style: const TextStyle( color: Colors.white, fontSize: 14, @@ -273,15 +282,4 @@ class _FolderPillState extends ConsumerState ), ); } - - bool _isParentFolder(String folderId) { - String? currentParentId = widget.folder.parentID; - while (currentParentId != null) { - if (currentParentId == folderId) return true; - final parentFolder = - ref.read(folderProvider.notifier).findFolderByID(currentParentId); - currentParentId = parentFolder?.parentID; - } - return false; - } } diff --git a/lib/widgets/library_models.dart b/lib/widgets/library_models.dart new file mode 100644 index 00000000..f38821a0 --- /dev/null +++ b/lib/widgets/library_models.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:icarus/const/agents.dart'; + +sealed class LibraryDragItem { + const LibraryDragItem(this.id); + + final String id; +} + +class FolderDragItem extends LibraryDragItem { + const FolderDragItem(super.id); +} + +class StrategyDragItem extends LibraryDragItem { + const StrategyDragItem(super.id); +} + +class LibraryPathItemData { + const LibraryPathItemData({ + required this.id, + required this.name, + }); + + final String? id; + final String name; +} + +class LibraryFolderItemData { + const LibraryFolderItemData({ + required this.id, + required this.name, + required this.icon, + required this.backgroundColor, + }); + + final String id; + final String name; + final IconData icon; + final Color backgroundColor; +} + +class LibraryStrategyItemData { + const LibraryStrategyItemData({ + required this.id, + required this.name, + required this.mapName, + required this.thumbnailAsset, + required this.statusLabel, + required this.statusColor, + required this.updatedLabel, + this.badgeLabel, + this.agentTypes = const [], + }); + + final String id; + final String name; + final String mapName; + final String thumbnailAsset; + final String statusLabel; + final Color statusColor; + final String updatedLabel; + final String? badgeLabel; + final List agentTypes; +} diff --git a/lib/widgets/pages_bar.dart b/lib/widgets/pages_bar.dart index 0c7f6e73..d5199f86 100644 --- a/lib/widgets/pages_bar.dart +++ b/lib/widgets/pages_bar.dart @@ -6,39 +6,107 @@ import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/collab/cloud_collab_provider.dart'; import 'package:icarus/providers/collab/remote_strategy_snapshot_provider.dart'; import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/widgets/custom_text_field.dart'; +import 'package:icarus/widgets/dialogs/confirm_alert_dialog.dart'; +import 'package:shadcn_ui/shadcn_ui.dart'; -class PagesBar extends ConsumerWidget { +class PagesBar extends ConsumerStatefulWidget { const PagesBar({super.key}); - Future _addPage(WidgetRef ref) async { + @override + ConsumerState createState() => _PagesBarState(); +} + +class _PagesBarState extends ConsumerState { + bool _expanded = false; + + Future _addPage() async { await ref.read(strategyProvider.notifier).addPage(); } - Future _selectPage(WidgetRef ref, String pageId) async { - await ref.read(strategyProvider.notifier).switchPage(pageId); + Future _selectPage(String id) async { + await ref.read(strategyProvider.notifier).switchPage(id); + } + + Future _renamePage(_PageBarItemData page) async { + final controller = TextEditingController(text: page.name); + final newName = await showShadDialog( + context: context, + builder: (ctx) => ShadDialog( + title: const Text('Rename page'), + description: const Text('Enter a new name for the page:'), + actions: [ + ShadButton.secondary( + onPressed: () => Navigator.of(ctx).pop(), + child: const Text('Cancel'), + ), + ShadButton( + onPressed: () => Navigator.of(ctx).pop(controller.text.trim()), + leading: const Icon(Icons.text_fields), + child: const Text('Rename'), + ), + ], + child: CustomTextField( + controller: controller, + onSubmitted: (value) => Navigator.of(ctx).pop(value.trim()), + ), + ), + ); + + controller.dispose(); + if (newName == null || newName.isEmpty || newName == page.name) { + return; + } + + await ref.read(strategyProvider.notifier).renamePage(page.id, newName); + } + + Future _deletePage(_PageBarItemData page, int totalPages) async { + if (totalPages <= 1) { + return; + } + + final confirm = await ConfirmAlertDialog.show( + context: context, + title: "Delete '${page.name}'?", + content: + 'Are you sure you want to delete this page? This action cannot be undone.', + confirmText: 'Delete', + cancelText: 'Cancel', + isDestructive: true, + ); + + if (confirm != true) { + return; + } + + await ref.read(strategyProvider.notifier).deletePage(page.id); } @override - Widget build(BuildContext context, WidgetRef ref) { + Widget build(BuildContext context) { final isCloud = ref.watch(isCloudCollabEnabledProvider); final activePageId = ref.watch(strategyProvider.select((state) => state.activePageId)); if (isCloud) { final snapshot = ref.watch(remoteStrategySnapshotProvider).valueOrNull; - if (snapshot == null || snapshot.pages.isEmpty) { - return const SizedBox.shrink(); - } - - final pages = [...snapshot.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - - return _SimplePagesBar( - pageIds: pages.map((p) => p.publicId).toList(growable: false), - pageNames: pages.map((p) => p.name).toList(growable: false), - activePageId: activePageId ?? pages.first.publicId, - onAdd: () => _addPage(ref), - onSelect: (id) => _selectPage(ref, id), + final canEdit = snapshot?.header.role != 'viewer'; + final pages = snapshot == null + ? const <_PageBarItemData>[] + : ([ + for (final page in [ + ...snapshot.pages + ]..sort((a, b) => a.sortIndex.compareTo(b.sortIndex))) + _PageBarItemData( + id: page.publicId, + name: page.name, + ), + ]); + return _buildBar( + pages: pages, + activePageId: activePageId, + canEdit: canEdit, ); } @@ -49,44 +117,45 @@ class PagesBar extends ConsumerWidget { valueListenable: box.listenable(keys: [strategyId]), builder: (context, strategyBox, _) { final strategy = strategyBox.get(strategyId); - if (strategy == null || strategy.pages.isEmpty) { - return const SizedBox.shrink(); - } - - final pages = [...strategy.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - - return _SimplePagesBar( - pageIds: pages.map((p) => p.id).toList(growable: false), - pageNames: pages.map((p) => p.name).toList(growable: false), - activePageId: activePageId ?? pages.first.id, - onAdd: () => _addPage(ref), - onSelect: (id) => _selectPage(ref, id), + final pages = strategy == null + ? const <_PageBarItemData>[] + : ([ + for (final page in [ + ...strategy.pages + ]..sort((a, b) => a.sortIndex.compareTo(b.sortIndex))) + _PageBarItemData( + id: page.id, + name: page.name, + ), + ]); + + return _buildBar( + pages: pages, + activePageId: activePageId, + canEdit: true, ); }, ); } -} -class _SimplePagesBar extends StatelessWidget { - const _SimplePagesBar({ - required this.pageIds, - required this.pageNames, - required this.activePageId, - required this.onAdd, - required this.onSelect, - }); + Widget _buildBar({ + required List<_PageBarItemData> pages, + required String? activePageId, + required bool canEdit, + }) { + if (pages.isEmpty) { + return const SizedBox.shrink(); + } - final List pageIds; - final List pageNames; - final String activePageId; - final VoidCallback onAdd; - final ValueChanged onSelect; + final resolvedActivePageId = activePageId ?? pages.first.id; + final activePage = pages.firstWhere( + (page) => page.id == resolvedActivePageId, + orElse: () => pages.first, + ); - @override - Widget build(BuildContext context) { - return Container( - width: 224, + return AnimatedContainer( + duration: const Duration(milliseconds: 180), + curve: Curves.easeInOut, decoration: BoxDecoration( color: Settings.tacticalVioletTheme.card, borderRadius: BorderRadius.circular(16), @@ -95,36 +164,416 @@ class _SimplePagesBar extends StatelessWidget { width: 2, ), ), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + width: 224, + child: _expanded + ? _ExpandedPanel( + pages: pages, + activePageId: resolvedActivePageId, + canEdit: canEdit, + onSelect: _selectPage, + onRename: _renamePage, + onDelete: (page) => _deletePage(page, pages.length), + onAdd: _addPage, + onCollapse: () => setState(() => _expanded = false), + ) + : _CollapsedPill( + activeName: activePage.name, + onAdd: canEdit ? _addPage : null, + onToggle: () => setState(() => _expanded = true), + ), + ); + } +} + +class _CollapsedPill extends StatelessWidget { + const _CollapsedPill({ + required this.activeName, + required this.onAdd, + required this.onToggle, + }); + + final String activeName; + final VoidCallback? onAdd; + final VoidCallback onToggle; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return SizedBox( + height: 48, child: Row( children: [ - IconButton( - onPressed: onAdd, - icon: const Icon(Icons.add, color: Colors.white), + const SizedBox(width: 8), + _SquareIconButton( + icon: Icons.add, + onTap: onAdd, tooltip: 'Add page', ), - const SizedBox(width: 8), + const SizedBox(width: 12), Expanded( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - for (var i = 0; i < pageIds.length; i++) - Padding( - padding: const EdgeInsets.only(right: 6), - child: ChoiceChip( - label: Text(pageNames[i]), - selected: pageIds[i] == activePageId, - onSelected: (_) => onSelect(pageIds[i]), - ), + child: Text( + activeName, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleMedium?.copyWith( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + ShadIconButton.ghost( + foregroundColor: Colors.white, + onPressed: onToggle, + icon: const Icon(Icons.keyboard_arrow_down, color: Colors.white), + ), + const SizedBox(width: 4), + ], + ), + ); + } +} + +class _ExpandedPanel extends ConsumerWidget { + const _ExpandedPanel({ + required this.pages, + required this.activePageId, + required this.canEdit, + required this.onSelect, + required this.onRename, + required this.onDelete, + required this.onAdd, + required this.onCollapse, + }); + + final List<_PageBarItemData> pages; + final String activePageId; + final bool canEdit; + final ValueChanged onSelect; + final ValueChanged<_PageBarItemData> onRename; + final ValueChanged<_PageBarItemData> onDelete; + final VoidCallback onAdd; + final VoidCallback onCollapse; + + static const double _rowHeight = 40; + static const double _verticalSpacing = 10; + static const double _headerFooterHeight = 49; + static const double _topPadding = 8; + static const double _bottomPadding = 0; + static const double _maxPanelHeight = 310; + + double _computeDesiredHeight(int count) { + if (count == 0) { + return _headerFooterHeight + 56; + } + final rowsHeight = count * _rowHeight; + final spacersHeight = (count - 1) * _verticalSpacing; + final listSection = + _topPadding + rowsHeight + spacersHeight + _bottomPadding; + return (listSection + _headerFooterHeight).clamp(0, _maxPanelHeight); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final desiredHeight = _computeDesiredHeight(pages.length); + final needsScroll = desiredHeight >= _maxPanelHeight - 0.5; + final activeIndex = pages.indexWhere((page) => page.id == activePageId); + + int? backwardIndex; + int? forwardIndex; + if (activeIndex >= 0 && pages.isNotEmpty) { + backwardIndex = activeIndex - 1; + if (backwardIndex < 0) backwardIndex = pages.length - 1; + + forwardIndex = activeIndex + 1; + if (forwardIndex >= pages.length) forwardIndex = 0; + } + + return AnimatedContainer( + duration: const Duration(milliseconds: 150), + curve: Curves.easeInOut, + constraints: BoxConstraints( + maxHeight: _maxPanelHeight, + minHeight: desiredHeight, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Padding( + padding: const EdgeInsets.only(top: _topPadding), + child: ReorderableListView.builder( + onReorder: canEdit + ? (oldIndex, newIndex) { + ref + .read(strategyProvider.notifier) + .reorderPage(oldIndex, newIndex); + } + : (_, __) {}, + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + shrinkWrap: !needsScroll, + physics: + needsScroll ? null : const NeverScrollableScrollPhysics(), + itemCount: pages.length, + buildDefaultDragHandles: false, + proxyDecorator: (child, index, animation) => child, + itemBuilder: (context, index) { + final page = pages[index]; + + var showForwardIndicator = false; + var showBackwardIndicator = false; + if (pages.length != 1) { + if (pages.length == 2) { + if (activeIndex == 0 && activeIndex != index) { + showForwardIndicator = true; + } else if (activeIndex == 1 && activeIndex != index) { + showBackwardIndicator = true; + } + } else { + if (forwardIndex != null && index == forwardIndex) { + showForwardIndicator = true; + } + if (backwardIndex != null && + index == backwardIndex && + forwardIndex != backwardIndex) { + showBackwardIndicator = true; + } + } + } + + final row = Padding( + key: ValueKey(page.id), + padding: const EdgeInsets.only(bottom: 8), + child: _PageRow( + page: page, + active: page.id == activePageId, + showBackwardIndicator: showBackwardIndicator, + showForwardIndicator: showForwardIndicator, + onSelect: onSelect, + onRename: onRename, + onDelete: onDelete, + disableRename: !canEdit, + disableDelete: !canEdit || pages.length == 1, ), - ], + ); + + if (!canEdit) { + return row; + } + + return ReorderableDragStartListener( + key: ValueKey(page.id), + index: index, + child: row, + ); + }, ), ), ), + Divider(height: 1, color: Settings.tacticalVioletTheme.border), + SizedBox( + height: 48, + child: Row( + children: [ + const SizedBox(width: 8), + _SquareIconButton( + icon: Icons.add, + onTap: canEdit ? onAdd : null, + tooltip: 'Add page', + ), + const Spacer(), + ShadIconButton.ghost( + foregroundColor: Colors.white, + onPressed: onCollapse, + icon: + const Icon(Icons.keyboard_arrow_up, color: Colors.white), + ), + const SizedBox(width: 4), + ], + ), + ), ], ), ); } } +class _PageRow extends StatelessWidget { + const _PageRow({ + required this.page, + required this.active, + required this.showBackwardIndicator, + required this.showForwardIndicator, + required this.onSelect, + required this.onRename, + required this.onDelete, + required this.disableRename, + required this.disableDelete, + }); + + final _PageBarItemData page; + final bool active; + final bool showBackwardIndicator; + final bool showForwardIndicator; + final ValueChanged onSelect; + final ValueChanged<_PageBarItemData> onRename; + final ValueChanged<_PageBarItemData> onDelete; + final bool disableRename; + final bool disableDelete; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final backgroundColor = active + ? Settings.tacticalVioletTheme.primary + : Settings.tacticalVioletTheme.card; + + return Material( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + child: InkWell( + mouseCursor: SystemMouseCursors.click, + borderRadius: BorderRadius.circular(14), + onTap: () => onSelect(page.id), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Settings.tacticalVioletTheme.border, + width: 1, + ), + boxShadow: [ + BoxShadow( + color: Settings.tacticalVioletTheme.card.withValues(alpha: 0.2), + blurRadius: 12, + offset: const Offset(0, 4), + ), + ], + color: backgroundColor, + ), + height: 40, + child: Padding( + padding: const EdgeInsets.only(left: 12), + child: Row( + children: [ + Expanded( + child: Text( + page.name, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleMedium?.copyWith( + color: Colors.white, + fontWeight: active ? FontWeight.w600 : FontWeight.w500, + fontSize: 14, + ), + ), + ), + if (showBackwardIndicator || showForwardIndicator) ...[ + const SizedBox(width: 6), + if (showBackwardIndicator) const _KeybindBadge(label: 'A'), + if (showBackwardIndicator && showForwardIndicator) + const SizedBox(width: 4), + if (showForwardIndicator) const _KeybindBadge(label: 'D'), + const SizedBox(width: 2), + ], + ShadTooltip( + builder: (context) => const Text('Rename'), + child: ShadIconButton.ghost( + hoverBackgroundColor: Colors.transparent, + foregroundColor: Colors.white, + icon: const Icon(Icons.edit, size: 18, color: Colors.white), + onPressed: disableRename ? null : () => onRename(page), + ), + ), + ShadTooltip( + builder: (context) => const Text('Delete'), + child: ShadIconButton.ghost( + hoverForegroundColor: + Settings.tacticalVioletTheme.destructive, + hoverBackgroundColor: Colors.transparent, + foregroundColor: + disableDelete ? Colors.white24 : Colors.white, + icon: const Icon(Icons.delete, size: 18), + onPressed: disableDelete ? null : () => onDelete(page), + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +class _KeybindBadge extends StatelessWidget { + const _KeybindBadge({required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + return Container( + height: 20, + width: 20, + alignment: Alignment.center, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.card, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: Settings.tacticalVioletTheme.border), + ), + child: Center( + child: Text( + label, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.labelSmall?.copyWith( + color: Settings.tacticalVioletTheme.mutedForeground, + fontWeight: FontWeight.w700, + fontSize: 11, + height: 1, + ), + ), + ), + ); + } +} + +class _SquareIconButton extends StatelessWidget { + const _SquareIconButton({ + required this.icon, + required this.onTap, + required this.tooltip, + }); + + final IconData icon; + final VoidCallback? onTap; + final String tooltip; + + @override + Widget build(BuildContext context) { + return ShadTooltip( + builder: (context) => Text(tooltip), + child: ShadIconButton( + icon: Icon(icon), + width: 36, + height: 36, + onPressed: onTap, + decoration: ShadDecoration( + border: ShadBorder( + radius: BorderRadius.circular(12), + ), + ), + ), + ); + } +} + +class _PageBarItemData { + const _PageBarItemData({ + required this.id, + required this.name, + }); + + final String id; + final String name; +} diff --git a/lib/widgets/strategy_tile/strategy_tile.dart b/lib/widgets/strategy_tile/strategy_tile.dart index f3a5e08e..863cc8b2 100644 --- a/lib/widgets/strategy_tile/strategy_tile.dart +++ b/lib/widgets/strategy_tile/strategy_tile.dart @@ -1,6 +1,5 @@ import 'dart:developer'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:icarus/const/settings.dart'; @@ -8,14 +7,31 @@ import 'package:icarus/providers/strategy_provider.dart'; import 'package:icarus/strategy_view.dart'; import 'package:icarus/widgets/dialogs/strategy/delete_strategy_alert_dialog.dart'; import 'package:icarus/widgets/dialogs/strategy/rename_strategy_dialog.dart'; -import 'package:icarus/widgets/folder_navigator.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:icarus/widgets/strategy_tile/strategy_tile_sections.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; class StrategyTile extends ConsumerStatefulWidget { - const StrategyTile({super.key, required this.strategyData}); - - final StrategyData strategyData; + const StrategyTile({ + super.key, + required this.strategyId, + required this.currentName, + required this.data, + this.canRename = true, + this.canDuplicate = true, + this.canExport = true, + this.canDelete = true, + this.enableDrag = true, + }); + + final String strategyId; + final String currentName; + final LibraryStrategyItemData data; + final bool canRename; + final bool canDuplicate; + final bool canExport; + final bool canDelete; + final bool enableDrag; @override ConsumerState createState() => _StrategyTileState(); @@ -25,63 +41,50 @@ class _StrategyTileState extends ConsumerState { Color _highlightColor = Settings.tacticalVioletTheme.border; bool _isLoading = false; - final ShadPopoverController _menuController = ShadPopoverController(); final ShadContextMenuController _contextMenuController = ShadContextMenuController(); @override void dispose() { - _menuController.dispose(); _contextMenuController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - final viewData = StrategyTileViewData(widget.strategyData); - - return Draggable( - data: StrategyItem(widget.strategyData), - dragAnchorStrategy: pointerDragAnchorStrategy, - feedback: Opacity( - opacity: 0.95, - child: Material( - color: Colors.transparent, - child: StrategyTileDragPreview(data: viewData), - ), - ), - child: MouseRegion( - cursor: SystemMouseCursors.click, - onEnter: (_) => - setState(() => _highlightColor = Settings.tacticalVioletTheme.ring), - onExit: (_) => setState( - () => _highlightColor = Settings.tacticalVioletTheme.border), - child: AbsorbPointer( - absorbing: _isLoading, - child: GestureDetector( - onTap: () => _openStrategy(context), - child: Stack( - children: [ - AnimatedContainer( - duration: const Duration(milliseconds: 100), - decoration: BoxDecoration( - color: ShadTheme.of(context).colorScheme.card, - borderRadius: BorderRadius.circular(16), - border: Border.all(color: _highlightColor, width: 2), - ), - padding: const EdgeInsets.all(8), - child: Column( - children: [ - Expanded( - child: StrategyTileThumbnail( - assetPath: viewData.thumbnailAsset, - ), + final child = MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) => + setState(() => _highlightColor = Settings.tacticalVioletTheme.ring), + onExit: (_) => + setState(() => _highlightColor = Settings.tacticalVioletTheme.border), + child: AbsorbPointer( + absorbing: _isLoading, + child: GestureDetector( + onTap: () => _openStrategy(context), + child: Stack( + children: [ + AnimatedContainer( + duration: const Duration(milliseconds: 100), + decoration: BoxDecoration( + color: ShadTheme.of(context).colorScheme.card, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: _highlightColor, width: 2), + ), + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Expanded( + child: StrategyTileThumbnail( + assetPath: widget.data.thumbnailAsset, ), - const SizedBox(height: 10), - Expanded(child: StrategyTileDetails(data: viewData)), - ], - ), + ), + const SizedBox(height: 10), + Expanded(child: StrategyTileDetails(data: widget.data)), + ], ), + ), + if (_buildMenuItems().isNotEmpty) Align( alignment: Alignment.topRight, child: Padding( @@ -95,62 +98,94 @@ class _StrategyTileState extends ConsumerState { onPressed: () { _contextMenuController.toggle(); }, - icon: const Icon( - Icons.more_vert_outlined, - ), + icon: const Icon(Icons.more_vert_outlined), ), ), ), ), - ], - ), + ], ), ), ), ); + + if (!widget.enableDrag) { + return child; + } + + return Draggable( + data: StrategyDragItem(widget.strategyId), + dragAnchorStrategy: pointerDragAnchorStrategy, + feedback: Opacity( + opacity: 0.95, + child: Material( + color: Colors.transparent, + child: StrategyTileDragPreview(data: widget.data), + ), + ), + child: child, + ); } List _buildMenuItems() { - return [ - ShadContextMenuItem( - leading: const Icon(LucideIcons.pencil), - child: const Text('Rename'), - onPressed: () => _showRenameDialog(), - ), - ShadContextMenuItem( - leading: const Icon(LucideIcons.copy), - child: const Text('Duplicate'), - onPressed: () => _duplicateStrategy(), - ), - ShadContextMenuItem( - leading: const Icon(LucideIcons.upload), - child: const Text('Export'), - onPressed: () => _exportStrategy(), - ), - ShadContextMenuItem( - leading: const Icon(LucideIcons.trash2, color: Colors.redAccent), - child: const Text('Delete', style: TextStyle(color: Colors.redAccent)), - onPressed: () => _showDeleteDialog(), - ), - ]; + final items = []; + if (widget.canRename) { + items.add( + ShadContextMenuItem( + leading: const Icon(LucideIcons.pencil), + child: const Text('Rename'), + onPressed: () => _showRenameDialog(), + ), + ); + } + if (widget.canDuplicate) { + items.add( + ShadContextMenuItem( + leading: const Icon(LucideIcons.copy), + child: const Text('Duplicate'), + onPressed: () => _duplicateStrategy(), + ), + ); + } + if (widget.canExport) { + items.add( + ShadContextMenuItem( + leading: const Icon(LucideIcons.upload), + child: const Text('Export'), + onPressed: () => _exportStrategy(), + ), + ); + } + if (widget.canDelete) { + items.add( + ShadContextMenuItem( + leading: const Icon(LucideIcons.trash2, color: Colors.redAccent), + child: + const Text('Delete', style: TextStyle(color: Colors.redAccent)), + onPressed: () => _showDeleteDialog(), + ), + ); + } + return items; } Future _openStrategy(BuildContext context) async { - log('StrategyTile: opening strategy'); + log('StrategyTile: opening strategy ${widget.strategyId}'); if (_isLoading) { - log('StrategyTile: already loading'); return; } setState(() => _isLoading = true); _showLoadingOverlay(); + var dismissedOverlay = false; try { - await ref - .read(strategyProvider.notifier) - .loadFromHive(widget.strategyData.id); - if (!context.mounted) return; + await ref.read(strategyProvider.notifier).openStrategy(widget.strategyId); + if (!context.mounted) { + return; + } Navigator.pop(context); + dismissedOverlay = true; await Navigator.push( context, PageRouteBuilder( @@ -170,12 +205,10 @@ class _StrategyTileState extends ConsumerState { }, ), ); - } catch (error, stackTrace) { - log('Error loading strategy: $error', stackTrace: stackTrace); - if (context.mounted) { + } finally { + if (!dismissedOverlay && context.mounted) { Navigator.pop(context); } - } finally { if (mounted) { setState(() => _isLoading = false); } @@ -193,32 +226,19 @@ class _StrategyTileState extends ConsumerState { Future _duplicateStrategy() async { await ref .read(strategyProvider.notifier) - .duplicateStrategy(widget.strategyData.id); + .duplicateStrategy(widget.strategyId); } Future _exportStrategy() async { - if (kIsWeb) { - Settings.showToast( - message: 'This feature is only supported in the Windows version.', - backgroundColor: Settings.tacticalVioletTheme.destructive, - ); - return; - } - - await ref - .read(strategyProvider.notifier) - .loadFromHive(widget.strategyData.id); - await ref - .read(strategyProvider.notifier) - .exportFile(widget.strategyData.id); + await ref.read(strategyProvider.notifier).exportStrategy(widget.strategyId); } Future _showRenameDialog() async { await showShadDialog( context: context, builder: (_) => RenameStrategyDialog( - strategyId: widget.strategyData.id, - currentName: widget.strategyData.name, + strategyId: widget.strategyId, + currentName: widget.currentName, ), ); } @@ -227,8 +247,8 @@ class _StrategyTileState extends ConsumerState { showDialog( context: context, builder: (_) => DeleteStrategyAlertDialog( - strategyID: widget.strategyData.id, - name: widget.strategyData.name, + strategyID: widget.strategyId, + name: widget.currentName, ), ); } diff --git a/lib/widgets/strategy_tile/strategy_tile_sections.dart b/lib/widgets/strategy_tile/strategy_tile_sections.dart index d85e8fe7..543cad89 100644 --- a/lib/widgets/strategy_tile/strategy_tile_sections.dart +++ b/lib/widgets/strategy_tile/strategy_tile_sections.dart @@ -4,30 +4,47 @@ import 'package:icarus/const/maps.dart'; import 'package:icarus/const/settings.dart'; import 'package:icarus/providers/strategy_page.dart'; import 'package:icarus/providers/strategy_provider.dart'; +import 'package:icarus/widgets/library_models.dart'; import 'package:shadcn_ui/shadcn_ui.dart'; -class StrategyTileViewData { - StrategyTileViewData(this.strategy) - : name = strategy.name, - mapName = _mapName(strategy.mapData), - attackLabel = _attackLabel(strategy.pages), - attackColor = _attackColor(strategy.pages), - thumbnailAsset = - 'assets/maps/thumbnails/${Maps.mapNames[strategy.mapData]}_thumbnail.webp', - lastEditedLabel = _timeAgo(strategy.lastEdited), - agentTypes = _collectAgentTypes(strategy.pages); +class StrategyTileDataFactory { + static LibraryStrategyItemData fromLocal(StrategyData strategy) { + return LibraryStrategyItemData( + id: strategy.id, + name: strategy.name, + mapName: _mapName(Maps.mapNames[strategy.mapData]), + statusLabel: _attackLabel(strategy.pages), + statusColor: _attackColor(strategy.pages), + thumbnailAsset: + 'assets/maps/thumbnails/${Maps.mapNames[strategy.mapData]}_thumbnail.webp', + updatedLabel: _timeAgo(strategy.lastEdited), + agentTypes: _collectAgentTypes(strategy.pages), + ); + } - final StrategyData strategy; - final String name; - final String mapName; - final String attackLabel; - final Color attackColor; - final String thumbnailAsset; - final String lastEditedLabel; - final List agentTypes; + static LibraryStrategyItemData fromCloud({ + required String id, + required String name, + required String mapData, + required DateTime updatedAt, + }) { + final normalizedMap = mapData.trim().isEmpty + ? 'unknown' + : mapData.trim().toLowerCase().replaceAll(' ', '_'); + + return LibraryStrategyItemData( + id: id, + name: name, + mapName: _mapName(mapData.trim()), + statusLabel: 'Synced', + statusColor: Colors.deepPurpleAccent, + thumbnailAsset: 'assets/maps/thumbnails/${normalizedMap}_thumbnail.webp', + updatedLabel: _timeAgo(updatedAt), + badgeLabel: 'Online', + ); + } - static String _mapName(MapValue map) { - final raw = Maps.mapNames[map]; + static String _mapName(String? raw) { if (raw == null || raw.isEmpty) { return 'Unknown'; } @@ -40,13 +57,14 @@ class StrategyTileViewData { } final first = pages.first.isAttack; final mixed = pages.any((page) => page.isAttack != first); - if (mixed) return 'Mixed'; + if (mixed) { + return 'Mixed'; + } return first ? 'Attack' : 'Defend'; } static Color _attackColor(List pages) { - final label = _attackLabel(pages); - switch (label) { + switch (_attackLabel(pages)) { case 'Attack': return Colors.redAccent; case 'Defend': @@ -123,8 +141,7 @@ class StrategyTileThumbnail extends StatelessWidget { class StrategyTileDetails extends StatelessWidget { const StrategyTileDetails({super.key, required this.data}); - final StrategyTileViewData data; - + final LibraryStrategyItemData data; static const _maxVisibleAgents = 3; @override @@ -133,10 +150,11 @@ class StrategyTileDetails extends StatelessWidget { return Container( decoration: BoxDecoration( - color: ShadTheme.of(context).colorScheme.card, - borderRadius: BorderRadius.circular(16), - border: Border.all(color: Settings.tacticalVioletTheme.border), - boxShadow: const [Settings.cardForegroundBackdrop]), + color: ShadTheme.of(context).colorScheme.card, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Settings.tacticalVioletTheme.border), + boxShadow: const [Settings.cardForegroundBackdrop], + ), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -158,20 +176,43 @@ class StrategyTileDetails extends StatelessWidget { ), const SizedBox(height: 5), Text(data.mapName), - const SizedBox(height: 5), - ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 123), - child: Row( - spacing: 5, - children: [ - ...agents - .take(_maxVisibleAgents) - .map((agent) => _AgentIcon(agentType: agent)), - if (agents.length > _maxVisibleAgents) - const _MoreAgentsIndicator(), - ], + const SizedBox(height: 8), + if (data.badgeLabel != null) + Container( + padding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Settings.tacticalVioletTheme.primary + .withValues(alpha: 0.22), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Settings.tacticalVioletTheme.primary + .withValues(alpha: 0.5), + ), + ), + child: Text( + data.badgeLabel!, + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ) + else + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 123), + child: Row( + spacing: 5, + children: [ + ...agents + .take(_maxVisibleAgents) + .map((agent) => _AgentIcon(agentType: agent)), + if (agents.length > _maxVisibleAgents) + const _MoreAgentsIndicator(), + ], + ), ), - ), ], ), ), @@ -180,11 +221,11 @@ class StrategyTileDetails extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Text( - data.attackLabel, - style: TextStyle(color: data.attackColor), + data.statusLabel, + style: TextStyle(color: data.statusColor), ), const SizedBox(height: 5), - Text(data.lastEditedLabel, overflow: TextOverflow.ellipsis), + Text(data.updatedLabel, overflow: TextOverflow.ellipsis), ], ), ], @@ -196,7 +237,7 @@ class StrategyTileDetails extends StatelessWidget { class StrategyTileDragPreview extends StatelessWidget { const StrategyTileDragPreview({super.key, required this.data}); - final StrategyTileViewData data; + final LibraryStrategyItemData data; @override Widget build(BuildContext context) { diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..e1aaee81 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,583 @@ +{ + "name": "icarus", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "icarus", + "dependencies": { + "convex": "^1.32.0" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz", + "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz", + "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz", + "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz", + "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz", + "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz", + "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz", + "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz", + "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz", + "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz", + "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz", + "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz", + "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz", + "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz", + "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz", + "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz", + "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz", + "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz", + "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz", + "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz", + "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz", + "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz", + "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz", + "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz", + "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz", + "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/bun": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.3.11.tgz", + "integrity": "sha512-5vPne5QvtpjGpsGYXiFyycfpDF2ECyPcTSsFBMa0fraoxiQyMJ3SmuQIGhzPg2WJuWxVBoxWJ2kClYTcw/4fAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "bun-types": "1.3.11" + } + }, + "node_modules/@types/node": { + "dev": true + }, + "node_modules/bun-types": { + "version": "1.3.11", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.3.11.tgz", + "integrity": "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/convex": { + "version": "1.34.0", + "resolved": "https://registry.npmjs.org/convex/-/convex-1.34.0.tgz", + "integrity": "sha512-TbC509Z4urZMChZR2aLPgalQ8gMhAYSz2VMxaYsCvba8YqB0Uxma7zWnXwRn7aEGXuA8ro5/uHgD1IJ0HhYYPg==", + "license": "Apache-2.0", + "dependencies": { + "esbuild": "0.27.0", + "prettier": "^3.0.0", + "ws": "8.18.0" + }, + "bin": { + "convex": "bin/main.js" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=7.0.0" + }, + "peerDependencies": { + "@auth0/auth0-react": "^2.0.1", + "@clerk/clerk-react": "^4.12.8 || ^5.0.0", + "react": "^18.0.0 || ^19.0.0-0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@auth0/auth0-react": { + "optional": true + }, + "@clerk/clerk-react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/esbuild": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz", + "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.0", + "@esbuild/android-arm": "0.27.0", + "@esbuild/android-arm64": "0.27.0", + "@esbuild/android-x64": "0.27.0", + "@esbuild/darwin-arm64": "0.27.0", + "@esbuild/darwin-x64": "0.27.0", + "@esbuild/freebsd-arm64": "0.27.0", + "@esbuild/freebsd-x64": "0.27.0", + "@esbuild/linux-arm": "0.27.0", + "@esbuild/linux-arm64": "0.27.0", + "@esbuild/linux-ia32": "0.27.0", + "@esbuild/linux-loong64": "0.27.0", + "@esbuild/linux-mips64el": "0.27.0", + "@esbuild/linux-ppc64": "0.27.0", + "@esbuild/linux-riscv64": "0.27.0", + "@esbuild/linux-s390x": "0.27.0", + "@esbuild/linux-x64": "0.27.0", + "@esbuild/netbsd-arm64": "0.27.0", + "@esbuild/netbsd-x64": "0.27.0", + "@esbuild/openbsd-arm64": "0.27.0", + "@esbuild/openbsd-x64": "0.27.0", + "@esbuild/openharmony-arm64": "0.27.0", + "@esbuild/sunos-x64": "0.27.0", + "@esbuild/win32-arm64": "0.27.0", + "@esbuild/win32-ia32": "0.27.0", + "@esbuild/win32-x64": "0.27.0" + } + }, + "node_modules/esbuild/node_modules/@esbuild/win32-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz", + "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/prettier": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 00000000..9aa66272 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,30 @@ +{ + "version": 1, + "skills": { + "convex-create-component": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "computedHash": "dab09d7c164ad5ed7cce61e8e0d14019969d4511d294bb2e9c46742b35c50e04" + }, + "convex-migration-helper": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "computedHash": "fafc14244b2d06e48a9b0c1fd82c97ac9e10d11907b05ea1774b7da245630aab" + }, + "convex-performance-audit": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "computedHash": "72bb6d836c16d6bbbfd2ebbcbe4009268f933aae864225e7846f21f342a2567b" + }, + "convex-quickstart": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "computedHash": "90304d1faa4e7b2409db08a6d5c0807c8bb331a5023197d525f3780cf883f5f6" + }, + "convex-setup-auth": { + "source": "get-convex/agent-skills", + "sourceType": "github", + "computedHash": "0e299633b83f579b494e45b91ba2f2c4690caba4a8c26acaaf26d8bd47a2be36" + } + } +} diff --git a/skills/convex-create-component/SKILL.md b/skills/convex-create-component/SKILL.md new file mode 100644 index 00000000..effe01fa --- /dev/null +++ b/skills/convex-create-component/SKILL.md @@ -0,0 +1,411 @@ +--- +name: convex-create-component +description: Design and build Convex components with clear boundaries, isolated state, and app-facing wrappers. Use when creating a new Convex component, extracting reusable backend logic into one, or packaging Convex functionality for reuse across apps. +--- + +# Convex Create Component + +Create reusable Convex components with clear boundaries and a small app-facing API. + +## When to Use + +- Creating a new Convex component in an existing app +- Extracting reusable backend logic into a component +- Building a third-party integration that should own its own tables and workflows +- Packaging Convex functionality for reuse across multiple apps + +## When Not to Use + +- One-off business logic that belongs in the main app +- Thin utilities that do not need Convex tables or functions +- App-level orchestration that should stay in `convex/` +- Cases where a normal TypeScript library is enough + +## Workflow + +1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding. +2. Choose the shape using the decision tree below and read the matching reference file. +3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state. +4. Make a short plan for: + - what tables the component owns + - what public functions it exposes + - what data must be passed in from the app (auth, env vars, parent IDs) + - what stays in the app as wrappers or HTTP mounts +5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files. +6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files. +7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it. +8. Call the component from the app through `components.` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`. +9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly. +10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing. + +## Choose the Shape + +Ask the user, then pick one path: + +| Goal | Shape | Reference | +|------|-------|-----------| +| Component for this app only | Local | `references/local-components.md` | +| Publish or share across apps | Packaged | `references/packaged-components.md` | +| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` | +| Not sure | Default to local | `references/local-components.md` | + +Read exactly one reference file before proceeding. + +## Default Approach + +Unless the user explicitly wants an npm package, default to a local component: + +- Put it under `convex/components//` +- Define it with `defineComponent(...)` in its own `convex.config.ts` +- Install it from the app's `convex/convex.config.ts` with `app.use(...)` +- Let `npx convex dev` generate the component's own `_generated/` files + +## Component Skeleton + +A minimal local component with a table and two functions, plus the app wiring. + +```ts +// convex/components/notifications/convex.config.ts +import { defineComponent } from "convex/server"; + +export default defineComponent("notifications"); +``` + +```ts +// convex/components/notifications/schema.ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + notifications: defineTable({ + userId: v.string(), + message: v.string(), + read: v.boolean(), + }).index("by_user", ["userId"]), +}); +``` + +```ts +// convex/components/notifications/lib.ts +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server.js"; + +export const send = mutation({ + args: { userId: v.string(), message: v.string() }, + returns: v.id("notifications"), + handler: async (ctx, args) => { + return await ctx.db.insert("notifications", { + userId: args.userId, + message: args.message, + read: false, + }); + }, +}); + +export const listUnread = query({ + args: { userId: v.string() }, + returns: v.array( + v.object({ + _id: v.id("notifications"), + _creationTime: v.number(), + userId: v.string(), + message: v.string(), + read: v.boolean(), + }) + ), + handler: async (ctx, args) => { + return await ctx.db + .query("notifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .filter((q) => q.eq(q.field("read"), false)) + .collect(); + }, +}); +``` + +```ts +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import notifications from "./components/notifications/convex.config.js"; + +const app = defineApp(); +app.use(notifications); + +export default app; +``` + +```ts +// convex/notifications.ts (app-side wrapper) +import { v } from "convex/values"; +import { mutation, query } from "./_generated/server"; +import { components } from "./_generated/api"; +import { getAuthUserId } from "@convex-dev/auth/server"; + +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); + +export const myUnread = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + return await ctx.runQuery(components.notifications.lib.listUnread, { + userId, + }); + }, +}); +``` + +Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app. + +## Critical Rules + +- Keep authentication in the app. `ctx.auth` is not available inside components. +- Keep environment access in the app. Component functions cannot read `process.env`. +- Pass parent app IDs across the boundary as strings. `Id` types become plain strings in the app-facing `ComponentApi`. +- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema. +- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`. +- Do not expose component functions directly to clients. Create app wrappers when client access is needed. +- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`. +- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`. +- Add `args` and `returns` validators to all public component functions. + +## Patterns + +### Authentication and environment access + +```ts +// Bad: component code cannot rely on app auth or env +const identity = await ctx.auth.getUserIdentity(); +const apiKey = process.env.OPENAI_API_KEY; +``` + +```ts +// Good: the app resolves auth and env, then passes explicit values +const userId = await getAuthUserId(ctx); +if (!userId) throw new Error("Not authenticated"); + +await ctx.runAction(components.translator.translate, { + userId, + apiKey: process.env.OPENAI_API_KEY, + text: args.text, +}); +``` + +### Client-facing API + +```ts +// Bad: assuming a component function is directly callable by clients +export const send = components.notifications.send; +``` + +```ts +// Good: re-export through an app mutation or query +export const sendNotification = mutation({ + args: { message: v.string() }, + returns: v.null(), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + + await ctx.runMutation(components.notifications.lib.send, { + userId, + message: args.message, + }); + return null; + }, +}); +``` + +### IDs across the boundary + +```ts +// Bad: parent app table IDs are not valid component validators +args: { userId: v.id("users") } +``` + +```ts +// Good: treat parent-owned IDs as strings at the boundary +args: { userId: v.string() } +``` + +### Function Handles for callbacks + +When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow. + +```ts +// App side: create a handle and pass it to the component +import { createFunctionHandle } from "convex/server"; + +export const startJob = mutation({ + handler: async (ctx) => { + const handle = await createFunctionHandle(internal.myModule.processItem); + await ctx.runMutation(components.workpool.enqueue, { + callback: handle, + }); + }, +}); +``` + +```ts +// Component side: accept and invoke the handle +import { v } from "convex/values"; +import type { FunctionHandle } from "convex/server"; +import { mutation } from "./_generated/server.js"; + +export const enqueue = mutation({ + args: { callback: v.string() }, + handler: async (ctx, args) => { + const handle = args.callback as FunctionHandle<"mutation">; + await ctx.scheduler.runAfter(0, handle, {}); + }, +}); +``` + +### Deriving validators from schema + +Instead of manually repeating field types in return validators, extend the schema validator: + +```ts +import { v } from "convex/values"; +import schema from "./schema.js"; + +const notificationDoc = schema.tables.notifications.validator.extend({ + _id: v.id("notifications"), + _creationTime: v.number(), +}); + +export const getLatest = query({ + args: {}, + returns: v.nullable(notificationDoc), + handler: async (ctx) => { + return await ctx.db.query("notifications").order("desc").first(); + }, +}); +``` + +### Static configuration with a globals table + +A common pattern for component configuration is a single-document "globals" table: + +```ts +// schema.ts +export default defineSchema({ + globals: defineTable({ + maxRetries: v.number(), + webhookUrl: v.optional(v.string()), + }), + // ... other tables +}); +``` + +```ts +// lib.ts +export const configure = mutation({ + args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, args) => { + const existing = await ctx.db.query("globals").first(); + if (existing) { + await ctx.db.patch(existing._id, args); + } else { + await ctx.db.insert("globals", args); + } + return null; + }, +}); +``` + +### Class-based client wrappers + +For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components. + +```ts +// src/client/index.ts +import type { GenericMutationCtx, GenericDataModel } from "convex/server"; +import type { ComponentApi } from "../component/_generated/component.js"; + +type MutationCtx = Pick, "runMutation">; + +export class Notifications { + constructor( + private component: ComponentApi, + private options?: { defaultChannel?: string }, + ) {} + + async send(ctx: MutationCtx, args: { userId: string; message: string }) { + return await ctx.runMutation(this.component.lib.send, { + ...args, + channel: this.options?.defaultChannel ?? "default", + }); + } +} +``` + +```ts +// App usage +import { Notifications } from "@convex-dev/notifications"; +import { components } from "./_generated/api"; + +const notifications = new Notifications(components.notifications, { + defaultChannel: "alerts", +}); + +export const send = mutation({ + args: { message: v.string() }, + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + await notifications.send(ctx, { userId, message: args.message }); + }, +}); +``` + +## Validation + +Try validation in this order: + +1. `npx convex codegen --component-dir convex/components/` +2. `npx convex codegen` +3. `npx convex dev` + +Important: + +- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured. +- Until codegen runs, component-local `./_generated/*` imports and app-side `components....` references will not typecheck. +- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing. + +## Reference Files + +Read exactly one of these after the user confirms the goal: + +- `references/local-components.md` +- `references/packaged-components.md` +- `references/hybrid-components.md` + +Official docs: [Authoring Components](https://docs.convex.dev/components/authoring) + +## Checklist + +- [ ] Asked the user what they want to build and confirmed the shape +- [ ] Read the matching reference file +- [ ] Confirmed a component is the right abstraction +- [ ] Planned tables, public API, boundaries, and app wrappers +- [ ] Component lives under `convex/components//` (or package layout if publishing) +- [ ] Component imports from its own `./_generated/server` +- [ ] Auth, env access, and HTTP routes stay in the app +- [ ] Parent app IDs cross the boundary as `v.string()` +- [ ] Public functions have `args` and `returns` validators +- [ ] Ran `npx convex dev` and fixed codegen or type issues diff --git a/skills/convex-create-component/agents/openai.yaml b/skills/convex-create-component/agents/openai.yaml new file mode 100644 index 00000000..ba9287e4 --- /dev/null +++ b/skills/convex-create-component/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Create Component" + short_description: "Design and build reusable Convex components with clear boundaries." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#14B8A6" + default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it." + +policy: + allow_implicit_invocation: true diff --git a/skills/convex-create-component/assets/icon.svg b/skills/convex-create-component/assets/icon.svg new file mode 100644 index 00000000..10f4c2c4 --- /dev/null +++ b/skills/convex-create-component/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/skills/convex-create-component/references/hybrid-components.md b/skills/convex-create-component/references/hybrid-components.md new file mode 100644 index 00000000..d2bb3514 --- /dev/null +++ b/skills/convex-create-component/references/hybrid-components.md @@ -0,0 +1,37 @@ +# Hybrid Convex Components + +Read this file only when the user explicitly wants a hybrid setup. + +## What This Means + +A hybrid component combines a local Convex component with shared library code. + +This can help when: + +- the user wants a local install but also shared package logic +- the component needs extension points or override hooks +- some logic should live in normal TypeScript code outside the component boundary + +## Default Advice + +Treat hybrid as an advanced option, not the default. + +Before choosing it, ask: + +- Why is a plain local component not enough? +- Why is a packaged component not enough? +- What exactly needs to stay overridable or shared? + +If the answer is vague, fall back to local or packaged. + +## Risks + +- More moving parts +- Harder upgrades and backwards compatibility +- Easier to blur the component boundary + +## Checklist + +- [ ] User explicitly needs hybrid behavior +- [ ] Local-only and packaged-only options were considered first +- [ ] The extension points are clearly defined before coding diff --git a/skills/convex-create-component/references/local-components.md b/skills/convex-create-component/references/local-components.md new file mode 100644 index 00000000..7fbfe21a --- /dev/null +++ b/skills/convex-create-component/references/local-components.md @@ -0,0 +1,38 @@ +# Local Convex Components + +Read this file when the component should live inside the current app and does not need to be published as an npm package. + +## When to Choose This + +- The user wants the simplest path +- The component only needs to work in this repo +- The goal is extracting app logic into a cleaner boundary + +## Default Layout + +Use this structure unless the repo already has a clear alternative pattern: + +```text +convex/ + convex.config.ts + components/ + / + convex.config.ts + schema.ts + .ts +``` + +## Workflow Notes + +- Define the component with `defineComponent("")` +- Install it from the app with `defineApp()` and `app.use(...)` +- Keep auth, env access, public API wrappers, and HTTP route mounting in the app +- Let the component own isolated tables and reusable backend workflows +- Add app wrappers if clients need to call into the component + +## Checklist + +- [ ] Component is inside `convex/components//` +- [ ] App installs it with `app.use(...)` +- [ ] Component owns only its own tables +- [ ] App wrappers handle client-facing calls when needed diff --git a/skills/convex-create-component/references/packaged-components.md b/skills/convex-create-component/references/packaged-components.md new file mode 100644 index 00000000..5668e7ed --- /dev/null +++ b/skills/convex-create-component/references/packaged-components.md @@ -0,0 +1,51 @@ +# Packaged Convex Components + +Read this file when the user wants a reusable npm package or a component shared across multiple apps. + +## When to Choose This + +- The user wants to publish the component +- The user wants a stable reusable package boundary +- The component will be shared across multiple apps or teams + +## Default Approach + +- Prefer starting from `npx create-convex@latest --component` when possible +- Keep the official authoring docs as the source of truth for package layout and exports +- Validate the bundled package through an example app, not just the source files + +## Build Flow + +When building a packaged component, make sure the bundled output exists before the example app tries to consume it. + +Recommended order: + +1. `npx convex codegen --component-dir ./path/to/component` +2. Run the package build command +3. Run `npx convex dev --typecheck-components` in the example app + +Do not assume normal app codegen is enough for packaged component workflows. + +## Package Exports + +If publishing to npm, make sure the package exposes the entry points apps need: + +- package root for client helpers, types, or classes +- `./convex.config.js` for installing the component +- `./_generated/component.js` for the app-facing `ComponentApi` type +- `./test` for testing helpers when applicable + +## Testing + +- Use `convex-test` for component logic +- Register the component schema and modules with the test instance +- Test app-side wrapper code from an example app that installs the package +- Export a small helper from `./test` if consumers need easy test registration + +## Checklist + +- [ ] Packaging is actually required +- [ ] Build order avoids bundle and codegen races +- [ ] Package exports include install and typing entry points +- [ ] Example app exercises the packaged component +- [ ] Core behavior is covered by tests diff --git a/skills/convex-migration-helper/SKILL.md b/skills/convex-migration-helper/SKILL.md new file mode 100644 index 00000000..f353678f --- /dev/null +++ b/skills/convex-migration-helper/SKILL.md @@ -0,0 +1,524 @@ +--- +name: convex-migration-helper +description: Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. +--- + +# Convex Migration Helper + +Safely migrate Convex schemas and data when making breaking changes. + +## When to Use + +- Adding new required fields to existing tables +- Changing field types or structure +- Splitting or merging tables +- Renaming or deleting fields +- Migrating from nested to relational data + +## Key Concepts + +### Schema Validation Drives the Workflow + +Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration: + +- You cannot add a required field if existing documents don't have it +- You cannot change a field's type if existing documents have the old type +- You cannot remove a field from the schema if existing documents still have it + +This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**. + +### Online Migrations + +Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats. + +### Prefer New Fields Over Changing Types + +When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back. + +### Don't Delete Data + +Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed. + +## Safe Changes (No Migration Needed) + +### Adding Optional Field + +```typescript +// Before +users: defineTable({ + name: v.string(), +}) + +// After - safe, new field is optional +users: defineTable({ + name: v.string(), + bio: v.optional(v.string()), +}) +``` + +### Adding New Table + +```typescript +posts: defineTable({ + userId: v.id("users"), + title: v.string(), +}).index("by_user", ["userId"]) +``` + +### Adding Index + +```typescript +users: defineTable({ + name: v.string(), + email: v.string(), +}) + .index("by_email", ["email"]) +``` + +## Breaking Changes: The Deployment Workflow + +Every breaking migration follows the same multi-deploy pattern: + +**Deploy 1 - Widen the schema:** + +1. Update schema to allow both old and new formats (e.g., add optional new field) +2. Update code to handle both formats when reading +3. Update code to write the new format for new documents +4. Deploy + +**Between deploys - Migrate data:** + +5. Run migration to backfill existing documents +6. Verify all documents are migrated + +**Deploy 2 - Narrow the schema:** + +7. Update schema to require the new format only +8. Remove code that handles the old format +9. Deploy + +## Using the Migrations Component (Recommended) + +For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring. + +### Installation + +```bash +npm install @convex-dev/migrations +``` + +### Setup + +```typescript +// convex/convex.config.ts +import { defineApp } from "convex/server"; +import migrations from "@convex-dev/migrations/convex.config.js"; + +const app = defineApp(); +app.use(migrations); +export default app; +``` + +```typescript +// convex/migrations.ts +import { Migrations } from "@convex-dev/migrations"; +import { components } from "./_generated/api.js"; +import { DataModel } from "./_generated/dataModel.js"; + +export const migrations = new Migrations(components.migrations); +export const run = migrations.runner(); +``` + +The `DataModel` type parameter is optional but provides type safety for migration definitions. + +### Define a Migration + +The `migrateOne` function processes a single document. The component handles batching and pagination automatically. + +```typescript +// convex/migrations.ts +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); +``` + +Shorthand: if you return an object, it is applied as a patch automatically. + +```typescript +export const clearDeprecatedField = migrations.define({ + table: "users", + migrateOne: () => ({ legacyField: undefined }), +}); +``` + +### Run a Migration + +From the CLI: + +```bash +# Define a one-off runner in convex/migrations.ts: +# export const runIt = migrations.runner(internal.migrations.addDefaultRole); +npx convex run migrations:runIt + +# Or use the general-purpose runner +npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}' +``` + +Programmatically from another Convex function: + +```typescript +await migrations.runOne(ctx, internal.migrations.addDefaultRole); +``` + +### Run Multiple Migrations in Order + +```typescript +export const runAll = migrations.runner([ + internal.migrations.addDefaultRole, + internal.migrations.clearDeprecatedField, + internal.migrations.normalizeEmails, +]); +``` + +```bash +npx convex run migrations:runAll +``` + +If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically. + +### Dry Run + +Test a migration before committing changes: + +```bash +npx convex run migrations:runIt '{"dryRun": true}' +``` + +This runs one batch and then rolls back, so you can see what it would do without changing any data. + +### Check Migration Status + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +### Cancel a Running Migration + +```bash +npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}' +``` + +Or programmatically: + +```typescript +await migrations.cancel(ctx, internal.migrations.addDefaultRole); +``` + +### Run Migrations on Deploy + +Chain migration execution after deploying: + +```bash +npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod +``` + +### Configuration Options + +#### Custom Batch Size + +If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts: + +```typescript +export const migrateHeavyTable = migrations.define({ + table: "largeDocuments", + batchSize: 10, + migrateOne: async (ctx, doc) => { + // migration logic + }, +}); +``` + +#### Migrate a Subset Using an Index + +Process only matching documents instead of the full table: + +```typescript +export const fixEmptyNames = migrations.define({ + table: "users", + customRange: (query) => + query.withIndex("by_name", (q) => q.eq("name", "")), + migrateOne: () => ({ name: "" }), +}); +``` + +#### Parallelize Within a Batch + +By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering: + +```typescript +export const clearField = migrations.define({ + table: "myTable", + parallelize: true, + migrateOne: () => ({ optionalField: undefined }), +}); +``` + +## Common Migration Patterns + +### Adding a Required Field + +```typescript +// Deploy 1: Schema allows both states +users: defineTable({ + name: v.string(), + role: v.optional(v.union(v.literal("user"), v.literal("admin"))), +}) + +// Migration: backfill the field +export const addDefaultRole = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.role === undefined) { + await ctx.db.patch(user._id, { role: "user" }); + } + }, +}); + +// Deploy 2: After migration completes, make it required +users: defineTable({ + name: v.string(), + role: v.union(v.literal("user"), v.literal("admin")), +}) +``` + +### Deleting a Field + +Mark the field optional first, migrate data to remove it, then remove from schema: + +```typescript +// Deploy 1: Make optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()) + +// Migration +export const removeIsPro = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.isPro !== undefined) { + await ctx.db.patch(team._id, { isPro: undefined }); + } + }, +}); + +// Deploy 2: Remove isPro from schema entirely +``` + +### Changing a Field Type + +Prefer creating a new field. You can combine adding and deleting in one migration: + +```typescript +// Deploy 1: Add new field, keep old field optional +// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...) + +// Migration: convert old field to new field +export const convertToEnum = migrations.define({ + table: "teams", + migrateOne: async (ctx, team) => { + if (team.plan === undefined) { + await ctx.db.patch(team._id, { + plan: team.isPro ? "pro" : "basic", + isPro: undefined, + }); + } + }, +}); + +// Deploy 2: Remove isPro from schema, make plan required +``` + +### Splitting Nested Data Into a Separate Table + +```typescript +export const extractPreferences = migrations.define({ + table: "users", + migrateOne: async (ctx, user) => { + if (user.preferences === undefined) return; + + const existing = await ctx.db + .query("userPreferences") + .withIndex("by_user", (q) => q.eq("userId", user._id)) + .first(); + + if (!existing) { + await ctx.db.insert("userPreferences", { + userId: user._id, + ...user.preferences, + }); + } + + await ctx.db.patch(user._id, { preferences: undefined }); + }, +}); +``` + +Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window. + +### Cleaning Up Orphaned Documents + +```typescript +export const deleteOrphanedEmbeddings = migrations.define({ + table: "embeddings", + migrateOne: async (ctx, doc) => { + const chunk = await ctx.db + .query("chunks") + .withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id)) + .first(); + + if (!chunk) { + await ctx.db.delete(doc._id); + } + }, +}); +``` + +## Migration Strategies for Zero Downtime + +During the migration window, your app must handle both old and new data formats. There are two main strategies. + +### Dual Write (Preferred) + +Write to both old and new structures. Read from the old structure until migration is complete. + +1. Deploy code that writes both formats, reads old format +2. Run migration on existing data +3. Deploy code that reads new format, still writes both +4. Deploy code that only reads and writes new format + +This is preferred because you can safely roll back at any point, the old format is always up to date. + +```typescript +// Bad: only writing to new structure before migration is done +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + await ctx.db.insert("teams", { + name: args.name, + plan: args.isPro ? "pro" : "basic", + }); + }, +}); + +// Good: writing to both structures during migration +export const createTeam = mutation({ + args: { name: v.string(), isPro: v.boolean() }, + handler: async (ctx, args) => { + const plan = args.isPro ? "pro" : "basic"; + await ctx.db.insert("teams", { + name: args.name, + isPro: args.isPro, + plan, + }); + }, +}); +``` + +### Dual Read + +Read both formats. Write only the new format. + +1. Deploy code that reads both formats (preferring new), writes only new format +2. Run migration on existing data +3. Deploy code that reads and writes only new format + +This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format. + +```typescript +// Good: reading both formats, preferring new +function getTeamPlan(team: Doc<"teams">): "basic" | "pro" { + if (team.plan !== undefined) return team.plan; + return team.isPro ? "pro" : "basic"; +} +``` + +## Small Table Shortcut + +For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component: + +```typescript +import { internalMutation } from "./_generated/server"; + +export const backfillSmallTable = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("smallConfig").collect(); + for (const doc of docs) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: "default" }); + } + } + }, +}); +``` + +```bash +npx convex run migrations:backfillSmallTable +``` + +Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component. + +## Verifying a Migration + +Query to check remaining unmigrated documents: + +```typescript +import { query } from "./_generated/server"; + +export const verifyMigration = query({ + handler: async (ctx) => { + const remaining = await ctx.db + .query("users") + .filter((q) => q.eq(q.field("role"), undefined)) + .take(10); + + return { + complete: remaining.length === 0, + sampleRemaining: remaining.map((u) => u._id), + }; + }, +}); +``` + +Or use the component's built-in status monitoring: + +```bash +npx convex run --component migrations lib:getStatus --watch +``` + +## Migration Checklist + +- [ ] Identify the breaking change and plan the multi-deploy workflow +- [ ] Update schema to allow both old and new formats +- [ ] Update code to handle both formats when reading +- [ ] Update code to write the new format for new documents +- [ ] Deploy widened schema and updated code +- [ ] Define migration using the `@convex-dev/migrations` component +- [ ] Test with `dryRun: true` +- [ ] Run migration and monitor status +- [ ] Verify all documents are migrated +- [ ] Update schema to require new format only +- [ ] Clean up code that handled old format +- [ ] Deploy final schema and code +- [ ] Remove migration code once confirmed stable + +## Common Pitfalls + +1. **Don't make a field required before migrating data**: Convex will reject the deploy. Always widen the schema first. +2. **Don't `.collect()` large tables**: Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small. +3. **Don't forget to write the new format before migrating**: If your code doesn't write the new format for new documents, documents created during the migration window will be missed. +4. **Don't skip the dry run**: Use `dryRun: true` to validate your migration logic before committing changes to production data. +5. **Don't delete fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed. +6. **Don't use crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove. diff --git a/skills/convex-migration-helper/agents/openai.yaml b/skills/convex-migration-helper/agents/openai.yaml new file mode 100644 index 00000000..c2a7fcc5 --- /dev/null +++ b/skills/convex-migration-helper/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Migration Helper" + short_description: "Plan and run safe Convex schema and data migrations." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#8B5CF6" + default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits." + +policy: + allow_implicit_invocation: true diff --git a/skills/convex-migration-helper/assets/icon.svg b/skills/convex-migration-helper/assets/icon.svg new file mode 100644 index 00000000..fba7241a --- /dev/null +++ b/skills/convex-migration-helper/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/skills/convex-performance-audit/SKILL.md b/skills/convex-performance-audit/SKILL.md new file mode 100644 index 00000000..6ee0417f --- /dev/null +++ b/skills/convex-performance-audit/SKILL.md @@ -0,0 +1,143 @@ +--- +name: convex-performance-audit +description: Audit and optimize Convex application performance, covering hot path reads, write contention, subscription cost, and function limits. Use when a Convex feature is slow, reads too much data, writes too often, has OCC conflicts, or needs performance investigation. +--- + +# Convex Performance Audit + +Diagnose and fix performance problems in Convex applications, one problem class at a time. + +## When to Use + +- A Convex page or feature feels slow or expensive +- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts +- Low-freshness read paths are using reactivity where point-in-time reads would do +- OCC conflict errors or excessive mutation retries +- High subscription count or slow UI updates +- Functions approaching execution or transaction limits +- The same performance pattern needs fixing across sibling functions + +## When Not to Use + +- Initial Convex setup, auth setup, or component extraction +- Pure schema migrations with no performance goal +- One-off micro-optimizations without a user-visible or deployment-visible problem + +## Guardrails + +- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak +- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path +- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale + +## First Step: Gather Signals + +Start with the strongest signal available: + +1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals. +2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed. + - If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up. +3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth. +4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted. + +## Signal Routing + +After gathering signals, identify the problem class and read the matching reference file. + +| Signal | Reference | +|---|---| +| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` | +| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` | +| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` | +| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` | +| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` | + +Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain. + +## Escalate Larger Fixes + +If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing. + +Examples: + +- introducing digest or summary tables across multiple flows +- splitting documents to isolate frequently-updated fields +- reworking pagination or fetch strategy across several screens +- switching to a new index or denormalized field that needs migration-safe rollout + +When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow. + +## Workflow + +### 1. Scope the problem + +Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom. + +Write down: + +- entrypoint functions +- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation` +- tables read +- tables written +- whether the path is high-read, high-write, or both + +### 2. Trace the full read and write set + +For each function in the path: + +1. Trace every `ctx.db.get()` and `ctx.db.query()` +2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()` +3. Note foreign-key lookups, JS-side filtering, and full-document reads +4. Identify all sibling functions touching the same tables +5. Identify reactive stats, aggregates, or widgets rendered on the same page + +In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems. + +### 3. Apply fixes from the relevant reference + +Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order. + +Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables. + +### 4. Fix sibling functions together + +When one function touching a table has a performance bug, audit sibling functions for the same pattern. + +After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables. + +Examples: + +- If one list query switches from full docs to a digest table, inspect the other list queries for that table +- If one mutation needs no-op write protection, inspect the other writers to the same table +- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk + +Do not leave one path fixed and another path on the old pattern unless there is a clear product reason. + +### 5. Verify before finishing + +Confirm all of these: + +1. Results are the same as before, no dropped records +2. Eliminated reads or writes are no longer in the path where expected +3. Fallback behavior works when denormalized or indexed fields are missing +4. New writes avoid unnecessary invalidation when data is unchanged +5. Every relevant sibling reader and writer was inspected, not just the original function + +## Reference Files + +- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables +- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting +- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads +- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size + +Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit. + +## Checklist + +- [ ] Gathered signals from insights, dashboard, or code audit +- [ ] Identified the problem class and read the matching reference +- [ ] Scoped one concrete user flow or function path +- [ ] Traced every read and write in that path +- [ ] Identified sibling functions touching the same tables +- [ ] Applied fixes from the reference, following the recommended fix order +- [ ] Fixed sibling functions consistently +- [ ] Verified behavior and confirmed no regressions diff --git a/skills/convex-performance-audit/agents/openai.yaml b/skills/convex-performance-audit/agents/openai.yaml new file mode 100644 index 00000000..9a21f387 --- /dev/null +++ b/skills/convex-performance-audit/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Performance Audit" + short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#EF4444" + default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes." + +policy: + allow_implicit_invocation: true diff --git a/skills/convex-performance-audit/assets/icon.svg b/skills/convex-performance-audit/assets/icon.svg new file mode 100644 index 00000000..7ab9e09c --- /dev/null +++ b/skills/convex-performance-audit/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/skills/convex-performance-audit/references/function-budget.md b/skills/convex-performance-audit/references/function-budget.md new file mode 100644 index 00000000..c71d14cb --- /dev/null +++ b/skills/convex-performance-audit/references/function-budget.md @@ -0,0 +1,232 @@ +# Function Budget + +Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client. + +## Core Principle + +Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention. + +## Limits to Know + +These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers. + +| Resource | Limit | +|---|---| +| Query/mutation execution time | 1 second (user code only, excludes DB operations) | +| Action execution time | 10 minutes | +| Data read per transaction | 16 MiB | +| Data written per transaction | 16 MiB | +| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) | +| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) | +| Documents written per transaction | 16,000 | +| Individual document size | 1 MiB | +| Function return value size | 16 MiB | + +## Symptoms + +- "Function execution took too long" errors +- "Transaction too large" or read/write set size errors +- Slow queries that read many documents +- Client receiving large payloads that slow down page load +- `npx convex insights --details` showing high bytes read + +## Common Causes + +### Unbounded collection + +A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents. + +### Large document reads on hot paths + +Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view. + +### Mutation doing too much work + +A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction. + +### Returning too much data to the client + +A query returning full documents when the client only needs a few fields. + +## Fix Order + +### 1. Bound your reads + +Never `.collect()` without a limit on a table that can grow unbounded. + +```ts +// Bad: unbounded read, breaks as the table grows +const messages = await ctx.db.query("messages").collect(); +``` + +```ts +// Good: paginate or limit +const messages = await ctx.db + .query("messages") + .withIndex("by_channel", (q) => q.eq("channelId", channelId)) + .order("desc") + .take(50); +``` + +### 2. Read smaller shapes + +If the list page only needs title, author, and date, do not read full documents with rich content fields. + +Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern. + +### 3. Break large mutations into batches + +If a mutation needs to update hundreds of documents, split it into a self-scheduling chain. + +```ts +// Bad: one mutation updating every row +export const backfillAll = internalMutation({ + handler: async (ctx) => { + const docs = await ctx.db.query("items").collect(); + for (const doc of docs) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + }, +}); +``` + +```ts +// Good: cursor-based batch processing +export const backfillBatch = internalMutation({ + args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) }, + handler: async (ctx, args) => { + const batchSize = args.batchSize ?? 100; + const result = await ctx.db + .query("items") + .paginate({ cursor: args.cursor ?? null, numItems: batchSize }); + + for (const doc of result.page) { + if (doc.newField === undefined) { + await ctx.db.patch(doc._id, { newField: computeValue(doc) }); + } + } + + if (!result.isDone) { + await ctx.scheduler.runAfter(0, internal.items.backfillBatch, { + cursor: result.continueCursor, + batchSize, + }); + } + }, +}); +``` + +### 4. Move heavy work to actions + +Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead. + +Actions run outside the transaction and can call mutations to write results back. + +```ts +// Bad: heavy computation inside a mutation +export const processUpload = mutation({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.db.insert("results", result); + }, +}); +``` + +```ts +// Good: action for heavy work, mutation for the write +export const processUpload = action({ + handler: async (ctx, args) => { + const result = expensiveComputation(args.data); + await ctx.runMutation(internal.results.store, { result }); + }, +}); +``` + +### 5. Trim return values + +Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning. + +```ts +// Bad: returns full documents including large content fields +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("articles").take(20); + }, +}); +``` + +```ts +// Good: project to only the fields the client needs +export const list = query({ + handler: async (ctx) => { + const articles = await ctx.db.query("articles").take(20); + return articles.map((a) => ({ + _id: a._id, + title: a.title, + author: a.author, + createdAt: a._creationTime, + })); + }, +}); +``` + +### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions + +Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost. + +```ts +// Bad: unnecessary overhead from ctx.runQuery inside a mutation +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await ctx.runQuery(api.users.getCurrentUser); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +```ts +// Good: plain helper function, no extra overhead +export const createProject = mutation({ + handler: async (ctx, args) => { + const user = await getCurrentUser(ctx); + await ctx.db.insert("projects", { ...args, ownerId: user._id }); + }, +}); +``` + +Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else. + +### 7. Avoid unnecessary `runAction` calls + +`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime). + +```ts +// Bad: runAction overhead for no reason +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await ctx.runAction(internal.items.processOne, { item }); + } + }, +}); +``` + +```ts +// Good: plain function call +export const processItems = action({ + handler: async (ctx, args) => { + for (const item of args.items) { + await processOneItem(ctx, { item }); + } + }, +}); +``` + +## Verification + +1. No function execution or transaction size errors +2. `npx convex insights --details` shows reduced bytes read +3. Large mutations are batched and self-scheduling +4. Client payloads are reasonably sized for the UI they serve +5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible +6. Sibling functions with similar patterns were checked diff --git a/skills/convex-performance-audit/references/hot-path-rules.md b/skills/convex-performance-audit/references/hot-path-rules.md new file mode 100644 index 00000000..96a7b94e --- /dev/null +++ b/skills/convex-performance-audit/references/hot-path-rules.md @@ -0,0 +1,359 @@ +# Hot Path Rules + +Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes. + +## Core Principle + +Every byte read or written multiplies with concurrency. + +Think: + +`cost x calls_per_second x 86400` + +In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync. + +## Consistency Rule + +If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern. + +Do this especially for: + +- multiple list queries over the same table +- multiple writers to the same table +- public browse and search queries over the same records +- helper functions reused by more than one endpoint + +## 1. Push Filters To Storage + +Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned. + +Prefer: + +- `withIndex(...)` +- `.withSearchIndex(...)` for text search +- narrower tables +- summary tables + +before accepting a scan-plus-filter pattern. + +```ts +// Bad: scans then filters in JavaScript +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + const tasks = await ctx.db.query("tasks").collect(); + return tasks.filter((task) => task.status === "open"); + }, +}); +``` + +```ts +// Also bad: Convex .filter() does not push to storage either +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .filter((q) => q.eq(q.field("status"), "open")) + .collect(); + }, +}); +``` + +```ts +// Good: use an index so storage does the filtering +export const listOpen = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db + .query("tasks") + .withIndex("by_status", (q) => q.eq("status", "open")) + .collect(); + }, +}); +``` + +### Migration rule for indexes + +New indexes on partially backfilled fields can create correctness bugs during rollout. + +Important Convex detail: + +`undefined !== false` + +If an older document is missing a field entirely, it will not match a compound index entry that expects `false`. + +Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify. + +If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`. + +```ts +// Bad: optional booleans can miss older rows where the field is undefined +const projects = await ctx.db + .query("projects") + .withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false)) + .order("desc") + .take(20); +``` + +```ts +// Good: switch hot-path reads only after the rollout is migration-safe +// See the migration helper skill for dual-read / backfill / cutover patterns. +``` + +### Check for redundant indexes + +Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete. + +```ts +// Bad: two indexes where one would do +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team", ["team"]) + .index("by_team_and_user", ["team", "user"]) +``` + +```ts +// Good: single compound index serves both query patterns +defineTable({ team: v.id("teams"), user: v.id("users") }) + .index("by_team_and_user", ["team", "user"]) +``` + +Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first. + +## 2. Minimize Data Sources + +Trace every read. + +If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path. + +### When to denormalize + +Denormalize when all of these are true: + +- the path is hot +- the joined document is much larger than the field you need +- many readers are paying that join cost repeatedly + +Useful mental model: + +`join_cost = rows_per_page x foreign_doc_size x pages_per_second` + +Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not. + +### Fallback rule + +Denormalized data is an optimization. Live data is the correctness path. + +Rules: + +- If the denormalized field is missing or null, fall back to the live read +- Do not show placeholders instead of falling back +- In lookup maps, only include fully populated entries + +```ts +// Bad: missing denormalized data becomes a placeholder and blocks correctness +const ownerName = project.ownerName ?? "Unknown owner"; +``` + +```ts +// Good: denormalized data is an optimization, not the only source of truth +const ownerName = + project.ownerName ?? + (await ctx.db.get(project.ownerId))?.name ?? + null; +``` + +Bad lookup map pattern: + +```ts +const ownersById = { + [project.ownerId]: { ownerName: null }, +}; +``` + +That blocks fallback because the map says "I have data" when it does not. + +Good lookup map pattern: + +```ts +const ownersById = + project.ownerName !== undefined && project.ownerName !== null + ? { [project.ownerId]: { ownerName: project.ownerName } } + : {}; +``` + +### No denormalized copy yet + +Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table. + +If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan. + +Rollout order: + +1. Update schema +2. Update write path +3. Backfill +4. Switch read path + +## 3. Minimize Row Size + +Hot list pages should read the smallest document shape that still answers the UI. + +Prefer summary or digest tables over full source tables when: + +- the list page only needs a subset of fields +- source documents are large +- the query is high volume + +An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page. + +Digest tables are a tradeoff, not a default: + +- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost +- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit + +```ts +// Bad: list page reads source docs, then joins owner data per row +const projects = await ctx.db + .query("projects") + .withIndex("by_public", (q) => q.eq("isPublic", true)) + .collect(); +``` + +```ts +// Good: list page reads the smaller digest shape first +const projects = await ctx.db + .query("projectDigests") + .withIndex("by_public_and_updated", (q) => q.eq("isPublic", true)) + .order("desc") + .take(20); +``` + +## 4. Skip No-Op Writes + +No-op writes still cost work in Convex: + +- invalidation +- replication +- trigger execution +- downstream sync + +Before `patch` or `replace`, compare against the existing document and skip the write if nothing changed. + +Apply this across sibling writers too. One careful writer does not help much if three other mutations still patch unconditionally. + +```ts +// Bad: patching unchanged values still triggers invalidation and downstream work +await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, +}); +``` + +```ts +// Good: only write when something actually changed +if (settings.theme !== args.theme || settings.locale !== args.locale) { + await ctx.db.patch(settings._id, { + theme: args.theme, + locale: args.locale, + }); +} +``` + +## 5. Match Consistency To Read Patterns + +Choose read strategy based on traffic shape. + +### High-read, low-write + +Examples: + +- public browse pages +- search results +- landing pages +- directory listings + +Prefer: + +- point-in-time reads where appropriate +- explicit refresh +- local state for pagination +- caching where appropriate + +Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns. + +### High-read, high-write + +Examples: + +- collaborative editors +- live dashboards +- presence-heavy views + +Reactive queries may be worth the ongoing cost. + +## Convex-Specific Notes + +### Reactive queries + +Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query. + +On the client: + +- `useQuery` creates a live subscription +- `usePaginatedQuery` creates a live subscription per page + +For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically. + +### Point-in-time reads + +Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful. + +Use them for: + +- aggregate snapshots +- reports +- low-churn listings +- pages where explicit refresh is fine + +### Triggers and fan-out + +Triggers fire on every write, including writes that did not materially change the document. + +When a write exists only to keep derived state in sync: + +- diff before patching +- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate + +### Aggregates + +Reactive global counts invalidate frequently on busy tables. + +Prefer: + +- one-shot aggregate fetches +- periodic recomputation +- precomputed summary rows + +for global stats that do not need live updates every second. + +### Backfills + +For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component. + +Deploy code that can handle both states before running the backfill. + +During the gap: + +- writes should populate the new shape +- reads should fall back safely + +## Verification + +Before closing the audit, confirm: + +1. Same results as before, no dropped records +2. The removed table or lookup is no longer in the hot-path read set +3. Tests or validation cover fallback behavior +4. Migration safety is preserved while fields or indexes are unbackfilled +5. Sibling functions were fixed consistently diff --git a/skills/convex-performance-audit/references/occ-conflicts.md b/skills/convex-performance-audit/references/occ-conflicts.md new file mode 100644 index 00000000..a96d0466 --- /dev/null +++ b/skills/convex-performance-audit/references/occ-conflicts.md @@ -0,0 +1,126 @@ +# OCC Conflict Resolution + +Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables. + +## Core Principle + +Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency. + +## Symptoms + +- OCC conflict errors in deployment logs or health page +- Mutations retrying multiple times before succeeding +- User-visible latency spikes on write-heavy pages +- `npx convex insights --details` showing high conflict rates + +## Common Causes + +### Hot documents + +Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record. + +### Broad read sets causing false conflicts + +A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified. + +### Fan-out from triggers or cascading writes + +A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others. + +Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function. + +### Write-then-read chains + +A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up. + +## Fix Order + +### 1. Reduce read set size + +Narrower reads mean fewer false conflicts. + +```ts +// Bad: broad scan creates a wide conflict surface +const allTasks = await ctx.db.query("tasks").collect(); +const mine = allTasks.filter((t) => t.ownerId === userId); +``` + +```ts +// Good: indexed query touches only relevant documents +const mine = await ctx.db + .query("tasks") + .withIndex("by_owner", (q) => q.eq("ownerId", userId)) + .collect(); +``` + +### 2. Split hot documents + +When many writers target the same document, split the contention point. + +```ts +// Bad: every vote increments the same counter document +const counter = await ctx.db.get(pollCounterId); +await ctx.db.patch(pollCounterId, { count: counter!.count + 1 }); +``` + +```ts +// Good: shard the counter across multiple documents, aggregate on read +const shardIndex = Math.floor(Math.random() * SHARD_COUNT); +const shardId = shardIds[shardIndex]; +const shard = await ctx.db.get(shardId); +await ctx.db.patch(shardId, { count: shard!.count + 1 }); +``` + +Aggregate the shards in a query or scheduled job when you need the total. + +### 3. Skip no-op writes + +Writes that do not change data still participate in conflict detection and trigger invalidation. + +```ts +// Bad: patches even when nothing changed +await ctx.db.patch(doc._id, { status: args.status }); +``` + +```ts +// Good: only write when the value actually differs +if (doc.status !== args.status) { + await ctx.db.patch(doc._id, { status: args.status }); +} +``` + +### 4. Move non-critical work to scheduled functions + +If a mutation does primary work plus secondary bookkeeping (analytics, notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set. + +```ts +// Bad: analytics update in the same transaction as the user action +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.db.insert("analytics", { event: "action", userId, ts: Date.now() }); +``` + +```ts +// Good: schedule the bookkeeping so the primary transaction is smaller +await ctx.db.patch(userId, { lastActiveAt: Date.now() }); +await ctx.scheduler.runAfter(0, internal.analytics.recordEvent, { + event: "action", + userId, +}); +``` + +### 5. Combine competing writes + +If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows. + +Do not introduce artificial locks or queues unless the above steps have been tried first. + +## Related: Invalidation Scope + +Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern. + +## Verification + +1. OCC conflict rate has dropped in insights or dashboard +2. Mutation latency is lower and more consistent +3. No data correctness regressions from splitting or scheduling changes +4. Sibling writers to the same hot documents were fixed consistently diff --git a/skills/convex-performance-audit/references/subscription-cost.md b/skills/convex-performance-audit/references/subscription-cost.md new file mode 100644 index 00000000..ae7d1adb --- /dev/null +++ b/skills/convex-performance-audit/references/subscription-cost.md @@ -0,0 +1,252 @@ +# Subscription Cost + +Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes. + +## Core Principle + +Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with: + +`subscriptions x invalidation_frequency x query_cost` + +Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle. + +## Symptoms + +- Dashboard shows high active subscription count +- UI feels sluggish or laggy despite fast individual queries +- React profiling shows frequent re-renders from Convex state +- Pages with many components each running their own `useQuery` +- Paginated lists where every loaded page stays subscribed + +## Common Causes + +### Reactive queries on low-freshness flows + +Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth. + +### Overly broad queries + +A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation. + +### Too many subscriptions per page + +A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor. + +### Paginated queries keeping all pages live + +`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive. + +### Frequently-updated fields on widely-read documents + +A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason. + +## Fix Order + +### 1. Use point-in-time reads when live updates are not valuable + +Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data. + +Consider a point-in-time read instead when all of these are true: + +- the flow is high-read +- the underlying data changes less often than users need to see +- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable + +Possible implementations depend on environment: + +- a server-rendered fetch +- a framework helper like `fetchQuery` +- a point-in-time client read such as `ConvexHttpClient.query()` + +```ts +// Reactive by default when fresh live data matters +function TeamPresence() { + const presence = useQuery(api.teams.livePresence, { teamId }); + return ; +} +``` + +```ts +// Point-in-time read when explicit refresh is acceptable +import { ConvexHttpClient } from "convex/browser"; + +const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL); + +function SnapshotView() { + const [items, setItems] = useState([]); + + useEffect(() => { + client.query(api.items.snapshot).then(setItems); + }, []); + + return ; +} +``` + +Good candidates for point-in-time reads: + +- aggregate snapshots +- reports +- low-churn listings +- flows where explicit refresh is already acceptable + +Keep reactive for: + +- collaborative editing +- live dashboards +- presence-heavy views +- any surface where users expect fresh changes to appear automatically + +### 2. Batch related data into fewer queries + +Instead of N components each fetching their own related data, fetch it in a single query. + +```ts +// Bad: each card fetches its own author +function ProjectCard({ project }: { project: Project }) { + const author = useQuery(api.users.get, { id: project.authorId }); + return ; +} +``` + +```ts +// Good: parent query returns projects with author names included +function ProjectList() { + const projects = useQuery(api.projects.listWithAuthors); + return projects?.map((p) => ( + + )); +} +``` + +This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N. + +This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count. + +### 3. Use skip to avoid unnecessary subscriptions + +The `"skip"` value prevents a subscription from being created when the arguments are not ready. + +```ts +// Bad: subscribes with undefined args, wastes a subscription slot +const profile = useQuery(api.users.getProfile, { userId: selectedId! }); +``` + +```ts +// Good: skip when there is nothing to fetch +const profile = useQuery( + api.users.getProfile, + selectedId ? { userId: selectedId } : "skip", +); +``` + +### 4. Isolate frequently-updated fields into separate documents + +If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes. + +```ts +// Bad: lastSeen lives on the user doc, every heartbeat invalidates +// every query that reads this user +const users = defineTable({ + name: v.string(), + email: v.string(), + lastSeen: v.number(), +}); +``` + +```ts +// Good: lastSeen lives in a separate heartbeat doc +const users = defineTable({ + name: v.string(), + email: v.string(), + heartbeatId: v.id("heartbeats"), +}); + +const heartbeats = defineTable({ + lastSeen: v.number(), +}); +``` + +Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly. + +For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat. + +### 5. Use the aggregate component for counts and sums + +Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table. + +Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively. + +If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables. + +### 6. Narrow query read sets + +Queries that return less data and touch fewer documents invalidate less often. + +```ts +// Bad: returns all fields, invalidates on any field change +export const list = query({ + handler: async (ctx) => { + return await ctx.db.query("projects").collect(); + }, +}); +``` + +```ts +// Good: use a digest table with only the fields the list needs +export const listDigests = query({ + handler: async (ctx) => { + return await ctx.db.query("projectDigests").collect(); + }, +}); +``` + +Writes to fields not in the digest table do not invalidate the digest query. + +### 7. Remove `Date.now()` from queries + +Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed. + +```ts +// Bad: Date.now() defeats query caching and causes frequent re-evaluation +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now())) + .take(100); +``` + +```ts +// Good: use a boolean field updated by a scheduled function +const releasedPosts = await ctx.db + .query("posts") + .withIndex("by_is_released", (q) => q.eq("isReleased", true)) + .take(100); +``` + +If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry. + +### 8. Consider pagination strategy + +For long lists where users scroll through many pages: + +- If the data does not need live updates, use point-in-time fetching with manual "load more" +- If it does need live updates, accept the subscription cost but limit the number of loaded pages +- Consider whether older pages can be unloaded as the user scrolls forward + +### 9. Separate backend cost from UI churn + +If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether. + +Treat this as a UX problem first when: + +- the underlying query is already reasonably cheap +- the complaint is flicker, loading flashes, or re-render churn +- live updates are still desirable once fresh data arrives + +## Verification + +1. Subscription count in dashboard is lower for the affected pages +2. UI responsiveness has improved +3. React profiling shows fewer unnecessary re-renders +4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily +5. Sibling pages with similar patterns were updated consistently diff --git a/skills/convex-quickstart/SKILL.md b/skills/convex-quickstart/SKILL.md new file mode 100644 index 00000000..369a6c9b --- /dev/null +++ b/skills/convex-quickstart/SKILL.md @@ -0,0 +1,337 @@ +--- +name: convex-quickstart +description: Initialize a new Convex project from scratch or add Convex to an existing app. Use when starting a new project with Convex, scaffolding a Convex app, or integrating Convex into an existing frontend. +--- + +# Convex Quickstart + +Set up a working Convex project as fast as possible. + +## When to Use + +- Starting a brand new project with Convex +- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app +- Scaffolding a Convex app for prototyping + +## When Not to Use + +- The project already has Convex installed and `convex/` exists - just start building +- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill + +## Workflow + +1. Determine the starting point: new project or existing app +2. If new project, pick a template and scaffold with `npm create convex@latest` +3. If existing app, install `convex` and wire up the provider +4. Run `npx convex dev` to connect a deployment and start the dev loop +5. Verify the setup works + +## Path 1: New Project (Recommended) + +Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together. + +### Pick a template + +| Template | Stack | +|----------|-------| +| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui | +| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui | +| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui | +| `nextjs-clerk` | Next.js + Clerk auth | +| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui | +| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui | +| `bare` | Convex backend only, no frontend | + +If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes. + +You can also use any GitHub repo as a template: + +```bash +npm create convex@latest my-app -- -t owner/repo +npm create convex@latest my-app -- -t owner/repo#branch +``` + +### Scaffold the project + +Always pass the project name and template flag to avoid interactive prompts: + +```bash +npm create convex@latest my-app -- -t react-vite-shadcn +cd my-app +npm install +``` + +The scaffolding tool creates files but does not run `npm install`, so you must run it yourself. + +To scaffold in the current directory (if it is empty): + +```bash +npm create convex@latest . -- -t react-vite-shadcn +npm install +``` + +### Start the dev loop + +`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly. + +**Ask the user to run this themselves:** + +Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will: +- Create a Convex project and dev deployment +- Write the deployment URL to `.env.local` +- Create the `convex/` directory with generated types +- Watch for changes and sync continuously + +The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`. + +**Exception - cloud agents (Codex, Jules, Devin):** These environments cannot open a browser for login. See the Agent Mode section below for how to run anonymously without user interaction. + +### Start the frontend + +The user should also run the frontend dev server in a separate terminal: + +```bash +npm run dev +``` + +Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`. + +### What you get + +After scaffolding, the project structure looks like: + +``` +my-app/ + convex/ # Backend functions and schema + _generated/ # Auto-generated types (check this into git) + schema.ts # Database schema (if template includes one) + src/ # Frontend code (or app/ for Next.js) + package.json + .env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL +``` + +The template already has: +- `ConvexProvider` wired into the app root +- Correct env var names for the framework +- Tailwind and shadcn/ui ready (for shadcn templates) +- Auth provider configured (for auth templates) + +You are ready to start adding schema, functions, and UI. + +## Path 2: Add Convex to an Existing App + +Use this when the user already has a frontend project and wants to add Convex as the backend. + +### Install + +```bash +npm install convex +``` + +### Initialize and start dev loop + +Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly. + +### Wire up the provider + +The Convex client must wrap the app at the root. The setup varies by framework. + +Create the `ConvexReactClient` at module scope, not inside a component: + +```tsx +// Bad: re-creates the client on every render +function App() { + const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + return ...; +} + +// Good: created once at module scope +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); +function App() { + return ...; +} +``` + +#### React (Vite) + +```tsx +// src/main.tsx +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import App from "./App"; + +const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); + +createRoot(document.getElementById("root")!).render( + + + + + , +); +``` + +#### Next.js (App Router) + +```tsx +// app/ConvexClientProvider.tsx +"use client"; + +import { ConvexProvider, ConvexReactClient } from "convex/react"; +import { ReactNode } from "react"; + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); + +export function ConvexClientProvider({ children }: { children: ReactNode }) { + return {children}; +} +``` + +```tsx +// app/layout.tsx +import { ConvexClientProvider } from "./ConvexClientProvider"; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} +``` + +#### Other frameworks + +For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide: + +- [Vue](https://docs.convex.dev/quickstart/vue) +- [Svelte](https://docs.convex.dev/quickstart/svelte) +- [React Native](https://docs.convex.dev/quickstart/react-native) +- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start) +- [Remix](https://docs.convex.dev/quickstart/remix) +- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs) + +### Environment variables + +The env var name depends on the framework: + +| Framework | Variable | +|-----------|----------| +| Vite | `VITE_CONVEX_URL` | +| Next.js | `NEXT_PUBLIC_CONVEX_URL` | +| Remix | `CONVEX_URL` | +| React Native | `EXPO_PUBLIC_CONVEX_URL` | + +`npx convex dev` writes the correct variable to `.env.local` automatically. + +## Agent Mode (Cloud-Based Agents) + +When running in a cloud-based agent environment (Codex, Jules, Devin, Cursor Background Agents) where you cannot log in interactively, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment. + +Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline: + +```bash +CONVEX_AGENT_MODE=anonymous npx convex dev +``` + +This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment. + +## Verify the Setup + +After setup, confirm everything is working: + +1. The user confirms `npx convex dev` is running without errors +2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts` +3. `.env.local` contains the deployment URL + +## Writing Your First Function + +Once the project is set up, create a schema and a query to verify the full loop works. + +`convex/schema.ts`: + +```ts +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; + +export default defineSchema({ + tasks: defineTable({ + text: v.string(), + completed: v.boolean(), + }), +}); +``` + +`convex/tasks.ts`: + +```ts +import { query, mutation } from "./_generated/server"; +import { v } from "convex/values"; + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("tasks").collect(); + }, +}); + +export const create = mutation({ + args: { text: v.string() }, + handler: async (ctx, args) => { + await ctx.db.insert("tasks", { text: args.text, completed: false }); + }, +}); +``` + +Use in a React component (adjust the import path based on your file location relative to `convex/`): + +```tsx +import { useQuery, useMutation } from "convex/react"; +import { api } from "../convex/_generated/api"; + +function Tasks() { + const tasks = useQuery(api.tasks.list); + const create = useMutation(api.tasks.create); + + return ( +
+ + {tasks?.map((t) =>
{t.text}
)} +
+ ); +} +``` + +## Development vs Production + +Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save. + +When ready to ship, deploy to production: + +```bash +npx convex deploy +``` + +This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development. + +## Next Steps + +- Add authentication: use the `convex-setup-auth` skill +- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas) +- Build components: use the `convex-create-component` skill +- Plan a migration: use the `convex-migration-helper` skill +- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage) +- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling) + +## Checklist + +- [ ] Determined starting point: new project or existing app +- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template +- [ ] If existing app: installed `convex` and wired up the provider +- [ ] User has `npx convex dev` running and connected to a deployment +- [ ] `convex/_generated/` directory exists with types +- [ ] `.env.local` has the deployment URL +- [ ] Verified a basic query/mutation round-trip works diff --git a/skills/convex-quickstart/agents/openai.yaml b/skills/convex-quickstart/agents/openai.yaml new file mode 100644 index 00000000..a51a6d09 --- /dev/null +++ b/skills/convex-quickstart/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Quickstart" + short_description: "Start a new Convex app or add Convex to an existing frontend." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#F97316" + default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works." + +policy: + allow_implicit_invocation: true diff --git a/skills/convex-quickstart/assets/icon.svg b/skills/convex-quickstart/assets/icon.svg new file mode 100644 index 00000000..d83a73f3 --- /dev/null +++ b/skills/convex-quickstart/assets/icon.svg @@ -0,0 +1,4 @@ + diff --git a/skills/convex-setup-auth/SKILL.md b/skills/convex-setup-auth/SKILL.md new file mode 100644 index 00000000..5c0c994a --- /dev/null +++ b/skills/convex-setup-auth/SKILL.md @@ -0,0 +1,113 @@ +--- +name: convex-setup-auth +description: Set up Convex authentication with proper user management, identity mapping, and access control patterns. Use when implementing auth flows. +--- + +# Convex Authentication Setup + +Implement secure authentication in Convex with user management and access control. + +## When to Use + +- Setting up authentication for the first time +- Implementing user management (users table, identity mapping) +- Creating authentication helper functions +- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT) + +## First Step: Choose the Auth Provider + +Convex supports multiple authentication approaches. Do not assume a provider. + +Before writing setup code: + +1. Ask the user which auth solution they want, unless the repository already makes it obvious +2. If the repo already uses a provider, continue with that provider unless the user wants to switch +3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding + +Common options: + +- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex +- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features +- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically +- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0 +- Custom JWT provider - use when integrating an existing auth system not covered above + +Look for signals in the repo before asking: + +- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages +- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components +- Environment variables that clearly point at a provider + +## After Choosing a Provider + +Read the provider's official guide and the matching local reference file: + +- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md` +- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md` +- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md` +- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md` + +The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks. + +Use those sources for: + +- package installation +- client provider wiring +- environment variables +- `convex/auth.config.ts` setup +- login and logout UI patterns +- framework-specific setup for React, Vite, or Next.js + +For shared auth behavior, use the official Convex docs as the source of truth: + +- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()` +- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage +- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance +- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth + +Do not invent a provider-agnostic user sync pattern from memory. +For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. +For Convex Auth, do not add a parallel `users` table plus `storeUser` flow. Follow the Convex Auth docs and built-in auth tables instead. + +Do not invent provider-specific setup from memory when the docs are available. +Do not assume provider initialization commands finish the entire integration. Verify generated files and complete the post-init wiring steps the provider reference calls out. + +## Workflow + +1. Determine the provider, either by asking the user or inferring from the repo +2. Ask whether the user wants local-only setup or production-ready setup now +3. Read the matching provider reference file +4. Follow the official provider docs for current setup details +5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns +6. Only add app-level user storage if the docs and app requirements call for it +7. Add authorization checks for ownership, roles, or team access only where the app needs them +8. Verify login state, protected queries, environment variables, and production configuration if requested + +If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it. +For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done. +If the environment has browser automation tools, you can use them. +If it does not, give the user a short manual validation checklist instead. + +## Reference Files + +### Provider References + +- `references/convex-auth.md` +- `references/clerk.md` +- `references/workos-authkit.md` +- `references/auth0.md` + +## Checklist + +- [ ] Chosen the correct auth provider before writing setup code +- [ ] Read the relevant provider reference file +- [ ] Asked whether the user wants local-only setup or production-ready setup +- [ ] Used the official provider docs for provider-specific wiring +- [ ] Used the official Convex docs for shared auth behavior and authorization patterns +- [ ] Only added app-level user storage if the app actually needs it +- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth +- [ ] Added authentication checks in protected backend functions +- [ ] Added authorization checks where the app actually needs them +- [ ] Clear error messages ("Not authenticated", "Unauthorized") +- [ ] Client auth provider configured for the chosen provider +- [ ] If requested, production auth setup is covered too diff --git a/skills/convex-setup-auth/agents/openai.yaml b/skills/convex-setup-auth/agents/openai.yaml new file mode 100644 index 00000000..d1c90a14 --- /dev/null +++ b/skills/convex-setup-auth/agents/openai.yaml @@ -0,0 +1,10 @@ +interface: + display_name: "Convex Setup Auth" + short_description: "Set up Convex auth, user identity mapping, and access control." + icon_small: "./assets/icon.svg" + icon_large: "./assets/icon.svg" + brand_color: "#2563EB" + default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation." + +policy: + allow_implicit_invocation: true diff --git a/skills/convex-setup-auth/assets/icon.svg b/skills/convex-setup-auth/assets/icon.svg new file mode 100644 index 00000000..4917dbb4 --- /dev/null +++ b/skills/convex-setup-auth/assets/icon.svg @@ -0,0 +1,3 @@ + diff --git a/skills/convex-setup-auth/references/auth0.md b/skills/convex-setup-auth/references/auth0.md new file mode 100644 index 00000000..9c729c5a --- /dev/null +++ b/skills/convex-setup-auth/references/auth0.md @@ -0,0 +1,116 @@ +# Auth0 + +Official docs: + +- https://docs.convex.dev/auth/auth0 +- https://auth0.github.io/auth0-cli/ +- https://auth0.github.io/auth0-cli/auth0_apps_create.html + +Use this when the app already uses Auth0 or the user wants Auth0 specifically. + +## Workflow + +1. Confirm the user wants Auth0 +2. Determine the app framework and whether Auth0 is already partly set up +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and Auth0 guides before making changes +5. Ask whether they want the fastest setup path by installing the Auth0 CLI +6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI +7. If they do not want the CLI path, use the Auth0 dashboard path instead +8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up +9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID +10. Set environment variables for local and production environments +11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +12. Gate Convex-backed UI with Convex auth state +13. Try to verify Convex reports the user as authenticated after Auth0 login +14. If the refresh-token path fails, stop improvising and send the user back to the official docs +15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered + +## What To Do + +- Read the official Convex and Auth0 guide before writing setup code +- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet +- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?" +- Make sure the app has already completed the relevant Auth0 quickstart for its frontend +- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0` +- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated + +## Key Setup Areas + +- install the Auth0 SDK for the app's framework +- configure `convex/auth.config.ts` with the Auth0 domain and client ID +- set environment variables for local and production environments +- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0` +- use Convex auth state when gating Convex-backed UI + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- frontend app entry or provider wrapper +- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/` +- Auth0 environment variables commonly include: + - `AUTH0_DOMAIN` + - `AUTH0_CLIENT_ID` + - `VITE_AUTH0_DOMAIN` + - `VITE_AUTH0_CLIENT_ID` + +## Concrete Steps + +1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework +2. Ask whether the user wants the Auth0 CLI path +3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login` +4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app +5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard +6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard +7. Install the Auth0 SDK for the app's framework +8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID +9. Set frontend and backend environment variables +10. Wrap the app in `Auth0Provider` +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0` +12. Run the normal Convex dev or deploy flow after backend config changes +13. Try the official provider config shown in the Convex docs +14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now +15. Only claim success if the user can sign in and Convex recognizes the authenticated session +16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too + +## Gotchas + +- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch +- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant +- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard +- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced +- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end +- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled +- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation +- Keep dev and prod tenants separate if the project uses different Auth0 environments +- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work. +- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it. +- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately. +- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered +- Verify production environment variables and redirect settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the Auth0 login flow +- Verify Convex-authenticated UI renders only after Convex auth state is ready +- Verify protected Convex queries succeed after login +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- Verify the Auth0 app settings match the real local callback and logout URLs during development +- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully +- If production-ready setup was requested, verify the production Auth0 configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Auth0 +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Complete the relevant Auth0 frontend setup +- [ ] Configure `convex/auth.config.ts` +- [ ] Set environment variables +- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs +- [ ] If requested, configure the production deployment too diff --git a/skills/convex-setup-auth/references/clerk.md b/skills/convex-setup-auth/references/clerk.md new file mode 100644 index 00000000..7dbde194 --- /dev/null +++ b/skills/convex-setup-auth/references/clerk.md @@ -0,0 +1,113 @@ +# Clerk + +Official docs: + +- https://docs.convex.dev/auth/clerk +- https://clerk.com/docs/guides/development/integrations/databases/convex + +Use this when the app already uses Clerk or the user wants Clerk's hosted auth features. + +## Workflow + +1. Confirm the user wants Clerk +2. Make sure the user has a Clerk account and a Clerk application +3. Determine the app framework: + - React + - Next.js + - TanStack Start +4. Ask whether the user wants local-only setup or production-ready setup now +5. Gather the Clerk keys and the Clerk Frontend API URL +6. Follow the correct framework section in the official docs +7. Complete the backend and client wiring +8. Verify Convex reports the user as authenticated after login +9. If the user wants production-ready setup, make sure the production Clerk config is also covered + +## What To Do + +- Read the official Convex and Clerk guide before writing setup code +- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application +- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active +- Match the guide to the app's framework, usually React, Next.js, or TanStack Start +- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth` + +## Key Setup Areas + +- install the Clerk SDK for the framework in use +- configure `convex/auth.config.ts` with the Clerk issuer domain +- set the required Clerk environment variables +- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk` +- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading` + +## Files and Env Vars To Expect + +- `convex/auth.config.ts` +- React or Vite client entry such as `src/main.tsx` +- Next.js client wrapper for Convex if using App Router +- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up` +- Clerk app creation page: `https://dashboard.clerk.com/apps/new` +- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex` +- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys` +- Clerk environment variables: + - `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs + - `CLERK_FRONTEND_API_URL` in the Clerk docs + - `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps + - `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps + - `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required + +`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs. + +## Concrete Steps + +1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up` +2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new` +3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed +4. Open `https://dashboard.clerk.com/apps/setup/convex` +5. Activate the Convex integration in Clerk if it is not already active +6. Copy the Clerk Frontend API URL shown there +7. Install the Clerk package for the app's framework +8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens +9. Set the publishable key in the frontend environment +10. Set the issuer domain or Frontend API URL so Convex can validate the JWT +11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk` +12. Wrap the app in `ClerkProvider` +13. Use Convex auth helpers for authenticated rendering +14. Run the normal Convex dev or deploy flow after updating backend auth config +15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too + +## Gotchas + +- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render +- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper +- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config +- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests. +- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it. +- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately. +- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key. +- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex` +- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included +- Verify production redirect URLs and any production Clerk domain values before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can sign in with Clerk +- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in +- Verify `useConvexAuth()` reaches the authenticated state after Clerk login +- Verify protected Convex queries run successfully inside authenticated UI +- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions +- If production-ready setup was requested, verify the production Clerk configuration is also covered + +## Checklist + +- [ ] Confirm the user wants Clerk +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Follow the correct framework section in the official guide +- [ ] Set Clerk environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify Convex authenticated state after login +- [ ] If requested, configure the production deployment too diff --git a/skills/convex-setup-auth/references/convex-auth.md b/skills/convex-setup-auth/references/convex-auth.md new file mode 100644 index 00000000..d4824d24 --- /dev/null +++ b/skills/convex-setup-auth/references/convex-auth.md @@ -0,0 +1,143 @@ +# Convex Auth + +Official docs: https://docs.convex.dev/auth/convex-auth +Setup guide: https://labs.convex.dev/auth/setup + +Use this when the user wants auth handled directly in Convex rather than through a third-party provider. + +## Workflow + +1. Confirm the user wants Convex Auth specifically +2. Determine which sign-in methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords and password reset +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the Convex Auth setup guide before writing code +5. Make sure the project has a configured Convex deployment: + - run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set + - if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing +6. Install the auth packages: + - `npm install @convex-dev/auth @auth/core@0.37.0` +7. Run the initialization command: + - `npx @convex-dev/auth` +8. Confirm the initializer created: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +9. Add the required `authTables` to `convex/schema.ts` +10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider` +11. Configure at least one auth method in `convex/auth.ts` +12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code +13. Verify the client can sign in successfully +14. Verify Convex receives authenticated identity in backend functions +15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well +16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex + +## What This Reference Is For + +- choosing Convex Auth as the default provider for a new Convex app +- understanding whether the app wants magic links, OTPs, OAuth, or passwords +- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior + +## What To Do + +- Read the Convex Auth setup guide before writing setup code +- Follow the setup flow from the docs rather than recreating it from memory +- If the app is new, consider starting from the official starter flow instead of hand-wiring everything +- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra + +## Concrete Steps + +1. Install `@convex-dev/auth` and `@auth/core@0.37.0` +2. Run `npx convex dev` if the project does not already have a configured deployment +3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment +4. Run `npx @convex-dev/auth` +5. Confirm the generated auth setup is present before continuing: + - `convex/auth.config.ts` + - `convex/auth.ts` + - `convex/http.ts` +6. Add `authTables` to `convex/schema.ts` +7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry +8. Configure the selected auth methods in `convex/auth.ts` +9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed +10. Verify login locally +11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment + +## Expected Files and Decisions + +- `convex/schema.ts` +- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file +- generated Convex Auth setup produced by `npx @convex-dev/auth` +- an existing configured Convex deployment, or the ability to create one with `npx convex dev` +- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods + +- Decide whether the user is creating a new app or adding auth to an existing app +- For a new app, prefer the official starter flow instead of rebuilding setup by hand +- Decide which auth methods the app needs: + - magic links or OTPs + - OAuth providers + - passwords +- Decide whether the user wants local-only setup or production-ready setup now +- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough + +## Gotchas + +- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior. +- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project. +- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`. +- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing. +- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method. +- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured. +- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough. +- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand. +- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too. +- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory. + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment +- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Human Handoff + +If `npx convex dev` or deployment setup requires human input: + +- stop and explain exactly what the user needs to do +- say why that step is required +- resume the auth setup immediately after the user confirms it is done + +## Validation + +- Verify the user can complete a sign-in flow +- Offer to validate sign up, sign out, and sign back in with the configured auth method +- If browser automation is available in the environment, you can do this directly +- If browser automation is not available, give the user a short manual validation checklist instead +- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions +- Verify protected UI only renders after Convex-authenticated state is ready +- Verify environment variables and redirect settings match the current app environment +- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in +- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed +- If production-ready setup was requested, verify the production deployment is also configured correctly + +## Checklist + +- [ ] Confirm the user wants Convex Auth specifically +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Ensure a Convex deployment is configured before running auth initialization +- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0` +- [ ] Run `npx convex dev` first if needed +- [ ] Run `npx @convex-dev/auth` +- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created +- [ ] Follow the setup guide for package install and wiring +- [ ] Add `authTables` to `convex/schema.ts` +- [ ] Replace `ConvexProvider` with `ConvexAuthProvider` +- [ ] Configure at least one auth method in `convex/auth.ts` +- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes +- [ ] Confirm which sign-in methods the app needs +- [ ] Verify the client can sign in and the backend receives authenticated identity +- [ ] Offer end-to-end validation of sign up, sign out, and sign back in +- [ ] If requested, configure the production deployment too +- [ ] Only add extra `users` table sync if the app needs app-level user records diff --git a/skills/convex-setup-auth/references/workos-authkit.md b/skills/convex-setup-auth/references/workos-authkit.md new file mode 100644 index 00000000..038cb9f3 --- /dev/null +++ b/skills/convex-setup-auth/references/workos-authkit.md @@ -0,0 +1,114 @@ +# WorkOS AuthKit + +Official docs: + +- https://docs.convex.dev/auth/authkit/ +- https://docs.convex.dev/auth/authkit/add-to-app +- https://docs.convex.dev/auth/authkit/auto-provision + +Use this when the app already uses WorkOS or the user wants AuthKit specifically. + +## Workflow + +1. Confirm the user wants WorkOS AuthKit +2. Determine whether they want: + - a Convex-managed WorkOS team + - an existing WorkOS team +3. Ask whether the user wants local-only setup or production-ready setup now +4. Read the official Convex and WorkOS AuthKit guide +5. Create or update `convex.json` for the app's framework and real local port +6. Follow the correct branch of the setup flow based on that choice +7. Configure the required WorkOS environment variables +8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs +9. Wire the client provider and callback flow +10. Verify authenticated requests reach Convex +11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too +12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex + +## What To Do + +- Read the official Convex and WorkOS AuthKit guide before writing setup code +- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team +- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra +- Follow the current setup flow from the docs instead of relying on older examples + +## Key Setup Areas + +- package installation for the app's framework +- `convex.json` with the `authKit` section for dev, and preview or prod if needed +- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration +- `convex/auth.config.ts` wiring for WorkOS-issued JWTs +- client provider setup and token flow into Convex +- login callback and redirect configuration + +## Files and Env Vars To Expect + +- `convex.json` +- `convex/auth.config.ts` +- frontend auth provider wiring +- callback or redirect route setup where the framework requires it +- WorkOS environment variables commonly include: + - `WORKOS_CLIENT_ID` + - `WORKOS_API_KEY` + - `WORKOS_COOKIE_PASSWORD` + - `VITE_WORKOS_CLIENT_ID` + - `VITE_WORKOS_REDIRECT_URI` + - `NEXT_PUBLIC_WORKOS_REDIRECT_URI` + +For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps. + +## Concrete Steps + +1. Choose Convex-managed or existing WorkOS team +2. Create or update `convex.json` with the `authKit` section for the framework in use +3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port +4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow +5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set` +6. Create or update `convex/auth.config.ts` for WorkOS JWT validation +7. Run the normal Convex dev or deploy flow so backend config is synced +8. Wire the WorkOS client provider in the app +9. Configure callback and redirect handling +10. Verify the user can sign in and return to the app +11. Verify Convex sees the authenticated user after login +12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too + +## Gotchas + +- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious +- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys +- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex +- Do not mix dev and prod WorkOS credentials or redirect URIs +- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it +- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts. +- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation. +- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again. +- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config. +- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded." + +## Production + +- Ask whether the user wants dev-only setup or production-ready setup +- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered +- Verify the production redirect and callback settings before calling the task complete +- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly. + +## Validation + +- Verify the user can complete the login flow and return to the app +- Verify the callback URL matches the real frontend port in local dev +- Verify Convex receives authenticated requests after login +- Verify `convex.json` matches the framework and chosen WorkOS setup path +- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path +- Verify environment variables differ correctly between local and production where needed +- If production-ready setup was requested, verify the production WorkOS configuration is also covered + +## Checklist + +- [ ] Confirm the user wants WorkOS AuthKit +- [ ] Ask whether the user wants local-only setup or production-ready setup +- [ ] Choose Convex-managed or existing WorkOS team +- [ ] Create or update `convex.json` +- [ ] Configure WorkOS environment variables +- [ ] Configure `convex/auth.config.ts` +- [ ] Verify authenticated requests reach Convex after login +- [ ] If requested, configure the production deployment too diff --git a/tool/_probe.dart b/tool/_probe.dart new file mode 100644 index 00000000..5ca33233 --- /dev/null +++ b/tool/_probe.dart @@ -0,0 +1,34 @@ +import 'dart:convert'; +import 'dart:io'; + +Future main() async { + final ws = await WebSocket.connect('ws://127.0.0.1:49695/OqqMw7jKLMo=/ws'); + var nextId = 1; + ws.add(jsonEncode({'jsonrpc': '2.0', 'id': nextId++, 'method': 'getVM'})); + await for (final raw in ws) { + final msg = jsonDecode(raw as String) as Map; + final result = msg['result']; + if (result is Map && result['type'] == 'VM') { + final isolates = result['isolates'] as List? ?? []; + for (final iso in isolates) { + final m = iso as Map; + print('${m['id']}: ${m['name']}'); + } + final first = isolates.isNotEmpty ? isolates.first as Map : null; + if (first != null) { + ws.add(jsonEncode({ + 'jsonrpc': '2.0', + 'id': nextId++, + 'method': 'getIsolate', + 'params': {'isolateId': first['id']}, + })); + } + continue; + } + if (result is Map && result['type'] == 'Isolate') { + print('extensionRPCs: ${result['extensionRPCs']}'); + await ws.close(); + return; + } + } +} From 4040ade977ac994ad15ffdaed381867b44945fbf Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Fri, 20 Mar 2026 04:54:42 -0400 Subject: [PATCH 6/6] Unify animated page navigation across cloud and local modes - Refactor page switching to use shared ordered page ID helpers - Apply animated forward/backward transitions in cloud mode too - Reuse transition direction resolution for both remote and local pages --- lib/providers/strategy_provider.dart | 148 ++++++++++++--------------- 1 file changed, 65 insertions(+), 83 deletions(-) diff --git a/lib/providers/strategy_provider.dart b/lib/providers/strategy_provider.dart index 773a65ca..bf9f82e8 100644 --- a/lib/providers/strategy_provider.dart +++ b/lib/providers/strategy_provider.dart @@ -346,11 +346,6 @@ class StrategyProvider extends Notifier { } Future switchPage(String pageID) async { - if (_isCloudMode()) { - await setActivePage(pageID); - return; - } - await setActivePageAnimated(pageID); } @@ -1308,76 +1303,32 @@ class StrategyProvider extends Notifier { } Future backwardPage() async { - if (_isCloudMode()) { - final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; - if (snapshot == null || snapshot.pages.isEmpty) return; - final pages = [...snapshot.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - final activeId = activePageID ?? pages.first.publicId; - final currentIndex = pages.indexWhere((p) => p.publicId == activeId); - if (currentIndex < 0) return; - var nextIndex = currentIndex - 1; - if (nextIndex < 0) nextIndex = pages.length - 1; - await setActivePage(pages[nextIndex].publicId); - return; - } - - if (activePageID == null) return; - - final box = Hive.box(HiveBoxNames.strategiesBox); - final doc = box.get(state.id); - if (doc == null || doc.pages.isEmpty) return; - - final pages = [...doc.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + final orderedPageIds = _orderedPageIds(); + if (orderedPageIds.isEmpty) return; - final currentIndex = pages.indexWhere((p) => p.id == activePageID); + final currentPageId = _currentOrderedPageId(orderedPageIds); + final currentIndex = orderedPageIds.indexOf(currentPageId); if (currentIndex == -1) return; int nextIndex = currentIndex - 1; - if (nextIndex < 0) nextIndex = pages.length - 1; + if (nextIndex < 0) nextIndex = orderedPageIds.length - 1; - final nextPage = pages[nextIndex]; - await setActivePageAnimated( - nextPage.id, - direction: PageTransitionDirection.backward, - ); + await setActivePageAnimated(orderedPageIds[nextIndex], + direction: PageTransitionDirection.backward); } Future forwardPage() async { - if (_isCloudMode()) { - final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; - if (snapshot == null || snapshot.pages.isEmpty) return; - final pages = [...snapshot.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - final activeId = activePageID ?? pages.first.publicId; - final currentIndex = pages.indexWhere((p) => p.publicId == activeId); - if (currentIndex < 0) return; - var nextIndex = currentIndex + 1; - if (nextIndex >= pages.length) nextIndex = 0; - await setActivePage(pages[nextIndex].publicId); - return; - } + final orderedPageIds = _orderedPageIds(); + if (orderedPageIds.isEmpty) return; - if (activePageID == null) return; - - final box = Hive.box(HiveBoxNames.strategiesBox); - final doc = box.get(state.id); - if (doc == null || doc.pages.isEmpty) return; - - final pages = [...doc.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); - - final currentIndex = pages.indexWhere((p) => p.id == activePageID); + final currentPageId = _currentOrderedPageId(orderedPageIds); + final currentIndex = orderedPageIds.indexOf(currentPageId); if (currentIndex == -1) return; int nextIndex = currentIndex + 1; - if (nextIndex >= pages.length) nextIndex = 0; + if (nextIndex >= orderedPageIds.length) nextIndex = 0; - final nextPage = pages[nextIndex]; - await setActivePageAnimated( - nextPage.id, - direction: PageTransitionDirection.forward, - ); + await setActivePageAnimated(orderedPageIds[nextIndex], + direction: PageTransitionDirection.forward); } Future reorderPage(int oldIndex, int newIndex) async { @@ -1449,17 +1400,51 @@ class StrategyProvider extends Notifier { await box.put(updated.id, updated); } + List _orderedPageIds() { + if (_isCloudMode()) { + final snapshot = ref.read(remoteStrategySnapshotProvider).valueOrNull; + if (snapshot == null || snapshot.pages.isEmpty) { + return const []; + } + + final orderedPages = [...snapshot.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + return orderedPages.map((page) => page.publicId).toList(growable: false); + } + + final doc = + Hive.box(HiveBoxNames.strategiesBox).get(state.id); + if (doc == null || doc.pages.isEmpty) { + return const []; + } + + final orderedPages = [...doc.pages] + ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); + return orderedPages.map((page) => page.id).toList(growable: false); + } + + String _currentOrderedPageId(List orderedPageIds) { + final currentPageId = activePageID ?? state.activePageId; + if (currentPageId != null && orderedPageIds.contains(currentPageId)) { + return currentPageId; + } + return orderedPageIds.first; + } + PageTransitionDirection _resolveDirectionForPage( - String pageID, List orderedPages) { - if (activePageID == null) return PageTransitionDirection.forward; + String pageID, List orderedPageIds) { + if (orderedPageIds.isEmpty) { + return PageTransitionDirection.forward; + } - final currentIndex = orderedPages.indexWhere((p) => p.id == activePageID); - final targetIndex = orderedPages.indexWhere((p) => p.id == pageID); + final currentIndex = + orderedPageIds.indexOf(_currentOrderedPageId(orderedPageIds)); + final targetIndex = orderedPageIds.indexOf(pageID); if (currentIndex < 0 || targetIndex < 0) { return PageTransitionDirection.forward; } - final length = orderedPages.length; + final length = orderedPageIds.length; final forwardSteps = (targetIndex - currentIndex + length) % length; final backwardSteps = (currentIndex - targetIndex + length) % length; return forwardSteps <= backwardSteps @@ -1472,10 +1457,6 @@ class StrategyProvider extends Notifier { {PageTransitionDirection? direction, Duration duration = kPageTransitionDuration}) async { if (pageID == activePageID) return; - if (_isCloudMode()) { - await setActivePage(pageID); - return; - } final transitionState = ref.read(transitionProvider); final transitionNotifier = ref.read(transitionProvider.notifier); @@ -1484,14 +1465,14 @@ class StrategyProvider extends Notifier { transitionNotifier.complete(); } - final box = Hive.box(HiveBoxNames.strategiesBox); - final doc = box.get(state.id); - if (doc == null || doc.pages.isEmpty) return; + final orderedPageIds = _orderedPageIds(); + if (orderedPageIds.isEmpty || !orderedPageIds.contains(pageID)) { + await setActivePage(pageID); + return; + } - final orderedPages = [...doc.pages] - ..sort((a, b) => a.sortIndex.compareTo(b.sortIndex)); final resolvedDirection = - direction ?? _resolveDirectionForPage(pageID, orderedPages); + direction ?? _resolveDirectionForPage(pageID, orderedPageIds); final startSettings = ref.read(strategySettingsProvider); final prev = _snapshotAllPlaced(); @@ -1604,10 +1585,7 @@ class StrategyProvider extends Notifier { return; } await ref.read(remoteStrategySnapshotProvider.notifier).refresh(); - final refreshed = ref.read(remoteStrategySnapshotProvider).valueOrNull; - if (refreshed != null) { - await _hydrateFromRemotePage(refreshed, pageID); - } + await setActivePageAnimated(pageID); return; } @@ -1741,7 +1719,11 @@ class StrategyProvider extends Notifier { refreshed.pages.any((page) => page.publicId == nextActivePageId) ? nextActivePageId : refreshed.pages.first.publicId; - await _hydrateFromRemotePage(refreshed, targetPageId); + if (targetPageId != activePageID) { + await setActivePageAnimated(targetPageId); + } else { + await _hydrateFromRemotePage(refreshed, targetPageId); + } return; }