@taskforcehq/taskforce 0.3.311 → 0.3.313
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -2
- package/dist/TaskforceCore.js +1 -1
- package/dist/components/features/InitiativesModule.js +1 -1
- package/dist/components/features/TaskSettings.js +1 -1
- package/dist/components/views/StandaloneLayout.js +3 -6
- package/dist/components/views/standalone/modals/AccountHubModal.d.ts +1 -2
- package/dist/components/views/standalone/modals/AccountHubModal.js +2 -3
- package/dist/components/views/standalone/modals/HelpModal.js +15 -2
- package/dist/hooks/useFilterSort.js +1 -1
- package/dist/hooks/useTaskforce.js +2 -2
- package/dist/hooks/workspace/useTaskforceWorkspaceBootstrap.js +5 -2
- package/dist/ui/assets/{AgentsModule-D8u9P5dZ.js → AgentsModule-BULqIo8e.js} +1 -1
- package/dist/ui/assets/{AnnotatedAttachmentWorkspace-CsUauFA2.js → AnnotatedAttachmentWorkspace-DHr4rHK9.js} +1 -1
- package/dist/ui/assets/{ContextAttachmentManager-DbQvDHFz.js → ContextAttachmentManager-DoMe2OpY.js} +1 -1
- package/dist/ui/assets/{DocumentWorkspace-BmTkN1A8.js → DocumentWorkspace-DumBWhvb.js} +1 -1
- package/dist/ui/assets/{EntityActivityTimeline-BXHTM-Nh.js → EntityActivityTimeline-sHk8Nzbq.js} +1 -1
- package/dist/ui/assets/{InitiativesModule-D33RyXx0.js → InitiativesModule-3X9UNzHh.js} +1 -1
- package/dist/ui/assets/{PlansPage-D0RXlT9_.js → PlansPage-C3A3EYaV.js} +1 -1
- package/dist/ui/assets/{TaskContextUpload-Vsg67lpR.js → TaskContextUpload-C8G7pWkX.js} +1 -1
- package/dist/ui/assets/{TaskSettings-DshLw7_d.js → TaskSettings-DM1o9Wla.js} +2 -2
- package/dist/ui/assets/{WorkflowsModule-CLM-1BnF.js → WorkflowsModule-CW0crzvD.js} +1 -1
- package/dist/ui/assets/documentReferences-BZB3nMRb.js +1 -0
- package/dist/ui/assets/index-BWFQ9mGn.js +5 -0
- package/dist/ui/assets/{index-DOR9PRqt.css → index-DcK_8tuE.css} +1 -1
- package/dist/ui/index.html +2 -2
- package/package.json +12 -4
- package/scripts/postinstall.js +4 -3
- package/dist/TaskforceCore.CategoryFallback.test.d.ts +0 -1
- package/dist/TaskforceCore.CategoryFallback.test.js +0 -101
- package/dist/TaskforceCore.filter-persistence.test.d.ts +0 -1
- package/dist/TaskforceCore.filter-persistence.test.js +0 -402
- package/dist/TaskforceCore.routing.test.d.ts +0 -1
- package/dist/TaskforceCore.routing.test.js +0 -311
- package/dist/TaskforceCore.test.d.ts +0 -1
- package/dist/TaskforceCore.test.js +0 -7910
- package/dist/TaskforceWidget.test.d.ts +0 -1
- package/dist/TaskforceWidget.test.js +0 -92
- package/dist/UnsavedChangesRelaxed.test.d.ts +0 -1
- package/dist/UnsavedChangesRelaxed.test.js +0 -16
- package/dist/__tests__/localizationCatalogs.test.d.ts +0 -1
- package/dist/__tests__/localizationCatalogs.test.js +0 -54
- package/dist/__tests__/workflowSimulation.test.d.ts +0 -1
- package/dist/__tests__/workflowSimulation.test.js +0 -113
- package/dist/annotatedAttachments/AnnotatedAttachmentSessionStore.test.d.ts +0 -1
- package/dist/annotatedAttachments/AnnotatedAttachmentSessionStore.test.js +0 -278
- package/dist/annotatedAttachments/payload.test.d.ts +0 -1
- package/dist/annotatedAttachments/payload.test.js +0 -67
- package/dist/compat/workspaceSyncCompat.test.d.ts +0 -1
- package/dist/compat/workspaceSyncCompat.test.js +0 -124
- package/dist/components/features/AgentsModule.test.d.ts +0 -1
- package/dist/components/features/AgentsModule.test.js +0 -601
- package/dist/components/features/AnnotatedAttachmentWorkspace.test.d.ts +0 -1
- package/dist/components/features/AnnotatedAttachmentWorkspace.test.js +0 -2883
- package/dist/components/features/DocumentWorkspace.test.d.ts +0 -1
- package/dist/components/features/DocumentWorkspace.test.js +0 -1439
- package/dist/components/features/TaskSettings.test.d.ts +0 -1
- package/dist/components/features/TaskSettings.test.js +0 -1674
- package/dist/components/features/settings/TaxonomyLibraryManager.test.d.ts +0 -1
- package/dist/components/features/settings/TaxonomyLibraryManager.test.js +0 -141
- package/dist/components/task/TaskActionHeader.test.d.ts +0 -1
- package/dist/components/task/TaskActionHeader.test.js +0 -91
- package/dist/components/task/TaskCard.test.d.ts +0 -1
- package/dist/components/task/TaskCard.test.js +0 -513
- package/dist/components/task/TaskContextUpload.test.d.ts +0 -1
- package/dist/components/task/TaskContextUpload.test.js +0 -506
- package/dist/components/task/TaskForm.test.d.ts +0 -1
- package/dist/components/task/TaskForm.test.js +0 -946
- package/dist/components/task/TaskKanban.empty-column-drop.test.d.ts +0 -1
- package/dist/components/task/TaskKanban.empty-column-drop.test.js +0 -66
- package/dist/components/task/TaskKanban.planning-drop.test.d.ts +0 -1
- package/dist/components/task/TaskKanban.planning-drop.test.js +0 -93
- package/dist/components/task/TaskKanban.test.d.ts +0 -1
- package/dist/components/task/TaskKanban.test.js +0 -99
- package/dist/components/task/TaskList.test.d.ts +0 -1
- package/dist/components/task/TaskList.test.js +0 -473
- package/dist/components/task/TaskStatusActions.test.d.ts +0 -1
- package/dist/components/task/TaskStatusActions.test.js +0 -54
- package/dist/components/task/taskKanbanDropRules.test.d.ts +0 -1
- package/dist/components/task/taskKanbanDropRules.test.js +0 -114
- package/dist/components/ui/LevelSelector.test.d.ts +0 -1
- package/dist/components/ui/LevelSelector.test.js +0 -55
- package/dist/components/ui/Markdown.test.d.ts +0 -1
- package/dist/components/ui/Markdown.test.js +0 -38
- package/dist/components/ui/MultiSelectFilter.test.d.ts +0 -1
- package/dist/components/ui/MultiSelectFilter.test.js +0 -74
- package/dist/components/ui/TaxonomyDropdown.test.d.ts +0 -1
- package/dist/components/ui/TaxonomyDropdown.test.js +0 -130
- package/dist/components/ui/TopNoticeLayer.test.d.ts +0 -1
- package/dist/components/ui/TopNoticeLayer.test.js +0 -25
- package/dist/components/views/AppShellHeader.test.d.ts +0 -1
- package/dist/components/views/AppShellHeader.test.js +0 -42
- package/dist/components/views/PlanComparisonPage.test.d.ts +0 -1
- package/dist/components/views/PlanComparisonPage.test.js +0 -758
- package/dist/components/views/PlansPage.test.d.ts +0 -1
- package/dist/components/views/PlansPage.test.js +0 -710
- package/dist/components/views/chrome/WorkspaceChromeSections.test.d.ts +0 -1
- package/dist/components/views/chrome/WorkspaceChromeSections.test.js +0 -54
- package/dist/components/views/chrome/workspaceChrome.test.d.ts +0 -1
- package/dist/components/views/chrome/workspaceChrome.test.js +0 -52
- package/dist/components/views/panels/DocumentFilterToolbar.test.d.ts +0 -1
- package/dist/components/views/panels/DocumentFilterToolbar.test.js +0 -19
- package/dist/components/views/panels/FilterToolbar.test.d.ts +0 -1
- package/dist/components/views/panels/FilterToolbar.test.js +0 -47
- package/dist/components/views/panels/PlanningDrawer.test.d.ts +0 -1
- package/dist/components/views/panels/PlanningDrawer.test.js +0 -529
- package/dist/components/views/planningScope.test.d.ts +0 -1
- package/dist/components/views/planningScope.test.js +0 -60
- package/dist/components/views/standalone/modals/AccountHubModal.test.d.ts +0 -1
- package/dist/components/views/standalone/modals/AccountHubModal.test.js +0 -72
- package/dist/components/views/standalone/modals/HelpModal.test.d.ts +0 -1
- package/dist/components/views/standalone/modals/HelpModal.test.js +0 -23
- package/dist/components/views/standalone/modals/SyncEnableWarningModal.test.d.ts +0 -1
- package/dist/components/views/standalone/modals/SyncEnableWarningModal.test.js +0 -24
- package/dist/components/views/teamManagementAccess.test.d.ts +0 -1
- package/dist/components/views/teamManagementAccess.test.js +0 -44
- package/dist/config/deployment.test.d.ts +0 -1
- package/dist/config/deployment.test.js +0 -90
- package/dist/config/envSchema.test.d.ts +0 -1
- package/dist/config/envSchema.test.js +0 -125
- package/dist/core/AiProfileService.test.d.ts +0 -1
- package/dist/core/AiProfileService.test.js +0 -184
- package/dist/core/AiProfiles.test.d.ts +0 -1
- package/dist/core/AiProfiles.test.js +0 -1873
- package/dist/core/AuthTokenService.test.d.ts +0 -1
- package/dist/core/AuthTokenService.test.js +0 -78
- package/dist/core/BulkUpdateFieldsPreview.test.d.ts +0 -1
- package/dist/core/BulkUpdateFieldsPreview.test.js +0 -62
- package/dist/core/CompletedAt.test.d.ts +0 -1
- package/dist/core/CompletedAt.test.js +0 -44
- package/dist/core/CreatedBy.test.d.ts +0 -1
- package/dist/core/CreatedBy.test.js +0 -188
- package/dist/core/DeletedTaskTrash.test.d.ts +0 -1
- package/dist/core/DeletedTaskTrash.test.js +0 -104
- package/dist/core/EntitlementsPolicy.test.d.ts +0 -1
- package/dist/core/EntitlementsPolicy.test.js +0 -280
- package/dist/core/GlobalSettingsService.test.d.ts +0 -1
- package/dist/core/GlobalSettingsService.test.js +0 -45
- package/dist/core/JsonBackupRuntime.test.d.ts +0 -1
- package/dist/core/JsonBackupRuntime.test.js +0 -155
- package/dist/core/PlanFeatureCatalog.test.d.ts +0 -1
- package/dist/core/PlanFeatureCatalog.test.js +0 -139
- package/dist/core/PlanVersionPolicy.test.d.ts +0 -1
- package/dist/core/PlanVersionPolicy.test.js +0 -236
- package/dist/core/PlanningEntities.test.d.ts +0 -1
- package/dist/core/PlanningEntities.test.js +0 -509
- package/dist/core/ScheduleFields.test.d.ts +0 -1
- package/dist/core/ScheduleFields.test.js +0 -193
- package/dist/core/SetupState.test.d.ts +0 -1
- package/dist/core/SetupState.test.js +0 -113
- package/dist/core/SignupMonetizationSettings.test.d.ts +0 -1
- package/dist/core/SignupMonetizationSettings.test.js +0 -515
- package/dist/core/Stats.test.d.ts +0 -1
- package/dist/core/Stats.test.js +0 -36
- package/dist/core/SystemAdmin.test.d.ts +0 -1
- package/dist/core/SystemAdmin.test.js +0 -1106
- package/dist/core/TaskActivitySync.test.d.ts +0 -1
- package/dist/core/TaskActivitySync.test.js +0 -90
- package/dist/core/TaskAttachmentsCanonical.test.d.ts +0 -1
- package/dist/core/TaskAttachmentsCanonical.test.js +0 -356
- package/dist/core/TaskAuditTimeline.test.d.ts +0 -1
- package/dist/core/TaskAuditTimeline.test.js +0 -319
- package/dist/core/TaskTaxonomyValidation.test.d.ts +0 -1
- package/dist/core/TaskTaxonomyValidation.test.js +0 -440
- package/dist/core/Taskforce.ids.test.d.ts +0 -1
- package/dist/core/Taskforce.ids.test.js +0 -611
- package/dist/core/Taskforce.listTasksSlim.test.d.ts +0 -1
- package/dist/core/Taskforce.listTasksSlim.test.js +0 -91
- package/dist/core/Taskforce.mcpAuth.test.d.ts +0 -1
- package/dist/core/Taskforce.mcpAuth.test.js +0 -450
- package/dist/core/Taskforce.realtimeMutation.test.d.ts +0 -1
- package/dist/core/Taskforce.realtimeMutation.test.js +0 -131
- package/dist/core/UserProfileAvatarDrafts.test.d.ts +0 -1
- package/dist/core/UserProfileAvatarDrafts.test.js +0 -138
- package/dist/core/WorkspaceDelete.test.d.ts +0 -1
- package/dist/core/WorkspaceDelete.test.js +0 -159
- package/dist/core/WorkspacePermissions.test.d.ts +0 -1
- package/dist/core/WorkspacePermissions.test.js +0 -270
- package/dist/core/WorkspacePlanMode.test.d.ts +0 -1
- package/dist/core/WorkspacePlanMode.test.js +0 -383
- package/dist/core/WorkspaceSyncSettings.test.d.ts +0 -1
- package/dist/core/WorkspaceSyncSettings.test.js +0 -65
- package/dist/core/__tests__/TaskAttachmentsCanonical.test.d.ts +0 -1
- package/dist/core/__tests__/TaskAttachmentsCanonical.test.js +0 -212
- package/dist/documentReviews/DocumentReviewSessionStore.test.d.ts +0 -1
- package/dist/documentReviews/DocumentReviewSessionStore.test.js +0 -127
- package/dist/hooks/authGuardPolicy.test.d.ts +0 -1
- package/dist/hooks/authGuardPolicy.test.js +0 -76
- package/dist/hooks/bootstrapTimeouts.test.d.ts +0 -1
- package/dist/hooks/bootstrapTimeouts.test.js +0 -12
- package/dist/hooks/sync/controlPlane.test.d.ts +0 -1
- package/dist/hooks/sync/controlPlane.test.js +0 -121
- package/dist/hooks/sync/lifecyclePolicy.test.d.ts +0 -1
- package/dist/hooks/sync/lifecyclePolicy.test.js +0 -124
- package/dist/hooks/sync/orchestratorShared.test.d.ts +0 -1
- package/dist/hooks/sync/orchestratorShared.test.js +0 -98
- package/dist/hooks/sync/pullLifecycle.test.d.ts +0 -1
- package/dist/hooks/sync/pullLifecycle.test.js +0 -80
- package/dist/hooks/sync/recovery.test.d.ts +0 -1
- package/dist/hooks/sync/recovery.test.js +0 -292
- package/dist/hooks/sync/transfers.test.d.ts +0 -1
- package/dist/hooks/sync/transfers.test.js +0 -928
- package/dist/hooks/sync/useRecentSyncEvents.test.d.ts +0 -1
- package/dist/hooks/sync/useRecentSyncEvents.test.js +0 -124
- package/dist/hooks/sync/useSyncStatusActions.test.d.ts +0 -1
- package/dist/hooks/sync/useSyncStatusActions.test.js +0 -133
- package/dist/hooks/sync/useSyncStatusControls.test.d.ts +0 -1
- package/dist/hooks/sync/useSyncStatusControls.test.js +0 -88
- package/dist/hooks/useFilterSort.test.d.ts +0 -1
- package/dist/hooks/useFilterSort.test.js +0 -419
- package/dist/hooks/useRealtimeSync.test.d.ts +0 -1
- package/dist/hooks/useRealtimeSync.test.js +0 -311
- package/dist/hooks/useSyncOrchestrator.aiProfiles.test.d.ts +0 -1
- package/dist/hooks/useSyncOrchestrator.aiProfiles.test.js +0 -54
- package/dist/hooks/useSyncOrchestrator.context-assets.test.d.ts +0 -1
- package/dist/hooks/useSyncOrchestrator.context-assets.test.js +0 -228
- package/dist/hooks/useSyncOrchestrator.retry-closure.test.d.ts +0 -1
- package/dist/hooks/useSyncOrchestrator.retry-closure.test.js +0 -2027
- package/dist/hooks/useTaskData.test.d.ts +0 -1
- package/dist/hooks/useTaskData.test.js +0 -291
- package/dist/hooks/useTaskMutations.test.d.ts +0 -1
- package/dist/hooks/useTaskMutations.test.js +0 -256
- package/dist/hooks/useTaskforce.contract.test.d.ts +0 -1
- package/dist/hooks/useTaskforce.contract.test.js +0 -7
- package/dist/hooks/useTaskforce.priority-filters.test.d.ts +0 -1
- package/dist/hooks/useTaskforce.priority-filters.test.js +0 -28
- package/dist/hooks/useTaskforce.runtime-routing.test.d.ts +0 -1
- package/dist/hooks/useTaskforce.runtime-routing.test.js +0 -246
- package/dist/hooks/useTaskforce.sync-behavior.test.d.ts +0 -1
- package/dist/hooks/useTaskforce.sync-behavior.test.js +0 -3644
- package/dist/hooks/useWorkspaceSyncController.test.d.ts +0 -1
- package/dist/hooks/useWorkspaceSyncController.test.js +0 -192
- package/dist/hooks/workspace/useTaskforceApiRouting.test.d.ts +0 -1
- package/dist/hooks/workspace/useTaskforceApiRouting.test.js +0 -77
- package/dist/hooks/workspace/workspaceLocalState.test.d.ts +0 -1
- package/dist/hooks/workspace/workspaceLocalState.test.js +0 -59
- package/dist/localization/localizationCatalogs.test.d.ts +0 -1
- package/dist/localization/localizationCatalogs.test.js +0 -37
- package/dist/mcp/aiProfileBootstrap.test.d.ts +0 -1
- package/dist/mcp/aiProfileBootstrap.test.js +0 -68
- package/dist/mcp/canonicalAssetHelpers.test.d.ts +0 -1
- package/dist/mcp/canonicalAssetHelpers.test.js +0 -67
- package/dist/mcp/clientIntegrations.test.d.ts +0 -1
- package/dist/mcp/clientIntegrations.test.js +0 -219
- package/dist/mcp/optionResolution.test.d.ts +0 -1
- package/dist/mcp/optionResolution.test.js +0 -43
- package/dist/mcp/runtime.test.d.ts +0 -1
- package/dist/mcp/runtime.test.js +0 -5211
- package/dist/mcp/structuredCommentValidation.test.d.ts +0 -1
- package/dist/mcp/structuredCommentValidation.test.js +0 -31
- package/dist/mcp/structuredDocValidation.test.d.ts +0 -1
- package/dist/mcp/structuredDocValidation.test.js +0 -35
- package/dist/mcp/toolRegistry.test.d.ts +0 -1
- package/dist/mcp/toolRegistry.test.js +0 -34
- package/dist/migrations/billingSchemaParity.test.d.ts +0 -1
- package/dist/migrations/billingSchemaParity.test.js +0 -160
- package/dist/migrations/taskSchemaMigrations.test.d.ts +0 -1
- package/dist/migrations/taskSchemaMigrations.test.js +0 -225
- package/dist/qaOpen.test.d.ts +0 -1
- package/dist/qaOpen.test.js +0 -56
- package/dist/releaseVersion.test.d.ts +0 -1
- package/dist/releaseVersion.test.js +0 -32
- package/dist/runtime/appGates.test.d.ts +0 -1
- package/dist/runtime/appGates.test.js +0 -42
- package/dist/server/aiProfileAvatarAssets.test.d.ts +0 -1
- package/dist/server/aiProfileAvatarAssets.test.js +0 -213
- package/dist/server/annotatedAttachmentsRoutes.test.d.ts +0 -1
- package/dist/server/annotatedAttachmentsRoutes.test.js +0 -532
- package/dist/server/auth.test.d.ts +0 -1
- package/dist/server/auth.test.js +0 -131
- package/dist/server/buildInfo.test.d.ts +0 -1
- package/dist/server/buildInfo.test.js +0 -29
- package/dist/server/cors.test.d.ts +0 -1
- package/dist/server/cors.test.js +0 -77
- package/dist/server/documentReviewRoutes.test.d.ts +0 -1
- package/dist/server/documentReviewRoutes.test.js +0 -190
- package/dist/server/email.test.d.ts +0 -1
- package/dist/server/email.test.js +0 -113
- package/dist/server/index.cookieProxy.test.d.ts +0 -1
- package/dist/server/index.cookieProxy.test.js +0 -67
- package/dist/server/index.rateLimit.test.d.ts +0 -1
- package/dist/server/index.rateLimit.test.js +0 -22
- package/dist/server/index.test.d.ts +0 -1
- package/dist/server/index.test.js +0 -283
- package/dist/server/rateLimit.test.d.ts +0 -1
- package/dist/server/rateLimit.test.js +0 -107
- package/dist/server/realtimeSync.auth.test.d.ts +0 -1
- package/dist/server/realtimeSync.auth.test.js +0 -62
- package/dist/server/realtimeSync.replay.test.d.ts +0 -1
- package/dist/server/realtimeSync.replay.test.js +0 -192
- package/dist/server/realtimeSync.workspaceIsolation.test.d.ts +0 -1
- package/dist/server/realtimeSync.workspaceIsolation.test.js +0 -101
- package/dist/server/routes/billing.test.d.ts +0 -1
- package/dist/server/routes/billing.test.js +0 -3515
- package/dist/server/routes/shared.test.d.ts +0 -1
- package/dist/server/routes/shared.test.js +0 -32
- package/dist/server/routes/sync.integration.test.d.ts +0 -1
- package/dist/server/routes/sync.integration.test.js +0 -2932
- package/dist/server/routes/syncAuxRoutes.test.d.ts +0 -1
- package/dist/server/routes/syncAuxRoutes.test.js +0 -158
- package/dist/server/routes/syncRouteGuards.test.d.ts +0 -1
- package/dist/server/routes/syncRouteGuards.test.js +0 -94
- package/dist/server/routes.test.d.ts +0 -1
- package/dist/server/routes.test.js +0 -15612
- package/dist/server/runtimeMode.test.d.ts +0 -1
- package/dist/server/runtimeMode.test.js +0 -26
- package/dist/server/securityHeaders.test.d.ts +0 -1
- package/dist/server/securityHeaders.test.js +0 -70
- package/dist/services/templateEngine.test.d.ts +0 -1
- package/dist/services/templateEngine.test.js +0 -150
- package/dist/services/templates.test.d.ts +0 -1
- package/dist/services/templates.test.js +0 -45
- package/dist/services/workflowDocumentFixtures.test.d.ts +0 -1
- package/dist/services/workflowDocumentFixtures.test.js +0 -78
- package/dist/services/workflowExportMatrix.test.d.ts +0 -1
- package/dist/services/workflowExportMatrix.test.js +0 -113
- package/dist/services/workflowExportSnapshots.test.d.ts +0 -1
- package/dist/services/workflowExportSnapshots.test.js +0 -30
- package/dist/services/workflowGeneration.test.d.ts +0 -1
- package/dist/services/workflowGeneration.test.js +0 -12
- package/dist/services/workflowSimulation.test.d.ts +0 -1
- package/dist/services/workflowSimulation.test.js +0 -113
- package/dist/services/workflowV2Policy.test.d.ts +0 -1
- package/dist/services/workflowV2Policy.test.js +0 -80
- package/dist/shared/customTaxonomyLibrary.test.d.ts +0 -1
- package/dist/shared/customTaxonomyLibrary.test.js +0 -20
- package/dist/shared/passwordPolicy.test.d.ts +0 -1
- package/dist/shared/passwordPolicy.test.js +0 -34
- package/dist/shared/runtimeContract.test.d.ts +0 -1
- package/dist/shared/runtimeContract.test.js +0 -23
- package/dist/shared/taxonomyLibrary.test.d.ts +0 -1
- package/dist/shared/taxonomyLibrary.test.js +0 -26
- package/dist/shared/taxonomyState.test.d.ts +0 -1
- package/dist/shared/taxonomyState.test.js +0 -71
- package/dist/soak/preflight.cli.d.ts +0 -1
- package/dist/soak/preflight.cli.js +0 -28
- package/dist/soak/preflight.d.ts +0 -26
- package/dist/soak/preflight.js +0 -113
- package/dist/soak/preflight.test.d.ts +0 -1
- package/dist/soak/preflight.test.js +0 -39
- package/dist/storage/objectStorageClient.test.d.ts +0 -1
- package/dist/storage/objectStorageClient.test.js +0 -82
- package/dist/storage/objectStorageConfig.test.d.ts +0 -1
- package/dist/storage/objectStorageConfig.test.js +0 -50
- package/dist/storage/postgresAdapter.test.d.ts +0 -1
- package/dist/storage/postgresAdapter.test.js +0 -29
- package/dist/storage/workspaceAssetStore.test.d.ts +0 -1
- package/dist/storage/workspaceAssetStore.test.js +0 -588
- package/dist/sync/cloudSyncApi.test.d.ts +0 -1
- package/dist/sync/cloudSyncApi.test.js +0 -111
- package/dist/sync/collaborationSyncPayload.test.d.ts +0 -1
- package/dist/sync/collaborationSyncPayload.test.js +0 -125
- package/dist/sync/contentSyncPayload.test.d.ts +0 -1
- package/dist/sync/contentSyncPayload.test.js +0 -143
- package/dist/sync/encryptionService.test.d.ts +0 -1
- package/dist/sync/encryptionService.test.js +0 -52
- package/dist/sync/planningSyncPayload.test.d.ts +0 -1
- package/dist/sync/planningSyncPayload.test.js +0 -92
- package/dist/sync/realtimeFeature.test.d.ts +0 -1
- package/dist/sync/realtimeFeature.test.js +0 -30
- package/dist/sync/realtimeReconcile.test.d.ts +0 -1
- package/dist/sync/realtimeReconcile.test.js +0 -43
- package/dist/sync/syncApplyHandlers.test.d.ts +0 -1
- package/dist/sync/syncApplyHandlers.test.js +0 -626
- package/dist/sync/syncService.test.d.ts +0 -1
- package/dist/sync/syncService.test.js +0 -903
- package/dist/sync/taskSyncPayload.test.d.ts +0 -1
- package/dist/sync/taskSyncPayload.test.js +0 -54
- package/dist/sync/workspacePullFeed.test.d.ts +0 -1
- package/dist/sync/workspacePullFeed.test.js +0 -438
- package/dist/sync/workspaceSyncModel.test.d.ts +0 -1
- package/dist/sync/workspaceSyncModel.test.js +0 -1442
- package/dist/test/setup.d.ts +0 -1
- package/dist/test/setup.js +0 -15
- package/dist/ui/assets/documentReferences-BPWp6ce0.js +0 -1
- package/dist/ui/assets/index-zvbo2Jse.js +0 -5
- package/dist/utils/accountProfileSummaryCache.test.d.ts +0 -1
- package/dist/utils/accountProfileSummaryCache.test.js +0 -63
- package/dist/utils/annotatedAttachments.test.d.ts +0 -1
- package/dist/utils/annotatedAttachments.test.js +0 -108
- package/dist/utils/assignees.test.d.ts +0 -1
- package/dist/utils/assignees.test.js +0 -25
- package/dist/utils/avatarUpload.test.d.ts +0 -1
- package/dist/utils/avatarUpload.test.js +0 -40
- package/dist/utils/canonicalAssetKind.test.d.ts +0 -1
- package/dist/utils/canonicalAssetKind.test.js +0 -24
- package/dist/utils/coalescedRefresh.test.d.ts +0 -1
- package/dist/utils/coalescedRefresh.test.js +0 -30
- package/dist/utils/constants.icons.test.d.ts +0 -1
- package/dist/utils/constants.icons.test.js +0 -41
- package/dist/utils/planParser.test.d.ts +0 -1
- package/dist/utils/planParser.test.js +0 -183
- package/dist/utils/planningReferences.test.d.ts +0 -1
- package/dist/utils/planningReferences.test.js +0 -17
- package/dist/utils/supportContact.test.d.ts +0 -1
- package/dist/utils/supportContact.test.js +0 -19
- package/dist/utils/syncEventDetails.test.d.ts +0 -1
- package/dist/utils/syncEventDetails.test.js +0 -23
- package/dist/utils/syncEventPresentation.test.d.ts +0 -1
- package/dist/utils/syncEventPresentation.test.js +0 -64
- package/dist/utils/syncStatusPresentation.test.d.ts +0 -1
- package/dist/utils/syncStatusPresentation.test.js +0 -164
- package/dist/utils/taskActivity.test.d.ts +0 -1
- package/dist/utils/taskActivity.test.js +0 -218
- package/dist/utils/taskDraftDefaults.test.d.ts +0 -1
- package/dist/utils/taskDraftDefaults.test.js +0 -34
- package/dist/utils/taskDragZones.test.d.ts +0 -1
- package/dist/utils/taskDragZones.test.js +0 -14
- package/dist/utils/taskNormalization.test.d.ts +0 -1
- package/dist/utils/taskNormalization.test.js +0 -158
- package/dist/utils/taskSearch.test.d.ts +0 -1
- package/dist/utils/taskSearch.test.js +0 -69
- package/dist/utils/taskUtils.test.d.ts +0 -1
- package/dist/utils/taskUtils.test.js +0 -19
- package/dist/utils/taskforceApiClient.test.d.ts +0 -1
- package/dist/utils/taskforceApiClient.test.js +0 -44
- package/dist/utils/taxonomyFormDefaults.test.d.ts +0 -1
- package/dist/utils/taxonomyFormDefaults.test.js +0 -63
- package/dist/utils/uiNotice.test.d.ts +0 -1
- package/dist/utils/uiNotice.test.js +0 -18
- package/dist/utils/workspaceIdentity.test.d.ts +0 -1
- package/dist/utils/workspaceIdentity.test.js +0 -61
- package/dist/utils/workspaceLifecycle.test.d.ts +0 -1
- package/dist/utils/workspaceLifecycle.test.js +0 -64
- package/dist/utils/workspaceSyncPresentation.test.d.ts +0 -1
- package/dist/utils/workspaceSyncPresentation.test.js +0 -71
- package/scripts/bootstrap-playwright-auth.mjs +0 -155
- package/scripts/check-cloud-mcp.mjs +0 -83
- package/scripts/check-compat-boundaries.mjs +0 -41
- package/scripts/check-env.ts +0 -31
- package/scripts/check-localization-strings.mjs +0 -49
- package/scripts/check-runtime-boundaries.mjs +0 -44
- package/scripts/debug-global.mjs +0 -34
- package/scripts/debug-login.mjs +0 -32
- package/scripts/debug-server.mjs +0 -36
- package/scripts/deploy-prod.sh +0 -41
- package/scripts/deploy-staging.sh +0 -23
- package/scripts/export-sqlite-to-postgres.mjs +0 -123
- package/scripts/generate-env-example.ts +0 -8
- package/scripts/mcp-stdio-adapter.mjs +0 -160
- package/scripts/migrate-task-data-assets.mjs +0 -408
- package/scripts/playwright-auth.sh +0 -19
- package/scripts/qa-open-lib.mjs +0 -175
- package/scripts/qa-open-lib.mjs.d.ts +0 -49
- package/scripts/qa-open.mjs +0 -352
- package/scripts/release-version-lib.mjs +0 -88
- package/scripts/release-version.mjs +0 -72
- package/scripts/run-billing-performance-smoke.sh +0 -24
- package/scripts/run-dev-proxy.sh +0 -51
- package/scripts/run-e2e-realtime.sh +0 -30
- package/scripts/run-smoke.sh +0 -35
- package/scripts/run-soak.sh +0 -41
- package/scripts/test-global.js +0 -143
- package/scripts/update-homebrew-formula.sh +0 -108
- package/scripts/with-esbuild.sh +0 -11
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EntityActivityTimeline-sHk8Nzbq.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-CLnehDTw.js","assets/vendor-markdown-BUxTU7dS.js","assets/vendor-dnd-DRzYolkg.js","assets/vendor-router-BbWMxlnO.js","assets/EntityActivityTimeline-DyqvvhuF.css","assets/TaskContextUpload-C8G7pWkX.js","assets/ContextAttachmentManager-DoMe2OpY.js","assets/documentReferences-BZB3nMRb.js","assets/TaskSettings-DM1o9Wla.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-DHr4rHK9.js","assets/AnnotatedAttachmentWorkspace-BVKew-mH.css","assets/DocumentWorkspace-DumBWhvb.js","assets/DocumentWorkspace-D4rJKXzd.css","assets/WorkflowsModule-CW0crzvD.js","assets/AgentsModule-BULqIo8e.js","assets/InitiativesModule-3X9UNzHh.js","assets/PlansPage-C3A3EYaV.js","assets/PlansPage-DeAzWYTb.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r,j as a,R as Fe,a as Zi,b as Tk}from"./vendor-react-CKJs5o3c.js";import{I as ks,C as Yi,a as tl,b as eo,c as Qp,F as Rk,A as jk,R as kd,T as gm,L as Np,d as Ro,e as Nk,X as ac,f as ig,g as cg,h as pr,B as Zu,U as ni,i as lg,S as Pk,P as to,j as Jc,G as Mk,k as Uu,l as Yu,m as vd,n as Ek,o as Xp,p as Dk,q as Pp,r as dg,s as Lk,t as Bk,M as ug,W as Wk,u as Fk,v as Ok,w as $k,x as jo,E as ef,y as mg,z as pg,D as Uk,H as zk,J as Hk,K as qf,N as Kf,O as Gk,Q as Vk,Z as qk,V as Kk,Y as Zk,_ as Yk,$ as fg,a0 as Jk,a1 as Zf,a2 as Qk,a3 as Xk,a4 as ev,a5 as tv}from"./vendor-icons-CLnehDTw.js";import{M as av,r as nv,a as rv}from"./vendor-markdown-BUxTU7dS.js";import{u as hg,a as Mp,b as sv,D as gg,c as ov,S as yg,v as kg,P as vg,d as Sg,C as tf,e as iv,p as cv,f as Yf,s as lv,K as dv,g as af,h as uv,i as wg,j as mv}from"./vendor-dnd-DRzYolkg.js";import{u as bg,a as _g,b as pv,M as fv,N as Jf,B as hv}from"./vendor-router-BbWMxlnO.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();const Yc="default",ym="General",Dr="task",gv=2,yv=[{value:Yc,label:ym,icon:"Inbox"}],Cg=[{value:Dr,label:"Task",icon:"CheckSquare",color:"blue-500"}],kv=[{value:gv,label:"Medium",color:"blue-500",icon:"Minus"}];function vv(){return yv.map(e=>({...e}))}function Sv(){return Cg.map(e=>({...e}))}function wv(e){const t=String(e||"").trim().toLowerCase();return Cg.find(n=>n.value===t)}function Ag(){return kv.map(e=>({...e}))}const bv="default",_v=[{value:bv,label:"Default",color:"slate-500",icon:"Circle"},{value:"evaluate",label:"Evaluate",color:"amber-500",icon:"Search"},{value:"collaborate",label:"Collaborate",color:"blue-500",icon:"Users"},{value:"plan",label:"Plan",color:"teal-500",icon:"FileText"},{value:"review",label:"Review",color:"violet-500",icon:"Microscope"}];function xg(){return _v.map(e=>({...e}))}const Cv={categories:vv(),types:Sv(),priorities:Ag(),approaches:xg(),taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,cloudMcpBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dark",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!0,showTaskCardStatusLabel:!0},Av=["light","dawn","dark","midnight"],Ju="dark",xv=[{id:"light",label:"Light",family:"light",icon:"sun"},{id:"dawn",label:"Dawn",family:"light",icon:"wind"},{id:"dark",label:"Dark",family:"dark",icon:"moon"},{id:"midnight",label:"Midnight",family:"dark",icon:"sparkles"}],Iv=new Set(Av),Tv=new Set(xv.filter(e=>e.family==="light").map(e=>e.id));function Rv(e){return typeof e=="string"&&Iv.has(e)}function Vc(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return Rv(t)?t:null}function Ig(e){const t=Vc(e);return t!==null&&Tv.has(t)}function Ep(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;const n=Math.floor(t);return n>0?n:null}function Qc(e,t){const n=Ep(typeof t=="object"&&t!==null?t.referenceNumber:t);return n?`${e}${n}`:""}function nf(e,t){const n=String(e||"").trim(),s=String(t||"").trim();if(!n||!s)return null;const o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=s.match(new RegExp(`^${o}(\\d+)$`,"i"));return l?Ep(l[1]):null}function km(e,t){return t?typeof t.referenceLabel=="string"&&t.referenceLabel.trim().length>0?t.referenceLabel.trim():Qc(e,t.referenceNumber):""}const rf="T-",Qf="LT-";function jv(e){return Qc(rf,e)}function Tg(e){return typeof e=="number"||e===null||e===void 0?Qc(Qf,e):Qc(Qf,{referenceNumber:e.localReferenceNumber??null})}function Rg(e){return nf(rf,e)}function Qi(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const t=km(rf,e);return t||Tg(e.localReferenceNumber)}function Nv(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function jg(e){return{label:Qi(e),isProvisional:Nv(e)}}Ag();const Pv={low:1,medium:2,high:3,critical:4,"on-hold":1},Mv={1:"low",2:"medium",3:"high",4:"critical",5:"critical"};function Ev(e){const t=String(e||"").trim().toLowerCase();return t==="blocked"||t==="on hold"||t==="on-hold"?"on-hold":t==="task"||t==="on-hold"||t==="in-progress"||t==="review"||t==="done"||t==="cancelled"?t:"task"}function Qu(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(1,Math.round(e));const t=Number(e);return Number.isFinite(t)?Math.max(1,Math.round(t)):Pv[String(e||"").trim().toLowerCase()]??2}function Dv(e,t){return Mv[String(e)]||t}function Po(e){const t=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,n=typeof e.localReferenceNumber=="number"?e.localReferenceNumber:Number.isFinite(Number(e.localReferenceNumber))?Number(e.localReferenceNumber):null;return{...e,referenceNumber:t&&t>0?Math.floor(t):null,localReferenceNumber:n&&n>0?Math.floor(n):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():t?jv(t):Tg(n),assignee:(()=>{const s=String(e.assignee||"").trim(),o=s.toLowerCase();return o==="agent"||o==="ai"?"agent":!s||o==="user"||o==="human"||o==="unassigned"||o==="none"||o==="null"?"unassigned":s})(),category:typeof e.category=="string"?e.category:e.category?.value||"default",type:(typeof e.type=="string"?e.type:e.type?.label||"task").toLowerCase(),priority:Qu(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:Ev(e.status)}}function Lv(e,t,n){if(!e||typeof e!="object")return{tasks:t,archivedTasks:n};const s=Po(e),o=String(s.id||"").trim();if(!o)return{tasks:t,archivedTasks:n};const l=!!s.isArchived,i=l?{...s,isArchived:!0}:{...s,isArchived:!1},d=k=>[...k].sort((S,h)=>{const g=Date.parse(String(S.updatedAt||S.createdAt||"")),v=Date.parse(String(h.updatedAt||h.createdAt||""));if(Number.isFinite(g)&&Number.isFinite(v)&&g!==v)return v-g;if(Number.isFinite(g)!==Number.isFinite(v))return Number.isFinite(v)?1:-1;const A=Date.parse(String(h.createdAt||""))-Date.parse(String(S.createdAt||""));return Number.isFinite(A)&&A!==0?A:String(S.id).localeCompare(String(h.id))}),m=t.filter(k=>k.id!==o),y=n.filter(k=>k.id!==o);return l?y.push(i):m.push(i),{tasks:d(m),archivedTasks:d(y)}}function Bv(e,t){if(!t.length||!e.length)return[];const n=new Set(t.map(o=>Number(o.value))),s=Array.from(new Set(e.map(o=>Number(o)).filter(o=>Number.isFinite(o)&&n.has(o))));return s.length>0?s:t.map(o=>Number(o.value))}function lp(e,t){return t.some(n=>String(n)===String(e))}function Wv(e,t){if(!e.length||!t.length)return e;const n=new Set(t.map(o=>o.value)),s=Array.from(new Set(e.filter(o=>n.has(o))));return s.length>0?s:t.map(o=>o.value)}const Fv={taskForm:{commentsSectionTitle:"Activity & Comments",hideComments:"Hide Comments",showComments:"Show Comments",noComments:"No comments yet. Start the conversation!",you:"You",commentPlaceholder:"Type a comment...",scheduledLabel:"Scheduled:",dueLabel:"Due:",createdLabel:"Created:",updatedLabel:"Updated:",completedLabel:"Completed:",emptyValue:"—",dueBeforeScheduled:"Due date is before scheduled date.",overdue:"This task is overdue."},schedule:{},taskList:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",sortByLabel:"Sort By:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",resetFiltersTitle:"Reset all filters",archiveAllTitle:"Archive all completed and cancelled tasks",noTasksToArchiveTitle:"No tasks to archive",archiveFinished:"Archive Finished",linksLabel:"Links",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchive:"Archived",noMatchingTasks:"No matching tasks",noActiveTasks:"No active tasks",addTaskToCategoryTitle:"Add task to {category}"},actionHeader:{saveChangesTitle:"Save Changes",update:"Update",copyTaskIdTitle:"Click to copy Task ID",startWorking:"Start Working",stopWorking:"Stop Working",unlockAndContinue:"Unlock & Continue Work",readyForReview:"Ready for Review",markComplete:"Mark Complete",unmarkComplete:"Unmark Complete",cancelTask:"Cancel Task",unmarkCancelled:"Unmark Cancelled",archiveNow:"Archive Now",completeTaskToArchive:"Complete task to archive",clearFormTitle:"Clear Form",clear:"Clear",addTaskTitle:"Add Task",addTask:"Add Task"},standalone:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",sortLabel:"Sort:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortComplexity:"Complexity",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",groupLabel:"Group:",groupCategory:"Category",groupType:"Type",groupPriority:"Priority",groupComplexity:"Complexity",groupApproach:"Workflow",groupAssignee:"Assignee",groupStatus:"Status",groupHierarchy:"Hierarchy",groupSchedule:"Schedule",showEmptyColumns:"Show Empty Columns",compressEmptyColumns:"Compress Empty Columns",hideEmptyColumns:"Hide Empty Columns",expandCards:"Expand Cards",compressCards:"Compress Cards",exitZenMode:"Exit Zen Mode",enterZenMode:"Enter Zen Mode",toggleFilters:"Toggle Filters",addTask:"Add Task",helpTutorial:"Help & Support",settings:"Settings",filtersCaps:"FILTERS:",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",linksLabel:"Links:",chooseLinksTitle:"Choose which linked tasks are shown",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchiveTitle:"Include archived tasks",includeArchive:"Archived",clearFilters:"Clear Filters",noTasksMatchFilters:"No tasks match current filters.",showingWithLinksHint:"Showing: {parentFilterLabel}. Switch Links to All or clear filters.",visibleActiveTasksTitle:"Visible active tasks / total active tasks",totalActiveTasksTitle:"Total active tasks"},setup:{headingCheckFailed:"Setup Check Failed",headingGlobalRequired:"Global Setup Required",headingWorkspaceRequired:"Configure your new workspace.",subtitleUnreadable:"Taskforce could not read setup state. Retry to continue.",subtitleGlobalRequired:"Choose your default operating mode to continue.",subtitleWorkspaceRequired:"",runtimeLabel:"Runtime",workspaceTermProject:"Project",workspaceTermMission:"Mission",coreModeOption:"Core Mode: {workspaceLabel} planning defaults",operationsModeOption:"Operations Mode: Mission-first terminology and flows",workspaceNamePlaceholder:"{workspaceLabel} name",workspaceDescriptionPlaceholder:"{workspaceLabel} description (optional)",saving:"Saving...",saveGlobalSetup:"Save Global Setup",saveWorkspaceSetup:"Save {workspaceLabel} Setup",globalSetupSaved:"Global setup saved.",workspaceSetupSaved:"{workspaceLabel} setup saved.",saveFailedWithStatus:"Failed to save setup ({status})",saveFailed:"Failed to save setup.",saveWorkspaceFailed:"Failed to save workspace profile.",retrySetupCheck:"Retry Setup Check",signOut:"Sign Out"}},Ov={taskForm:{commentsSectionTitle:"Actividad y comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Aun no hay comentarios. Inicia la conversacion.",you:"Tu",commentPlaceholder:"Escribe un comentario...",scheduledLabel:"Programado:",dueLabel:"Vence:",createdLabel:"Creado:",updatedLabel:"Actualizado:",completedLabel:"Completado:",emptyValue:"—",dueBeforeScheduled:"La fecha de vencimiento es anterior a la fecha programada.",overdue:"Esta tarea esta vencida."},schedule:{},taskList:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",sortByLabel:"Ordenar por:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",resetFiltersTitle:"Restablecer todos los filtros",archiveAllTitle:"Archivar todas las tareas completadas y canceladas",noTasksToArchiveTitle:"No hay tareas para archivar",archiveFinished:"Archivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchive:"Incluir archivo",noMatchingTasks:"No hay tareas coincidentes",noActiveTasks:"No hay tareas activas",addTaskToCategoryTitle:"Agregar tarea a {category}"},actionHeader:{saveChangesTitle:"Guardar cambios",update:"Actualizar",copyTaskIdTitle:"Haz clic para copiar el ID de la tarea",startWorking:"Comenzar trabajo",stopWorking:"Detener trabajo",unlockAndContinue:"Desbloquear y continuar",readyForReview:"Lista para revision",markComplete:"Marcar como completada",unmarkComplete:"Quitar completada",cancelTask:"Cancelar tarea",unmarkCancelled:"Quitar cancelada",archiveNow:"Archivar ahora",completeTaskToArchive:"Completa la tarea para archivar",clearFormTitle:"Limpiar formulario",clear:"Limpiar",addTaskTitle:"Agregar tarea",addTask:"Agregar tarea"},standalone:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",sortLabel:"Orden:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortComplexity:"Complejidad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridad",groupComplexity:"Complejidad",groupApproach:"Flujo de trabajo",groupAssignee:"Asignado a",groupStatus:"Estado",groupHierarchy:"Jerarquia",groupSchedule:"Calendario",showEmptyColumns:"Mostrar columnas vacias",compressEmptyColumns:"Comprimir columnas vacias",hideEmptyColumns:"Ocultar columnas vacias",expandCards:"Expandir tarjetas",compressCards:"Comprimir tarjetas",exitZenMode:"Salir del modo zen",enterZenMode:"Entrar en modo zen",toggleFilters:"Alternar filtros",addTask:"Agregar tarea",helpTutorial:"Ayuda y soporte",settings:"Configuracion",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",linksLabel:"Vinculos:",chooseLinksTitle:"Elige que tareas vinculadas se muestran",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchiveTitle:"Incluir tareas archivadas",includeArchive:"Incluir archivo",clearFilters:"Limpiar filtros",noTasksMatchFilters:"Ninguna tarea coincide con los filtros actuales.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Cambia Vinculos a Todas o limpia filtros.",visibleActiveTasksTitle:"Tareas activas visibles / total de tareas activas",totalActiveTasksTitle:"Total de tareas activas"},setup:{headingCheckFailed:"Fallo en verificacion de configuracion",headingGlobalRequired:"Configuracion global requerida",headingWorkspaceRequired:"Configuracion del espacio requerida",subtitleUnreadable:"Taskforce no pudo leer el estado de configuracion. Reintenta para continuar.",subtitleGlobalRequired:"Elige tu modo operativo predeterminado para continuar.",subtitleWorkspaceRequired:"Configura el perfil de tu espacio para continuar.",runtimeLabel:"Entorno",workspaceTermProject:"Proyecto",workspaceTermMission:"Mision",coreModeOption:"Modo Core: valores predeterminados de planificacion para {workspaceLabel}",operationsModeOption:"Modo Operaciones: terminologia y flujos orientados a Mision",workspaceNamePlaceholder:"Nombre de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descripcion de {workspaceLabel} (opcional)",saving:"Guardando...",saveGlobalSetup:"Guardar configuracion global",saveWorkspaceSetup:"Guardar configuracion de {workspaceLabel}",globalSetupSaved:"Configuracion global guardada.",workspaceSetupSaved:"Configuracion de {workspaceLabel} guardada.",saveFailedWithStatus:"Error al guardar la configuracion ({status})",saveFailed:"Error al guardar la configuracion.",saveWorkspaceFailed:"Error al guardar el perfil del espacio.",retrySetupCheck:"Reintentar verificacion",signOut:"Cerrar sesion"}},$v={taskForm:{commentsSectionTitle:"Atividade e comentarios",hideComments:"Ocultar comentarios",showComments:"Mostrar comentarios",noComments:"Ainda nao ha comentarios. Inicie a conversa.",you:"Voce",commentPlaceholder:"Digite um comentario...",scheduledLabel:"Agendado:",dueLabel:"Vencimento:",createdLabel:"Criado:",updatedLabel:"Atualizado:",completedLabel:"Concluido:",emptyValue:"—",dueBeforeScheduled:"A data de vencimento e anterior a data agendada.",overdue:"Esta tarefa esta atrasada."},schedule:{},taskList:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",sortByLabel:"Ordenar por:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",resetFiltersTitle:"Redefinir todos os filtros",archiveAllTitle:"Arquivar todas as tarefas concluidas e canceladas",noTasksToArchiveTitle:"Nao ha tarefas para arquivar",archiveFinished:"Arquivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchive:"Incluir arquivo",noMatchingTasks:"Nenhuma tarefa correspondente",noActiveTasks:"Nenhuma tarefa ativa",addTaskToCategoryTitle:"Adicionar tarefa a {category}"},actionHeader:{saveChangesTitle:"Salvar alteracoes",update:"Atualizar",copyTaskIdTitle:"Clique para copiar o ID da tarefa",startWorking:"Iniciar trabalho",stopWorking:"Parar trabalho",unlockAndContinue:"Desbloquear e continuar",readyForReview:"Pronto para revisao",markComplete:"Marcar como concluida",unmarkComplete:"Desmarcar concluida",cancelTask:"Cancelar tarefa",unmarkCancelled:"Desmarcar cancelada",archiveNow:"Arquivar agora",completeTaskToArchive:"Conclua a tarefa para arquivar",clearFormTitle:"Limpar formulario",clear:"Limpar",addTaskTitle:"Adicionar tarefa",addTask:"Adicionar tarefa"},standalone:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",sortLabel:"Ordenar:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortComplexity:"Complexidade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridade",groupComplexity:"Complexidade",groupApproach:"Fluxo de trabalho",groupAssignee:"Atribuido para",groupStatus:"Status",groupHierarchy:"Hierarquia",groupSchedule:"Agenda",showEmptyColumns:"Mostrar colunas vazias",compressEmptyColumns:"Comprimir colunas vazias",hideEmptyColumns:"Ocultar colunas vazias",expandCards:"Expandir cards",compressCards:"Comprimir cards",exitZenMode:"Sair do modo zen",enterZenMode:"Entrar no modo zen",toggleFilters:"Alternar filtros",addTask:"Adicionar tarefa",helpTutorial:"Ajuda e suporte",settings:"Configuracoes",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",linksLabel:"Vinculos:",chooseLinksTitle:"Escolha quais tarefas vinculadas sao exibidas",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchiveTitle:"Incluir tarefas arquivadas",includeArchive:"Incluir arquivo",clearFilters:"Limpar filtros",noTasksMatchFilters:"Nenhuma tarefa corresponde aos filtros atuais.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Mude Vinculos para Todas ou limpe os filtros.",visibleActiveTasksTitle:"Tarefas ativas visiveis / total de tarefas ativas",totalActiveTasksTitle:"Total de tarefas ativas"},setup:{headingCheckFailed:"Falha na verificacao da configuracao",headingGlobalRequired:"Configuracao global obrigatoria",headingWorkspaceRequired:"Configuracao do espaco obrigatoria",subtitleUnreadable:"Taskforce nao conseguiu ler o estado da configuracao. Tente novamente para continuar.",subtitleGlobalRequired:"Escolha seu modo operacional padrao para continuar.",subtitleWorkspaceRequired:"Configure o perfil do seu espaco para continuar.",runtimeLabel:"Ambiente",workspaceTermProject:"Projeto",workspaceTermMission:"Missao",coreModeOption:"Modo Core: padroes de planejamento para {workspaceLabel}",operationsModeOption:"Modo Operacoes: terminologia e fluxos orientados por Missao",workspaceNamePlaceholder:"Nome de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descricao de {workspaceLabel} (opcional)",saving:"Salvando...",saveGlobalSetup:"Salvar configuracao global",saveWorkspaceSetup:"Salvar configuracao de {workspaceLabel}",globalSetupSaved:"Configuracao global salva.",workspaceSetupSaved:"Configuracao de {workspaceLabel} salva.",saveFailedWithStatus:"Falha ao salvar configuracao ({status})",saveFailed:"Falha ao salvar configuracao.",saveWorkspaceFailed:"Falha ao salvar perfil do espaco.",retrySetupCheck:"Tentar verificacao novamente",signOut:"Sair"}},Ng=["en-US","es-419","pt-BR"],Xu="en-US",dp={"en-US":Fv,"es-419":Ov,"pt-BR":$v},Pg={en:"en-US",es:"es-419",pt:"pt-BR"};let Ji=Xu;function Uv(e){return e.split(".").filter(Boolean)}function up(e,t){let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return typeof n=="string"?n:void 0}function Mg(e){if(!e)return Xu;const t=Ng.find(s=>s.toLowerCase()===e.toLowerCase());if(t)return t;const n=e.split("-")[0]?.toLowerCase()||"";return Pg[n]||Xu}function mp(e,t){return t?e.replace(/\{([^}]+)\}/g,(n,s)=>{const o=t[s];return o==null?"":String(o)}):e}function Eg(){return Ji}function zv(){return[...Ng]}function Dg(e){const t=Mg(e);return Ji=t,t}function Hv(e){const t=typeof navigator<"u"?navigator.language:null;return Ji=Mg(t),Ji}function $e(e,t){const n=Uv(e),s=up(dp[Ji],n);if(s)return mp(s,t);const o=Ji.split("-")[0]?.toLowerCase()||"",l=Pg[o];if(l&&l!==Ji){const d=up(dp[l],n);if(d)return mp(d,t)}const i=up(dp[Xu],n);return i?mp(i,t):e}const Gv="default",Xi="bootstrap";function Vv(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function sf(e){const t=String(e||"").trim().toLowerCase();return t?`${(t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${Vv(t)}`:Xi}function Lg(e){const t=String(e||"").trim().toLowerCase();if(!t)return Xi;const n=t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return n?n.slice(0,96):Xi}function Bg(e){const t=String(e||"").trim();return t?sf(t):Xi}function qv(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?Xi:Bg(e.projectRoot)}function Kv(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const n=String(e.workspaceId||"").trim();return n&&!of(n)?sf(`cloud-workspace:${n}`):Xi}return Bg(e.projectRoot)}function of(e){return String(e||"").trim().toLowerCase()===Gv}const Zv={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function Yv(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function Jv(e){return Zv[Yv(e)]}const Sd={production:{appBaseUrl:"https://app.taskforcehq.ai",mcpBaseUrl:"https://mcp.taskforcehq.ai",label:"Production",themeToken:"production"},staging:{appBaseUrl:"https://staging-app.taskforcehq.ai",mcpBaseUrl:"https://staging-mcp.taskforcehq.ai",label:"Staging",themeToken:"staging"},performance:{appBaseUrl:"https://performance-app.taskforcehq.ai",mcpBaseUrl:"https://performance-mcp.taskforcehq.ai",label:"Performance",themeToken:"performance"}};function vm(e){const t=String(e||"").trim().toLowerCase();return t==="production"||t==="staging"||t==="performance"?t:null}function Qv(e){return vm(e)||"production"}function Xf(e){return Sd[Qv(String(e||""))]}function Xv(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;for(const[n,s]of Object.entries(Sd))if(new URL(s.appBaseUrl).hostname.toLowerCase()===t||new URL(s.mcpBaseUrl).hostname.toLowerCase()===t)return n;return null}function cf(e){const t=String(e||"").trim();if(!t)return null;try{return Xv(new URL(t).hostname)}catch{return null}}function eS(e){const t=cf(e);return t?Sd[t].mcpBaseUrl:null}function Ui(e,t){return String(e[t]||"").trim()}function eh(e,t,n){e.push(t),n?.(t)}function tS(e,t){const n=[],s=Ui(e,"ENV"),o=vm(s);if(o)return eh(n,`[Taskforce compat] ENV=${s} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${o} instead.`,t),{cloudEnvironment:o,warnings:n};const l=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:Ui(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:Ui(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:Ui(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:Ui(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:Ui(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:Ui(e,"TASKFORCE_BASE_URL")}];for(const i of l){if(!i.value)continue;const d=cf(i.value);if(d)return eh(n,`[Taskforce compat] ${i.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${d}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,t),{cloudEnvironment:d,warnings:n}}return{cloudEnvironment:null,warnings:n}}function Js(e,t){return String(e[t]||"").trim()}function aS(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function zc(e){return String(e||"").trim().replace(/\/+$/,"")}function nS(e){return String(e||"").trim().replace(/\/+$/,"")}function Io(...e){for(const t of e)if(String(t||"").trim())return String(t||"").trim();return""}function rS(e,t={}){const n=[],s=ve=>{n.push(ve),t.onWarning?.(ve)},o=aS(Js(e,"TASKFORCE_RUNTIME_MODE")),l=vm(Js(e,"TASKFORCE_CLOUD_ENVIRONMENT")),i=l?{cloudEnvironment:l}:tS(e,s),d=l||i.cloudEnvironment,m=zc(String(t.requestBaseUrl||"")),y=zc(Io(Js(e,"VITE_TASKFORCE_BASE_URL"),Js(e,"TASKFORCE_BASE_URL"))),k=zc(Js(e,"VITE_TASKFORCE_API_BASE_URL")),S=zc(Js(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),h=zc(Io(Js(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Js(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),g=zc(Js(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),v=nS(Js(e,"VITE_TASKFORCE_WS_BASE_URL")),A=d?Sd[d].appBaseUrl:"",_=d?Sd[d].mcpBaseUrl:"",I=Io(g,S,k,y,A),B=Io(h,_,I),V=Io(m,y,k,S,I),L=Io(m,k,y,I),J=Io(S,y,k,I),me=o==="local"?Io(v,m,k,y,g,S,A,I):Io(m,v,L,V,I);return{runtimeMode:o,cloudEnvironment:d,cloudBaseUrl:I,cloudMcpBaseUrl:B,baseUrl:V,apiBaseUrl:L,cloudAuthBaseUrl:J,wsBaseUrl:me,cloudAuthViaLocalProxy:o==="local"||!!g,warnings:n}}function lf(e){return rS({TASKFORCE_CLOUD_ENVIRONMENT:"",VITE_TASKFORCE_BASE_URL:e.VITE_TASKFORCE_BASE_URL,VITE_TASKFORCE_API_BASE_URL:e.VITE_TASKFORCE_API_BASE_URL,VITE_TASKFORCE_CLOUD_AUTH_BASE_URL:e.VITE_TASKFORCE_CLOUD_AUTH_BASE_URL,VITE_TASKFORCE_CLOUD_MCP_BASE_URL:e.VITE_TASKFORCE_CLOUD_MCP_BASE_URL,VITE_TASKFORCE_WS_BASE_URL:e.VITE_TASKFORCE_WS_BASE_URL})}function th(e){const t=String(e.workspaceId||"default").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"default",n=Number.isFinite(Number(e.epoch))?Math.max(0,Math.floor(Number(e.epoch))):0,s=String(e.seed||"session").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"session",o=String(e.phase||"bootstrap").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"bootstrap";return`tfb-${s}-${t}-e${n}-${o}`}function pp(e,t){const n=String(t||"").trim();if(!n)return e;const s=new Headers(e?.headers||void 0);return s.has("x-taskforce-bootstrap-trace-id")||s.set("x-taskforce-bootstrap-trace-id",n),{...e||{},headers:s}}const em="unassigned",Wg="agent",sS="user",oS=/^[0-9a-f]{8,}$/i;function Fg(e){const t=String(e||"").trim().toLowerCase();return t===Wg||t==="ai"||t.startsWith("ai-profile-")}function Og(e){const t=String(e||"").trim().toLowerCase();return!t||t===em||t==="none"||t==="null"||t===sS}function tm(e){return Fg(e)?"agent":Og(e)?"unassigned":"member"}function iS(e){const t=String(e.displayName||"").trim(),n=String(e.email||"").trim().toLowerCase();return t||n||String(e.userId||"").trim()||"Workspace member"}function si(){return[{value:em,label:"Unassigned",icon:"HelpCircle",color:"var(--text-secondary)",kind:"unassigned"}]}function cS(e){const t=new Map;for(const n of e){const s=String(n.userId||"").trim();s&&t.set(s,{value:s,label:iS(n),icon:"User",color:"#22c55e",kind:"member",avatarUrl:typeof n.avatarUrl=="string"&&n.avatarUrl.trim().length>0?n.avatarUrl.trim():null})}return wd(Array.from(t.values()))}function wd(e){const t=new Map;for(const s of si())t.set(s.value,s);for(const s of Array.isArray(e)?e:[]){const o=String(s?.value||"").trim(),l=typeof s?.archivedAt=="string"?s.archivedAt.trim():"";!o||l||o===em||o===Wg||t.set(o,{value:o,label:String(s.label||o).trim()||o,icon:String(s.icon||(s.kind==="agent"?"Bot":"User")),color:String(s.color||(s.kind==="agent"?"#8b5cf6":"#22c55e")),kind:s.kind==="agent"?"agent":"member",avatarUrl:typeof s.avatarUrl=="string"&&s.avatarUrl.trim().length>0?s.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(s.avatarRevision))?Math.max(0,Math.floor(Number(s.avatarRevision))):null,avatarUpdatedAt:typeof s.avatarUpdatedAt=="string"&&s.avatarUpdatedAt.trim().length>0?s.avatarUpdatedAt.trim():null,username:typeof s.username=="string"&&s.username.trim().length>0?s.username.trim():null,archivedAt:null,createdAt:typeof s.createdAt=="string"&&s.createdAt.trim().length>0?s.createdAt.trim():null,updatedAt:typeof s.updatedAt=="string"&&s.updatedAt.trim().length>0?s.updatedAt.trim():null})}const n=[em];return Array.from(t.values()).sort((s,o)=>{const l=n.indexOf(s.value),i=n.indexOf(o.value);return l>=0||i>=0?l<0?1:i<0?-1:l-i:s.label.localeCompare(o.label,void 0,{sensitivity:"base"})})}function lS(e,t){const n=String(t||"").trim();if(!n||e.some(l=>l.value===n))return e;const s=n.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),o=s?s.split(" ").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join(" "):n;if(tm(n)==="agent"){const l=String(n).toLowerCase().startsWith("ai-profile-")&&s.split(" ").every(i=>oS.test(i));return wd([...e,{value:n,label:l?"AI":o||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return tm(n)==="member"?wd([...e,{value:n,label:o||n,icon:"User",color:"#22c55e",kind:"member"}]):e}function $g(e){const t=Array.isArray(e)?e.filter(Boolean):[];return wd(t)}function pd(e,t){const n=String(e||"").trim(),o=$g(t).find(l=>l.value===n);return o?o.label:Fg(n)?"AI":Og(n)?"Unassigned":n||"Unassigned"}const Ug="taskforce.workspaceContext.v2",dS="taskforce.uiState.app.v1",uS="taskforce.bootstrapDebug.v1",ah=5e3,Au=new Map;function mS(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(uS)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function zt(e,t){if(!mS())return;console.info("[Taskforce Bootstrap]",e,t&&typeof t=="object"?t:{})}function pS(e,t){const n=String(e).trim()||"default";return`${String(t).trim()||"default"}::${n}`}async function df(e){const t=String(e.stateKey||"default").trim()||"default",n=String(e.workspaceId||"").trim(),s=e.patch&&typeof e.patch=="object"?e.patch:{},o=JSON.stringify(s),l=pS(t,n||"default"),i=Date.now(),d=Au.get(l);if(d&&d.serializedPatch===o){if(d.status==="success"&&e.skipIfUnchanged!==!1)return zt("ui_state_persist_skipped",{stateKey:t,workspaceId:n||"default",reason:"unchanged"}),{skipped:!0,reason:"unchanged"};if(e.respectFailureCooldown!==!1&&d.retryAfter>i)return zt("ui_state_persist_skipped",{stateKey:t,workspaceId:n||"default",reason:"cooldown",retryAfterMs:d.retryAfter-i}),{skipped:!0,reason:"cooldown"}}try{const m=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json",...e.headers||{}},credentials:"include",body:JSON.stringify({stateKey:t,...n?{workspaceId:n}:{},patch:s})}),y=await m.json().catch(()=>({}));if(m.ok&&y?.success!==!1)return Au.set(l,{serializedPatch:o,status:"success",retryAfter:0}),{skipped:!1,response:m,payload:y};if(Au.set(l,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??ah)}),zt("ui_state_persist_failed",{stateKey:t,workspaceId:n||"default",status:m.status,error:String(y?.error||"")}),e.throwOnError)throw new Error(String(y?.error||`Failed to persist UI state (${m.status})`));return{skipped:!1,response:m,payload:y}}catch(m){if(Au.set(l,{serializedPatch:o,status:"failure",retryAfter:i+(e.failureRetryMs??ah)}),zt("ui_state_persist_failed",{stateKey:t,workspaceId:n||"default",error:m instanceof Error?m.message:String(m)}),e.throwOnError)throw m;return{skipped:!1,payload:null}}}function uf(e){const t=sf(e);return`${Ug}.${t}`}function zg(e){const t=Lg(e);return`${Ug}.${t}`}function Dp(e){if(typeof window>"u")return"";try{const t=uf(e),n=String(window.localStorage.getItem(t)||"").trim();if(n&&n.length<=120&&!/\s/.test(n))return n;const s=zg(e),o=String(window.localStorage.getItem(s)||"").trim();return o&&o.length<=120&&!/\s/.test(o)?(window.localStorage.setItem(t,o),o):""}catch{return""}}function fS(e,t){if(typeof window>"u")return;const n=String(e||"").trim();try{if(!n||of(n))return;const s=uf(t),o=String(window.localStorage.getItem(s)||"").trim();if(!n&&o&&o.toLowerCase()!=="default")return;window.localStorage.setItem(s,n)}catch{}}function nh(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(uf(e)),window.localStorage.removeItem(zg(e))}catch{}}function Hg(e){const t=Lg(e);return`${dS}.${t}`}function rh(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Hg(e));if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function hS(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Hg(t),JSON.stringify(e))}catch{}}const Lp="taskforce.localMutationActorUserId.v1";function Gg(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function gS(e){const t=String(e||"").trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function od(e){if(!(typeof window>"u"))try{const t=String(e||"").trim();if(!t||t==="anonymous"){window.sessionStorage.removeItem(Lp);return}window.sessionStorage.setItem(Lp,t)}catch{}}function mf(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Lp)||"").trim()}catch{return""}}function yS(e,t){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!gS(window.location.hostname))return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function kS(e,t,n){if(!yS(e,t))return n;const s=mf();if(!s)return n;const o=new Headers(n?.headers||void 0);return o.has("x-taskforce-user-id")||o.set("x-taskforce-user-id",s),{...n,headers:o}}function vS(e,t){if(!e.startsWith("/"))return e;const n=Gg(t);return n?`${n}${e}`:e}async function LO(e,t,n){const s=vS(e,n),o=Gg(n).length>0,l=kS(e,s,t),i=typeof performance<"u"?performance.now():Date.now();try{const d=await fetch(s,l);if(!(o&&s!==e&&e.startsWith("/api/taskforce/")&&(d.status===401||d.status===403)))return d;zt("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,status:d.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)});try{const y=await fetch(e,l);return zt("taskforce_api_auth_fallback_completed",{path:e,primaryUrl:s,fallbackUrl:e,primaryStatus:d.status,fallbackStatus:y.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),y}catch{return zt("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:s,fallbackUrl:e,status:d.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),d}}catch(d){if(!o||!e.startsWith("/"))throw d;zt("taskforce_api_network_fallback_retry",{path:e,primaryUrl:s,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i),error:d instanceof Error?d.message:String(d)});const m=await fetch(e,l);return zt("taskforce_api_network_fallback_completed",{path:e,primaryUrl:s,fallbackUrl:e,fallbackStatus:m.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-i)}),m}}function SS(e){const t=Number(e?.status);return Number.isFinite(t)&&t>0?Math.floor(t):0}async function al(e){try{const t=await e,n=await t.text().catch(()=>"");let s={};if(n)try{s=JSON.parse(n)}catch{s={error:!t.ok&&t.statusText?`${t.status} ${t.statusText}`:n.slice(0,400)}}else!t.ok&&t.statusText&&(s={error:`${t.status} ${t.statusText}`});const o=t.headers.get("retry-after");let l;if(o){const i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>0)l=i*1e3;else{const d=Date.parse(o);if(Number.isFinite(d)){const m=d-Date.now();m>0&&(l=m)}}}return{ok:t.ok,status:t.status,data:s,retryAfterMs:l}}catch(t){return{ok:!1,status:SS(t),data:{}}}}async function wS(e){return al(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function bS(e,t){return al(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function fp(e,t){return al(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}))}async function sh(e,t){return al(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function _S(e,t){const n=new URLSearchParams({limit:String(t.limit),workspaceId:t.workspaceId});t.cursor&&n.set("cursor",t.cursor),t.repairMode===!0&&n.set("repair","1");const s=e("/api/taskforce/sync/workspace/pull"),o=s.includes("?")?"&":"?";return al(fetch(`${s}${o}${n.toString()}`,{method:"GET",credentials:"include"}))}async function CS(e,t){return al(fetch(e("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...t,...t.repairMode===!0?{repair:!0}:{}})}))}async function Bp(e,t,n){const s=JSON.stringify({workspaceId:e,changes:t,workspaceMembers:Array.isArray(n?.workspaceMembers)?n.workspaceMembers:void 0,...n?.repairMode===!0?{repair:!0}:{},bootstrapSnapshot:n?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(n.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?n.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),o="/api/taskforce/sync/workspace/apply-local",l=[];try{const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:s});if(i.ok){const y=await i.json().catch(()=>({}));return{ok:!0,status:i.status,data:y,failures:l}}const d=await i.text().catch(()=>"");let m={};if(d)try{m=JSON.parse(d)}catch{m={error:d.slice(0,400)}}else i.statusText&&(m={error:`${i.status} ${i.statusText}`});return l.push(`${o}:${i.status}`),{ok:!1,status:i.status,data:m,failures:l}}catch{l.push(`${o}:network`)}return{ok:!1,status:0,data:{},failures:l}}const Wp="V1:AESGCM:",pf="AES-GCM",AS=12;async function Vg(e){const t=Buffer.from(e,"base64");if(t.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",t,{name:pf},!1,["encrypt","decrypt"])}async function oh(e,t){if(!e)return e;const n=crypto.getRandomValues(new Uint8Array(AS)),s=await Vg(t),l=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:pf,iv:n},s,l),d=Buffer.from(i).toString("base64"),m=Buffer.from(n).toString("base64");return`${Wp}${m}:${d}`}async function ih(e,t){if(!e||!e.startsWith(Wp))return e;const n=e.slice(Wp.length),[s,o]=n.split(":");if(!s||!o)throw new Error("Malformed encrypted document payload.");const l=Buffer.from(s,"base64"),i=Buffer.from(o,"base64"),d=await Vg(t);try{const m=await crypto.subtle.decrypt({name:pf,iv:l},d,i);return new TextDecoder("utf-8").decode(m)}catch(m){throw new Error(`Failed to decrypt document: ${m.message}`)}}var qc={};function Qr(e){return e&&typeof e=="object"?e:{}}function Bs(e){const t=Number(e||0);return t===0||t===429||t>=500}function ch(e,t){const n=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim();return n==="WORKSPACE_ID_ALREADY_EXISTS"||s.toLowerCase()==="workspace id already exists"?"This workspace is already linked to another cloud account. Sign in with the original account, ask the workspace owner to grant you access, or keep this workspace local-only.":s||`Workspace provisioning failed (${t})`}function xS(e,t){if(t!==400)return!1;const n=String(e.code||"").trim().toUpperCase(),s=String(e.error||"").trim().toLowerCase();return n==="WORKSPACE_ID_REQUIRED"&&s.includes("no cloud workspace is selected")}async function IS(e){if(!e.cloudAuthConfigured)return{success:!1,error:"Cloud auth endpoint is not configured."};if(e.runtimeMode!=="local")return{success:!1,error:"Workspace sync is only available in local runtime."};if(!e.isAuthenticated)return{success:!1,error:"Authentication required."};try{let t=await fp(e.resolveCloudAuthUrl,e.workspaceId);if(t.ok)return{success:!0,provisioned:!1};const n=Qr(t.data);if(t.status===401)return{success:!1,statusCode:401,transient:!1,error:String(n.error||"Authentication required for workspace sync.")};if(t.status===429)return{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(n.error||"Workspace sync rate limited. Please retry later.")};if(xS(n,t.status)){const s=await sh(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=Qr(s.data);return{success:!1,statusCode:s.status,transient:Bs(s.status),retryAfterMs:s.retryAfterMs,error:ch(o,s.status)}}if(t=await fp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=Qr(t.data);return t.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:t.status===429?{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:t.status,transient:Bs(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}if(t.status===409&&n.code==="WORKSPACE_ID_MISMATCH"){if(e.allowProvisionOnMismatch===!1)return{success:!1,statusCode:409,transient:!1,error:String(n.error||"Selected cloud workspace could not be attached to this local workspace.")};const s=await sh(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const o=Qr(s.data);return{success:!1,statusCode:s.status,error:ch(o,s.status)}}if(t=await fp(e.resolveCloudAuthUrl,e.workspaceId),!t.ok){const o=Qr(t.data);return t.status===401?{success:!1,statusCode:401,transient:!1,error:String(o.error||"Authentication required for workspace sync.")}:t.status===429?{success:!1,statusCode:429,retryAfterMs:t.retryAfterMs,transient:!0,error:String(o.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:t.status,transient:Bs(t.status),error:String(o.error||`Workspace sync handshake failed (${t.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:t.status,transient:Bs(t.status),error:String(n.error||`Workspace sync handshake failed (${t.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}async function TS(e,t){const n=JSON.stringify([e,t]);try{const s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{let s=2166136261;for(let l=0;l<n.length;l+=1)s^=n.charCodeAt(l),s=Math.imul(s,16777619);const o=(s>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${o}`}}async function RS(e){const t=e.payload.changes.length,n=e.payload.deleteTaskIds.size,s=await TS(e.workspaceId,e.payload.changes);let o=0,l=e.payload.changes;if(typeof process<"u"&&qc?.TASKFORCE_SYNC_KEY){const S=qc.TASKFORCE_SYNC_KEY,h=[];for(const g of l)g.op==="document-upsert"&&typeof g.content=="string"?h.push({...g,content:await oh(g.content,S)}):g.op==="asset-upsert"&&typeof g.contentBase64=="string"&&g.contentBase64.length>0?h.push({...g,contentBase64:await oh(g.contentBase64,S)}):h.push(g);l=h}const i=async()=>{const S=Date.now(),h=await CS(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,idempotencyKey:s,changes:l,repairMode:e.repairMode===!0});return o+=Date.now()-S,h};let d=await i();if(!d.ok&&(d.status===403||d.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(d=await i()),!d.ok){const S=Qr(d.data);return{success:!1,status:d.status,error:typeof S.error=="string"?S.error:void 0,code:typeof S.code=="string"?S.code:void 0,retryAfterMs:d.retryAfterMs,transient:Bs(d.status),requestMs:o,changeCount:t,deleteCount:n,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}const m=Qr(d.data),y=Array.isArray(m.emittedEventIds)?Array.from(new Set(m.emittedEventIds.map(S=>String(S||"").trim()).filter(Boolean))):[],k=Array.isArray(m.appliedTaskUpserts)?m.appliedTaskUpserts.map(S=>{const h=S&&typeof S=="object"?S:{},g=h.task&&typeof h.task=="object"?h.task:null,v=String(g?.id||"").trim();return!g||!v?null:{archived:h.archived===!0,task:g}}).filter(S=>!!S):[];return{success:!0,syncedAt:new Date().toISOString(),requestMs:o,changeCount:t,deleteCount:n,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:e.payload.pushedWatermarks,pushedTaskChangeKeys:e.payload.pushedTaskChangeKeys??new Map,emittedEventIds:y,appliedTaskUpserts:k}}async function jS(e){let t=e.cursor,n=!0,s=0,o=0,l=0,i=0;const d=new Set;let m=!1,y=!1,k=!1,S=!1;const h=new Set,g=new Set,v=new Set;let A=null;const _=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;try{for(;n&&s<_;){const I=async()=>{const re=Date.now(),x=await _S(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:t,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0});return l+=Date.now()-re,x};let B=await I();if(!B.ok&&B.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(B=await I()),!B.ok){const re=Qr(B.data);return{success:!1,kind:"pull_http",status:B.status,errorCode:typeof re.code=="string"?re.code:void 0,error:typeof re.error=="string"?re.error:void 0,retryAfterMs:B.retryAfterMs,transient:Bs(B.status),cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),serverDiagnostics:null}}const V=B.data||{},L=Array.isArray(V?.changes)?V.changes:[],J=V?.diagnostics&&typeof V.diagnostics=="object"?V.diagnostics:null;A=J;const me=Array.isArray(V?.workspaceMembers),ve=me?V.workspaceMembers:void 0;for(const re of L){if(re.op==="upsert"){re?.archived===!0||re?.task?.isArchived===!0?y=!0:m=!0;continue}if(re.op==="annotated-attachment-session-upsert"){const K=String(re?.session?.id||"").trim();K&&v.add(K);continue}if(re.op==="task-event-upsert"||re.op==="entity-event-upsert"){k=!0;continue}if(re.op==="initiative-upsert"||re.op==="workstream-upsert"){S=!0;continue}if(re.op==="document-upsert"){if(typeof re.content=="string"&&typeof process<"u"&&qc?.TASKFORCE_SYNC_KEY)try{re.content=await ih(re.content,qc.TASKFORCE_SYNC_KEY)}catch{const K=String(re.path||"").trim();K&&h.add(K)}continue}if(re.op==="asset-upsert"){if(typeof re.contentBase64=="string"&&typeof process<"u"&&qc?.TASKFORCE_SYNC_KEY)try{re.contentBase64=await ih(re.contentBase64,qc.TASKFORCE_SYNC_KEY)}catch{const K=String(re.path||"").trim();K&&h.add(K)}continue}if(re.op!=="delete")continue;const x=String(re.taskId||"").trim();x&&d.add(x)}if(e.onPagePulled&&e.onPagePulled(),L.length>0||me){const re=Date.now(),x=await Bp(e.workspaceId,L,{...me?{workspaceMembers:ve}:{},repairMode:e.repairMode===!0}),K=x.failures;if(!x.ok){i+=Date.now()-re;const pe=Qr(x.data);if(K.some(O=>O.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:K,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,documentDecryptFailures:Array.from(h),serverDiagnostics:J};const M=K.some(O=>{if(O.endsWith(":network"))return!0;const de=O.split(":").pop()||"",ge=Number.parseInt(de,10);return Number.isFinite(ge)&&(ge===429||ge>=500)});return{success:!1,kind:"apply_all_candidates",status:x.status||void 0,transient:M,error:String(pe.error||"").trim()||void 0,failures:K,hasTransientApplyFailure:M,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:A}}const ue=Qr(x.data);if(ue.success===!1)return i+=Date.now()-re,{success:!1,kind:"apply_payload",transient:!1,error:String(ue.error||"Workspace sync apply failed."),cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:A};if(i+=Date.now()-re,o+=L.length,Array.isArray(ue.emittedEventIds))for(const pe of ue.emittedEventIds)g.add(String(pe));e.onChangesApplied&&e.onChangesApplied(L.length)}V&&"nextCursor"in V&&(V.nextCursor===null||typeof V.nextCursor=="string")&&(t=V.nextCursor),n=!!V?.hasMore,s+=1}if(e.bootstrap){const I=Date.now(),B=await Bp(e.workspaceId,[],{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(v)}}),V=B.failures;if(!B.ok){i+=Date.now()-I;const L=Qr(B.data);if(V.some(ve=>ve.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:V,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:A};const me=V.some(ve=>{if(ve.endsWith(":network"))return!0;const re=ve.split(":").pop()||"",x=Number.parseInt(re,10);return Number.isFinite(x)&&(x===429||x>=500)});return{success:!1,kind:"apply_all_candidates",status:B.status||void 0,transient:me,error:String(L.error||"").trim()||void 0,failures:V,hasTransientApplyFailure:me,cursor:t,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:A}}i+=Date.now()-I}return{success:!0,syncedAt:new Date().toISOString(),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:A}}catch(I){return{success:!1,kind:"exception",status:0,transient:!0,error:String(I?.message||I||"Workspace sync pull failed unexpectedly."),cursor:t||null,pages:s,appliedChanges:o,pullRequestMs:l,applyMs:i,pulledDeleteTaskIds:d,pulledActiveUpserts:m,pulledArchivedUpserts:y,pulledTaskEventUpserts:k,pulledPlanningUpserts:S,documentDecryptFailures:Array.from(h),emittedEventIds:Array.from(g),serverDiagnostics:null}}}async function NS(e){const t=await wS(e.resolveCloudAuthUrl);if(!t.ok){const h=Number(t.status||0);return{success:!1,error:`Sync pull failed (${t.status})`,statusCode:t.status,retryAfterMs:t.retryAfterMs,transient:Bs(h)}}const n=Qr(t.data),s=n.settings&&typeof n.settings=="object"?n.settings:{},o=typeof n.updatedAt=="string"&&n.updatedAt.trim().length>0?n.updatedAt.trim():null,l=e.getLocalUpdatedAt(e.userId),i=l?Date.parse(l):NaN,d=o?Date.parse(o):NaN;if(!l&&e.preferCloudOnFirstSync&&Number.isFinite(d))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};if(Number.isFinite(d)&&(!Number.isFinite(i)||d>i))return await e.applyRemoteSettings(s),{success:!0,mode:"pulled",updatedAt:o};const m=l||new Date().toISOString(),y=await bS(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:m});if(!y.ok){const h=Number(y.status||0);return{success:!1,error:`Sync push failed (${y.status})`,statusCode:y.status,retryAfterMs:y.retryAfterMs,transient:Bs(h)}}const k=Qr(y.data);return{success:!0,mode:"pushed",updatedAt:typeof k.updatedAt=="string"&&k.updatedAt.trim().length>0?k.updatedAt.trim():m}}function PS(e){const t=Math.max(1,Math.floor(Number(e)||1)),n=Math.min(12e4,1500*2**Math.max(0,t-1)),s=Math.floor(n*(.15*Math.random()));return n+s}const MS=["chat_app","ide","cli","coding_tool","agent"],BO=["chat_app","ide","cli","coding_tool","agent","unclassified"],ES={chat_app:"Chat App",ide:"IDE",cli:"CLI",coding_tool:"Coding Tool",agent:"Agent"},DS={chat_app:"Chat Apps",ide:"IDEs",cli:"CLI",coding_tool:"Coding Tools",agent:"Agents",unclassified:"Unclassified"};function LS(e){return typeof e=="string"&&MS.includes(e)}function qg(e){if(typeof e!="string")return null;const t=e.trim();return t==="other"?"agent":LS(t)?t:null}function WO(e){return ES[e]}function FO(e){return e??"unclassified"}function OO(e){return DS[e]}const BS=["cloud_metered","local_unmetered"],WS={cloud_metered:"Cloud MCP",local_unmetered:"Local MCP"};function FS(e){return typeof e=="string"&&BS.includes(e)}function Kg(e){if(typeof e!="string")return null;const t=e.trim();return FS(t)?t:null}function $O(e){return WS[e]}function ri(e){if(e==null)return;const t=String(e).trim();return t.length>0?t:void 0}function mn(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function bd(e){return ri(e)}function am(e){return mn(e)}function Er(e){return mn(e)}function Xc(e){const t=mn(e);return t&&t.startsWith("/api/taskforce/context/")?t:null}function xu(e){return ri(e)}function Iu(e){if(e!==void 0)return mn(e)}function OS(e){return typeof e=="boolean"?e:void 0}function Tu(e,t){if(e===void 0)return;if(e===null||e==="")return t?.nullable?null:void 0;const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return t?.nullable?null:void 0;const s=Math.floor(n);return Number.isFinite(t?.min)&&s<Number(t?.min)?t?.nullable?null:void 0:s}function $S(e){if(!e||typeof e!="object"||Array.isArray(e))return;const n=Object.entries(e).reduce((s,[o,l])=>Array.isArray(l)?(s[o]=l.map(i=>String(i??"")),s):(l==null||(s[o]=String(l)),s),{});return Object.keys(n).length>0?n:{}}function US(e){return Array.isArray(e)?e:void 0}function zS(e){return Array.isArray(e)?e:void 0}function HS(e){return Array.isArray(e)?e:void 0}function Zg(e){const t=e&&typeof e=="object"?e:{};return{id:String(t.id||"").trim(),title:String(t.title||"").trim(),description:t.description===void 0?void 0:t.description||null,status:String(t.status||"task").trim()||"task",priority:Tu(t.priority,{min:1})??void 0,complexity:Tu(t.complexity,{min:1,nullable:!0}),type:String(t.type||"").trim(),category:String(t.category||"").trim(),approach:xu(t.approach),canceledReason:t.canceledReason===void 0?void 0:t.canceledReason||null,createdAt:String(t.createdAt||"").trim(),updatedAt:xu(t.updatedAt),completedAt:t.completedAt===void 0?void 0:t.completedAt||null,isArchived:OS(t.isArchived),taxonomies:$S(t.taxonomies),createdBy:xu(t.createdBy),assignee:xu(t.assignee),scheduledDate:Iu(t.scheduledDate),dueDate:Iu(t.dueDate),scheduledWeekKey:Iu(t.scheduledWeekKey),orderInDay:Tu(t.orderInDay,{min:0,nullable:!0}),workstreamId:Iu(t.workstreamId),referenceNumber:Tu(t.referenceNumber,{min:1,nullable:!0}),comments:US(t.comments),attachments:zS(t.attachments),checklistItems:HS(t.checklistItems)}}function GS(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=Object.entries(e).filter(([s])=>String(s||"").trim().length>0).sort(([s],[o])=>s.localeCompare(o)),n={};for(const[s,o]of t){if(Array.isArray(o)){n[s]=o.map(l=>String(l??"")).sort((l,i)=>l.localeCompare(i));continue}o!=null&&(n[s]=String(o))}return n}function VS(e){return Array.isArray(e)?e.map(t=>{const n=t&&typeof t=="object"?t:{};return{id:String(n.id||"").trim(),title:String(n.title||"").trim(),isCompleted:!!n.isCompleted,order:n.order===void 0||n.order===null?"":String(n.order)}}).sort((t,n)=>{const s=Number.parseInt(t.order,10),o=Number.parseInt(n.order,10);return Number.isFinite(s)&&Number.isFinite(o)&&s!==o?s-o:t.title!==n.title?t.title.localeCompare(n.title):t.id.localeCompare(n.id)}):[]}function qS(e){return Array.isArray(e)?e.map(t=>{const n=t&&typeof t=="object"?t:null;return{id:String(n?.id||"").trim(),author:String(n?.author||"").trim(),submittedAuthor:ri(n?.submittedAuthor)||"",text:String(n?.text||""),timestamp:Er(n?.timestamp)||"",actor:n?.actor??null}}).sort((t,n)=>t.timestamp!==n.timestamp?t.timestamp.localeCompare(n.timestamp):t.id!==n.id?t.id.localeCompare(n.id):t.author!==n.author?t.author.localeCompare(n.author):t.text.localeCompare(n.text)):[]}function KS(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t.trim(),fsPath:"",caption:"",displayName:"",originalFilename:"",assetId:"",referenceNumber:"",taskId:"",timestamp:""};const n=t&&typeof t=="object"?t:null;return{path:String(n?.path||"").trim(),fsPath:ri(n?.fsPath)||"",caption:ri(n?.caption)||"",displayName:ri(n?.displayName)||"",originalFilename:ri(n?.originalFilename)||"",assetId:bd(n?.assetId)||"",referenceNumber:n?.referenceNumber===void 0||n.referenceNumber===null?"":String(n.referenceNumber),taskId:am(n?.taskId)||"",timestamp:Er(n?.timestamp)||""}}).sort((t,n)=>t.path!==n.path?t.path.localeCompare(n.path):t.assetId!==n.assetId?t.assetId.localeCompare(n.assetId):t.timestamp!==n.timestamp?t.timestamp.localeCompare(n.timestamp):JSON.stringify(t).localeCompare(JSON.stringify(n))):[]}function ZS(e,t){const n=Zg(e);return JSON.stringify({id:n.id,title:n.title,description:mn(n.description)||"",category:n.category,type:n.type,priority:n.priority===void 0||n.priority===null?"":String(n.priority),complexity:n.complexity===void 0||n.complexity===null?"":String(n.complexity),status:n.status,approach:ri(n.approach)||"",canceledReason:mn(n.canceledReason)||"",createdAt:n.createdAt,completedAt:Er(n.completedAt)||"",taxonomies:GS(n.taxonomies),createdBy:bd(n.createdBy)||"",assignee:bd(n.assignee)||"",scheduledDate:mn(n.scheduledDate)||"",dueDate:mn(n.dueDate)||"",scheduledWeekKey:mn(n.scheduledWeekKey)||"",orderInDay:n.orderInDay===void 0||n.orderInDay===null?"":String(n.orderInDay),workstreamId:am(n.workstreamId)||"",referenceNumber:n.referenceNumber===void 0||n.referenceNumber===null?"":String(n.referenceNumber),comments:qS(n.comments),attachments:KS(n.attachments),checklistItems:VS(n.checklistItems),isArchived:t?"1":"0"})}function YS(...e){return e.reduce((t,n)=>{const s=Er(n)||"";return t?s&&s>t?s:t:s},"")}function JS(e){const t=e||{};return YS(t.createdAt,t.updatedAt,t.lastActiveAt,t.archivedAt,t.rosterStateUpdatedAt)}function QS(e){const t=e||{};return JSON.stringify({id:String(t.id||"").trim(),workspaceId:String(t.workspaceId||"").trim(),profileToken:String(t.profileToken||"").trim(),name:String(t.name||"").trim(),username:String(t.username||"").trim(),icon:String(t.icon||"Bot").trim()||"Bot",color:String(t.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:Xc(t.avatarUrl)||"",avatarSourceUrl:Xc(t.avatarSourceUrl)||"",avatarRevision:Number.isFinite(Number(t.avatarRevision))?Math.max(0,Math.floor(Number(t.avatarRevision))):0,avatarUpdatedAt:Er(t.avatarUpdatedAt)||"",description:mn(t.description)||"",role:mn(t.role)||"",provider:mn(t.provider)||"",model:mn(t.model)||"",surfaceType:mn(t.surfaceType)||"",seatScope:mn(t.seatScope)||"",providerMetadata:t.providerMetadata&&typeof t.providerMetadata=="object"&&!Array.isArray(t.providerMetadata)?t.providerMetadata:null,archivedAt:Er(t.archivedAt)||"",archivedBy:bd(t.archivedBy)||"",archivedReason:mn(t.archivedReason)||"",mergedIntoProfileId:bd(t.mergedIntoProfileId)||"",rosterStateUpdatedAt:Er(t.rosterStateUpdatedAt)||"",createdAt:Er(t.createdAt)||"",updatedAt:Er(t.updatedAt)||"",lastActiveAt:Er(t.lastActiveAt)||""})}const ys={kind:"task",getId:e=>String(e?.id||"").trim(),getWatermark:e=>String(e?.updatedAt||e?.createdAt||"").trim(),getChangeKey:e=>ZS(e,!!e?.isArchived)},fd={kind:"ai-profile",getId:e=>String(e?.id||"").trim(),getWatermark:e=>JS(e),getChangeKey:e=>QS(e)};function lh(e,t,n){const s=e.getId(t);if(!s)return!1;const o=e.getChangeKey(t),l=n?.watermarks;if(!l||l.size===0||!l.has(s))return!0;const d=n?.changeKeys?.get(s);return typeof d=="string"?d!==o:(l.get(s)||"")!==o}function dh(e){return Zg(e)}function uh(e,t){const n=e??t;return new Set(Array.from(n).map(s=>String(s||"").trim()).filter(s=>s.length>0))}function XS(e){return[...e].sort((t,n)=>{const s=String(t?.createdAt||"").trim(),o=String(n?.createdAt||"").trim(),l=s.localeCompare(o);return l!==0?l:String(t?.id||"").trim().localeCompare(String(n?.id||"").trim())})}function mh(e){return[...e].sort((t,n)=>{const s=String(t?.id||"").trim(),o=String(n?.id||"").trim();return s.localeCompare(o)})}function nm(e){return Array.isArray(e)?e:void 0}function ew(e){const t=new Date().toISOString(),n=new Set(Array.from(e.pendingDeletedTaskIds).map(c=>String(c||"").trim()).filter(c=>c.length>0)),s=new Map(Array.from(e.pendingDeletedTaskWatermarks||new Map).map(([c,Y])=>[String(c||"").trim(),String(Y||"").trim()]).filter(([c,Y])=>c.length>0&&Number.isFinite(Date.parse(Y)))),o=e.lastPushedWatermarks,l=e.lastPushedTaskChangeKeys,i=(c,Y)=>(c?.referenceNumber===void 0||c?.referenceNumber===null)&&Number.isFinite(Number(c?.localReferenceNumber))?!0:lh(ys,{...c,isArchived:Y},{watermarks:o,changeKeys:l}),d=mh(e.tasks||[]),m=mh(e.archivedTasks||[]),y=new Map,k=new Map,S=new Map,h=new Map,g=d.filter(c=>!n.has(String(c?.id||"").trim())&&i(c,!1)).map(c=>{const Y=String(c?.id||"").trim(),ye=ys.getWatermark(c),Ie=ys.getChangeKey({...c,isArchived:!1});return Y&&(S.set(Y,ye),h.set(Y,Ie)),{op:"upsert",archived:!1,task:dh(c)}}),v=m.filter(c=>!n.has(String(c?.id||"").trim())&&i(c,!0)).map(c=>{const Y=String(c?.id||"").trim(),ye=ys.getWatermark(c),Ie=ys.getChangeKey({...c,isArchived:!0});return Y&&(S.set(Y,ye),h.set(Y,Ie)),{op:"upsert",archived:!0,task:dh(c)}}),A=new Set;for(const c of e.tasks||[]){const Y=String(c?.id||"").trim();Y&&(A.add(Y),y.set(Y,ys.getWatermark(c)),k.set(Y,ys.getChangeKey({...c,isArchived:!1})))}for(const c of e.archivedTasks||[]){const Y=String(c?.id||"").trim();Y&&(A.add(Y),y.set(Y,ys.getWatermark(c)),k.set(Y,ys.getChangeKey({...c,isArchived:!0})))}const _=Array.from(e.lastPushedTaskIds).filter(c=>!A.has(c)).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t})),I=Array.from(n).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t})),B=new Set([..._.map(c=>String(c.taskId)),...I.map(c=>String(c.taskId))]),V=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),L=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>[String(c?.id||"").trim(),String(c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),J=e.lastPushedInitiativeWatermarks,me=!J||J.size===0,ve=(Array.isArray(e.initiatives)?e.initiatives:[]).map(c=>({op:"initiative-upsert",initiative:{id:String(c?.id||"").trim(),referenceNumber:Number.isFinite(Number(c?.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,referenceLabel:typeof c?.referenceLabel=="string"&&c.referenceLabel.trim().length>0?c.referenceLabel.trim():void 0,title:String(c?.title||"").trim(),description:typeof c?.description=="string"?c.description:null,ownerId:typeof c?.ownerId=="string"&&c.ownerId.trim().length>0?c.ownerId.trim():null,createdAt:String(c?.createdAt||"").trim(),updatedAt:String(c?.updatedAt||c?.createdAt||"").trim(),order:Number.isFinite(Number(c?.order))?Math.floor(Number(c.order)):null,attachments:nm(c?.attachments),isArchived:!!c?.isArchived}})).filter(c=>c.initiative.id.length>0).filter(c=>me?!0:J.get(c.initiative.id)!==c.initiative.updatedAt),re=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),x=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>[String(c?.id||"").trim(),String(c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),K=e.lastPushedWorkstreamWatermarks,ue=!K||K.size===0,pe=(Array.isArray(e.workstreams)?e.workstreams:[]).map(c=>({op:"workstream-upsert",workstream:{id:String(c?.id||"").trim(),referenceNumber:Number.isFinite(Number(c?.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,referenceLabel:typeof c?.referenceLabel=="string"&&c.referenceLabel.trim().length>0?c.referenceLabel.trim():void 0,initiativeId:typeof c?.initiativeId=="string"&&c.initiativeId.trim().length>0?c.initiativeId.trim():null,title:String(c?.title||"").trim(),description:typeof c?.description=="string"?c.description:null,ownerId:typeof c?.ownerId=="string"&&c.ownerId.trim().length>0?c.ownerId.trim():null,createdAt:String(c?.createdAt||"").trim(),updatedAt:String(c?.updatedAt||c?.createdAt||"").trim(),order:Number.isFinite(Number(c?.order))?Math.floor(Number(c.order)):null,attachments:nm(c?.attachments),isArchived:!!c?.isArchived}})).filter(c=>c.workstream.id.length>0).filter(c=>ue?!0:K.get(c.workstream.id)!==c.workstream.updatedAt),X=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),M=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>[String(c?.id||"").trim(),fd.getWatermark(c)]).filter(([c])=>c.length>0)),O=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>[String(c?.id||"").trim(),fd.getChangeKey(c)]).filter(([c])=>c.length>0)),de=e.lastPushedAiProfileWatermarks,ge=e.lastPushedAiProfileChangeKeys,$=!de||de.size===0,_e=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(c=>({op:"ai-profile-upsert",profile:{id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),profileToken:String(c.profileToken||"").trim(),name:String(c.name||"").trim(),username:String(c.username||"").trim(),icon:String(c.icon||"Bot").trim()||"Bot",color:String(c.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:Xc(c.avatarUrl),avatarSourceUrl:Xc(c.avatarSourceUrl),avatarRevision:Number.isFinite(Number(c.avatarRevision))?Math.max(0,Math.floor(Number(c.avatarRevision))):0,avatarUpdatedAt:typeof c.avatarUpdatedAt=="string"&&c.avatarUpdatedAt.trim().length>0?c.avatarUpdatedAt.trim():null,description:typeof c.description=="string"&&c.description.trim()||null,role:typeof c.role=="string"&&c.role.trim()||null,provider:typeof c.provider=="string"&&c.provider.trim()||null,model:typeof c.model=="string"&&c.model.trim()||null,surfaceType:qg(c.surfaceType),seatScope:Kg(c.seatScope),providerMetadata:c.providerMetadata&&typeof c.providerMetadata=="object"&&!Array.isArray(c.providerMetadata)?c.providerMetadata:null,archivedAt:typeof c.archivedAt=="string"&&c.archivedAt.trim().length>0?c.archivedAt.trim():null,archivedBy:typeof c.archivedBy=="string"&&c.archivedBy.trim().length>0?c.archivedBy.trim():null,archivedReason:typeof c.archivedReason=="string"&&c.archivedReason.trim()||null,mergedIntoProfileId:typeof c.mergedIntoProfileId=="string"&&c.mergedIntoProfileId.trim().length>0?c.mergedIntoProfileId.trim():null,rosterStateUpdatedAt:typeof c.rosterStateUpdatedAt=="string"&&c.rosterStateUpdatedAt.trim().length>0?c.rosterStateUpdatedAt.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),lastActiveAt:typeof c.lastActiveAt=="string"&&c.lastActiveAt.trim().length>0?c.lastActiveAt.trim():null}})).filter(c=>c.profile.id.length>0&&c.profile.workspaceId.length>0).filter(c=>$?!0:lh(fd,c.profile,{watermarks:de,changeKeys:ge})),je=uh(e.currentDocumentPaths,(Array.isArray(e.documents)?e.documents:[]).map(c=>String(c?.path||"").trim())),se=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!je.has(c))),ce=new Map((Array.isArray(e.documents)?e.documents:[]).map(c=>[String(c?.path||"").trim(),String(c?.updatedAt||"").trim()]).filter(([c])=>c.length>0)),Re=e.lastPushedDocumentWatermarks,Pe=!Re||Re.size===0,Ce=(Array.isArray(e.documents)?e.documents:[]).map(c=>({op:"document-upsert",path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),content:typeof c.content=="string"?c.content:"",assetId:typeof c.assetId=="string"&&c.assetId.trim().length>0?c.assetId.trim():void 0,documentId:typeof c.documentId=="string"&&c.documentId.trim().length>0?c.documentId.trim():null,referenceNumber:Number.isFinite(Number(c.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,version:Number.isFinite(Number(c.version))?Math.max(1,Math.floor(Number(c.version))):null,taskId:typeof c.taskId=="string"&&c.taskId.trim().length>0?c.taskId.trim():null,linkTargetType:c.linkTargetType==="initiative"||c.linkTargetType==="workstream"||c.linkTargetType==="task"?c.linkTargetType:null,linkTargetId:typeof c.linkTargetId=="string"&&c.linkTargetId.trim().length>0?c.linkTargetId.trim():null,logicalName:typeof c.logicalName=="string"&&c.logicalName.trim().length>0?c.logicalName.trim():null,caption:typeof c.caption=="string"&&c.caption.trim().length>0?c.caption.trim():null,originalFilename:typeof c.originalFilename=="string"&&c.originalFilename.trim().length>0?c.originalFilename.trim():null,linkRole:c.linkRole==="reference"?"reference":"attachment"})).filter(c=>c.path.length>0).filter(c=>Pe?!0:Re.get(c.path)!==c.updatedAt),Ee=uh(e.currentAssetPaths,(Array.isArray(e.assets)?e.assets:[]).map(c=>String(c?.path||"").trim())),U=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!Ee.has(c))),T=new Map((Array.isArray(e.assets)?e.assets:[]).map(c=>[String(c?.path||"").trim(),String(c?.updatedAt||"").trim()]).filter(([c])=>c.length>0)),b=e.lastPushedAssetWatermarks,j=!b||b.size===0,D=(Array.isArray(e.assets)?e.assets:[]).map(c=>({op:"asset-upsert",path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),contentBase64:typeof c.contentBase64=="string"?c.contentBase64:"",assetId:typeof c.assetId=="string"&&c.assetId.trim().length>0?c.assetId.trim():void 0,kind:c.kind==="image"?"image":"file",mimeType:typeof c.mimeType=="string"&&c.mimeType.trim().length>0?c.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(c.referenceNumber))?Math.max(1,Math.floor(Number(c.referenceNumber))):null,taskId:typeof c.taskId=="string"&&c.taskId.trim().length>0?c.taskId.trim():null,linkTargetType:c.linkTargetType==="initiative"||c.linkTargetType==="workstream"||c.linkTargetType==="task"?c.linkTargetType:null,linkTargetId:typeof c.linkTargetId=="string"&&c.linkTargetId.trim().length>0?c.linkTargetId.trim():null,logicalName:typeof c.logicalName=="string"&&c.logicalName.trim().length>0?c.logicalName.trim():null,caption:typeof c.caption=="string"&&c.caption.trim().length>0?c.caption.trim():null,originalFilename:typeof c.originalFilename=="string"&&c.originalFilename.trim().length>0?c.originalFilename.trim():null,linkRole:c.linkRole==="reference"?"reference":c.linkRole==="image"?"image":"attachment"})).filter(c=>c.path.length>0&&c.contentBase64.length>0).filter(c=>j?!0:b.get(c.path)!==c.updatedAt),te=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],P=new Set(te.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),H=new Set(te.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),be=e.lastPushedDocumentReviewSessionIds||new Set,z=new Map(te.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),ie=e.lastPushedDocumentReviewSessionWatermarks,ee=!ie||ie.size===0,Q=te.map(c=>({op:"document-review-session-upsert",session:{id:String(c.id||"").trim(),assetId:String(c.assetId||"").trim(),documentId:typeof c.documentId=="string"&&c.documentId.trim().length>0?c.documentId.trim():null,documentVersion:Number.isFinite(Number(c.documentVersion))?Math.max(1,Math.floor(Number(c.documentVersion))):null,title:typeof c.title=="string"&&c.title.trim().length>0?c.title.trim():null,status:c.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof c.createdByActorId=="string"&&c.createdByActorId.trim().length>0?c.createdByActorId.trim():null,updatedByActorId:typeof c.updatedByActorId=="string"&&c.updatedByActorId.trim().length>0?c.updatedByActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.session.id.length>0&&c.session.assetId.length>0&&!c.session.deletedAt).filter(c=>ee?!0:ie.get(c.session.id)!==c.session.updatedAt),q=te.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({sessionId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.sessionId.length>0).filter(c=>ee?!0:ie.get(c.sessionId)!==c.deletedAt),Se=Array.from(be).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!P.has(c)),we=[...Se.map(c=>({sessionId:c,deletedAt:t})),...q],Te=new Set([...Se,...q.map(c=>c.sessionId)]),Me=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],nt=new Set(Me.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),gt=new Set(Me.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),lt=e.lastPushedDocumentReviewCommentIds||new Set,St=new Map(Me.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),Ke=e.lastPushedDocumentReviewCommentWatermarks,Ct=!Ke||Ke.size===0,dt=Me.map(c=>({op:"document-review-comment-upsert",comment:{id:String(c.id||"").trim(),sessionId:String(c.sessionId||"").trim(),body:String(c.body||"").trim(),anchor:c.anchor??null,order:Number.isFinite(Number(c.order))?Math.max(0,Math.floor(Number(c.order))):0,authorActorId:typeof c.authorActorId=="string"&&c.authorActorId.trim().length>0?c.authorActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.comment.id.length>0&&c.comment.sessionId.length>0&&!c.comment.deletedAt).filter(c=>Ct?!0:Ke.get(c.comment.id)!==c.comment.updatedAt),Xe=Me.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({commentId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.commentId.length>0).filter(c=>Ct?!0:Ke.get(c.commentId)!==c.deletedAt),ct=Array.from(lt).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!nt.has(c)),ne=[...ct.map(c=>({commentId:c,deletedAt:t})),...Xe],st=new Set([...ct,...Xe.map(c=>c.commentId)]),Ye=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],Pt=new Set(Ye.map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),kt=new Set(Ye.filter(c=>String(c?.deletedAt||"").trim().length===0).map(c=>String(c?.id||"").trim()).filter(c=>c.length>0)),It=e.lastPushedAnnotatedAttachmentSessionIds||new Set,Ft=new Map(Ye.map(c=>[String(c?.id||"").trim(),String(c?.deletedAt||c?.updatedAt||c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),Mt=e.lastPushedAnnotatedAttachmentSessionWatermarks,Be=!Mt||Mt.size===0,et=Ye.map(c=>({op:"annotated-attachment-session-upsert",session:{id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),taskId:String(c.taskId||"").trim(),baseImageAssetId:String(c.baseImageAssetId||"").trim(),title:typeof c.title=="string"&&c.title.trim().length>0?c.title.trim():null,globalInstruction:typeof c.globalInstruction=="string"&&c.globalInstruction.trim().length>0?c.globalInstruction.trim():null,annotations:Array.isArray(c.annotations)?c.annotations:[],createdByActorId:typeof c.createdByActorId=="string"&&c.createdByActorId.trim().length>0?c.createdByActorId.trim():null,updatedByActorId:typeof c.updatedByActorId=="string"&&c.updatedByActorId.trim().length>0?c.updatedByActorId.trim():null,createdAt:String(c.createdAt||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:typeof c.deletedAt=="string"&&c.deletedAt.trim().length>0?c.deletedAt.trim():null}})).filter(c=>c.session.id.length>0&&c.session.workspaceId.length>0&&c.session.baseImageAssetId.length>0&&!c.session.deletedAt).filter(c=>Be?!0:Mt.get(c.session.id)!==c.session.updatedAt),Ue=Ye.filter(c=>String(c?.deletedAt||"").trim().length>0).map(c=>({sessionId:String(c?.id||"").trim(),deletedAt:String(c?.deletedAt||c?.updatedAt||c?.createdAt||t).trim()||t})).filter(c=>c.sessionId.length>0).filter(c=>Be?!0:Mt.get(c.sessionId)!==c.deletedAt),Qe=Array.from(It).map(c=>String(c||"").trim()).filter(c=>c.length>0&&!Pt.has(c)),yt=[...Qe.map(c=>({sessionId:c,deletedAt:t})),...Ue],ot=new Set([...Qe,...Ue.map(c=>c.sessionId)]),ae=XS(Array.isArray(e.taskEvents)?e.taskEvents:[]),ze=new Map(ae.map(c=>[String(c?.id||"").trim(),String(c?.createdAt||"").trim()]).filter(([c])=>c.length>0)),bt=e.lastPushedTaskEventWatermarks,Ot=!bt||bt.size===0,Bt=ae.map(c=>{const Y=c.entityType==="initiative"||c.entityType==="workstream"?c.entityType:"task",ye=String(c.entityId||c.taskId||"").trim(),Ie={id:String(c.id||"").trim(),workspaceId:String(c.workspaceId||"").trim(),entityType:Y,entityId:ye,taskId:Y==="task"?String(c.taskId||ye).trim():void 0,action:String(c.action||"").trim(),actor:String(c.actor||"system").trim()||"system",actorType:c.actorType==="ai"||c.actorType==="human"||c.actorType==="system"?c.actorType:"system",details:c.details&&typeof c.details=="object"&&!Array.isArray(c.details)?c.details:{},createdAt:String(c.createdAt||"").trim()};return Y==="task"?{op:"task-event-upsert",event:{...Ie,entityType:"task",taskId:String(Ie.taskId||ye).trim()}}:{op:"entity-event-upsert",event:{...Ie,entityType:Y,taskId:void 0}}}).filter(c=>c.event.id.length>0&&c.event.entityId.length>0&&c.event.workspaceId.length>0&&c.event.action.length>0&&Number.isFinite(Date.parse(c.event.createdAt))).filter(c=>Ot?!0:bt.get(c.event.id)!==c.event.createdAt),Oe=[...ve,...pe,...e.taxonomyState&&typeof e.taxonomyState=="object"?[{op:"taxonomy-upsert",taxonomyState:e.taxonomyState,updatedAt:t}]:Array.isArray(e.taxonomies)?[{op:"taxonomy-upsert",taxonomies:e.taxonomies,updatedAt:t}]:[],..._e,...Ce,...Array.from(se).map(c=>({op:"document-delete",path:c,deletedAt:t})),...D,...Array.from(U).map(c=>({op:"asset-delete",path:c,deletedAt:t})),...Q,...we.map(c=>({op:"document-review-session-delete",sessionId:c.sessionId,deletedAt:c.deletedAt})),...dt,...ne.map(c=>({op:"document-review-comment-delete",commentId:c.commentId,deletedAt:c.deletedAt})),...et,...yt.map(c=>({op:"annotated-attachment-session-delete",sessionId:c.sessionId,deletedAt:c.deletedAt})),...Bt,...g,...v,...Array.from(B).map(c=>({op:"delete",taskId:c,deletedAt:s.get(c)||t}))],Lt=e.baselineResetReason??null,vt=c=>{const Y=c.upsertCount+(c.deleteCount||0);if(c.currentCount===0&&Y===0)return{mode:"none",reason:null,currentCount:0,baselineCount:c.baselineCount,changeCount:Y};if(c.alwaysFull)return{mode:Y>0?"send-all":"none",reason:Y>0?"full-state-domain":null,currentCount:c.currentCount,baselineCount:c.baselineCount,changeCount:Y};const ye=c.baselineCount===0&&c.currentCount>0&&c.upsertCount>=c.currentCount;return{mode:ye?"send-all":"delta",reason:ye?Lt||"missing-baseline":null,currentCount:c.currentCount,baselineCount:c.baselineCount,changeCount:Y}},E=Oe.reduce((c,Y)=>{const ye=String(Y.op||"").trim();return c[ye]=(c[ye]||0)+1,c},{});return{changes:Oe,currentTaskIds:new Set(Array.from(A).filter(c=>!n.has(c))),currentTaskWatermarks:new Map(Array.from(y.entries()).filter(([c])=>!n.has(c))),currentTaskChangeKeys:new Map(Array.from(k.entries()).filter(([c])=>!n.has(c))),deleteTaskIds:B,currentInitiativeIds:V,currentInitiativeWatermarks:L,currentWorkstreamIds:re,currentWorkstreamWatermarks:x,currentAiProfileIds:X,currentAiProfileWatermarks:M,currentAiProfileChangeKeys:O,currentDocumentPaths:je,deleteDocumentPaths:se,currentDocumentWatermarks:ce,currentAssetPaths:Ee,deleteAssetPaths:U,currentAssetWatermarks:T,currentDocumentReviewSessionIds:H,deleteDocumentReviewSessionIds:Te,currentDocumentReviewSessionWatermarks:z,currentDocumentReviewCommentIds:gt,deleteDocumentReviewCommentIds:st,currentDocumentReviewCommentWatermarks:St,currentAnnotatedAttachmentSessionIds:kt,deleteAnnotatedAttachmentSessionIds:ot,currentAnnotatedAttachmentSessionWatermarks:Ft,currentTaskEventWatermarks:ze,pushedWatermarks:S,pushedTaskChangeKeys:h,deltaDiagnostics:{totalChanges:Oe.length,byOp:E,baselineResetReason:Lt,domains:{tasks:vt({currentCount:A.size,baselineCount:o?.size||0,upsertCount:g.length+v.length,deleteCount:B.size}),initiatives:vt({currentCount:V.size,baselineCount:J?.size||0,upsertCount:ve.length}),workstreams:vt({currentCount:re.size,baselineCount:K?.size||0,upsertCount:pe.length}),aiProfiles:vt({currentCount:X.size,baselineCount:de?.size||0,upsertCount:_e.length}),documents:vt({currentCount:je.size,baselineCount:Re?.size||0,upsertCount:Ce.length,deleteCount:se.size}),assets:vt({currentCount:Ee.size,baselineCount:b?.size||0,upsertCount:D.length,deleteCount:U.size}),documentReviewSessions:vt({currentCount:H.size,baselineCount:ie?.size||0,upsertCount:Q.length,deleteCount:Te.size}),documentReviewComments:vt({currentCount:gt.size,baselineCount:Ke?.size||0,upsertCount:dt.length,deleteCount:st.size}),annotatedAttachmentSessions:vt({currentCount:kt.size,baselineCount:Mt?.size||0,upsertCount:et.length,deleteCount:ot.size}),taskEvents:vt({currentCount:ze.size,baselineCount:bt?.size||0,upsertCount:Bt.length}),taxonomy:vt({currentCount:e.taxonomyState&&typeof e.taxonomyState=="object"||Array.isArray(e.taxonomies)?1:0,baselineCount:0,upsertCount:E["taxonomy-upsert"]||0,alwaysFull:!0})}}}}function tw(e){const t=(e.tasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),n=(e.archivedTasks||[]).map(i=>`${i.id}:${i.updatedAt||i.createdAt||""}:${i.status}`).sort(),s=e.pendingDeletedTaskIds?Array.from(e.pendingDeletedTaskIds).sort():[],o=(e.initiatives||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",attachments:nm(i.attachments)||[],isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)),l=(e.workstreams||[]).map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),initiativeId:typeof i.initiativeId=="string"?i.initiativeId.trim():"",title:String(i.title||"").trim(),ownerId:typeof i.ownerId=="string"?i.ownerId.trim():"",attachments:nm(i.attachments)||[],isArchived:!!i.isArchived})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id));return JSON.stringify({workspaceId:e.workspaceId,initiatives:o,workstreams:l,taxonomyState:e.taxonomyState&&typeof e.taxonomyState=="object"?e.taxonomyState:null,taxonomies:Array.isArray(e.taxonomies)?e.taxonomies:[],aiProfiles:Array.isArray(e.aiProfiles)?e.aiProfiles.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),name:String(i.name||"").trim(),username:String(i.username||"").trim(),archivedAt:String(i.archivedAt||"").trim(),archivedReason:String(i.archivedReason||"").trim(),mergedIntoProfileId:String(i.mergedIntoProfileId||"").trim(),rosterStateUpdatedAt:String(i.rosterStateUpdatedAt||"").trim()})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],taskEvents:Array.isArray(e.taskEvents)?e.taskEvents.map(i=>({id:String(i.id||"").trim(),taskId:String(i.taskId||"").trim(),action:String(i.action||"").trim(),actor:String(i.actor||"").trim(),actorType:i.actorType==="ai"||i.actorType==="human"||i.actorType==="system"?i.actorType:"system",createdAt:String(i.createdAt||"").trim()})).filter(i=>i.id.length>0&&i.taskId.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],documents:Array.isArray(e.documents)?e.documents.map(i=>({path:String(i.path||"").trim(),updatedAt:String(i.updatedAt||"").trim(),length:typeof i.content=="string"?i.content.length:0})).filter(i=>i.path.length>0).sort((i,d)=>i.path.localeCompare(d.path)):[],assets:Array.isArray(e.assets)?e.assets.map(i=>({path:String(i.path||"").trim(),updatedAt:String(i.updatedAt||"").trim(),length:typeof i.contentBase64=="string"?i.contentBase64.length:0,kind:i.kind==="image"?"image":"file"})).filter(i=>i.path.length>0).sort((i,d)=>i.path.localeCompare(d.path)):[],documentReviewSessions:Array.isArray(e.documentReviewSessions)?e.documentReviewSessions.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),assetId:String(i.assetId||"").trim(),status:i.status==="resolved"?"resolved":"open",deletedAt:String(i.deletedAt||"").trim(),commentCount:Array.isArray(i.comments)?i.comments.length:0})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],documentReviewComments:Array.isArray(e.documentReviewComments)?e.documentReviewComments.map(i=>({id:String(i.id||"").trim(),sessionId:String(i.sessionId||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),deletedAt:String(i.deletedAt||"").trim(),bodyLength:String(i.body||"").length})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],annotatedAttachmentSessions:Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions.map(i=>({id:String(i.id||"").trim(),updatedAt:String(i.updatedAt||i.createdAt||"").trim(),taskId:String(i.taskId||"").trim(),baseImageAssetId:String(i.baseImageAssetId||"").trim(),deletedAt:String(i.deletedAt||"").trim(),annotationCount:Array.isArray(i.annotations)?i.annotations.length:0})).filter(i=>i.id.length>0).sort((i,d)=>i.id.localeCompare(d.id)):[],active:t,archived:n,pendingDeletes:s})}function zu(){return{version:2,enabled:!1,phase:"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null,pushBaseline:null}}function ei(e){const t=String(e||"").trim();return t.length>0?t:null}function ph(e){return String(e||"").trim().toLowerCase()==="attach-cloud-import"?"attach-cloud-import":null}function aw(e){if(!Array.isArray(e)||e.length<2)return null;const t=String(e[0]||"").trim(),n=String(e[1]||"").trim();return!t||!n?null:[t,n]}function nw(e){return Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(t=>t.length>0):[]}function fh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=s=>Array.isArray(t[s])?t[s].map(o=>aw(o)).filter(o=>Array.isArray(o)):[];return{taskIds:nw(t.taskIds),taskWatermarks:n("taskWatermarks"),taskChangeKeys:n("taskChangeKeys"),initiativeWatermarks:n("initiativeWatermarks"),workstreamWatermarks:n("workstreamWatermarks"),aiProfileWatermarks:n("aiProfileWatermarks"),aiProfileChangeKeys:n("aiProfileChangeKeys"),documentWatermarks:n("documentWatermarks"),assetWatermarks:n("assetWatermarks"),documentReviewSessionWatermarks:n("documentReviewSessionWatermarks"),documentReviewCommentWatermarks:n("documentReviewCommentWatermarks"),annotatedAttachmentSessionWatermarks:n("annotatedAttachmentSessionWatermarks"),taskEventWatermarks:n("taskEventWatermarks"),taxonomyStateFingerprint:String(t.taxonomyStateFingerprint||"").trim()}}function rw(e,t){if(!!!(e.enabled??e.cloudSyncEnabled))return"idle";const s=String(e.phase||"").trim().toLowerCase();if(s==="idle"||s==="provision-local"||s==="attach-cloud"||s==="active"||s==="error")return s;const o=String(e.bootstrapMode||"").trim().toLowerCase();if(o==="provision-local"||o==="attach-cloud")return o;const l=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":l==="cloud"?t.lastPullAt?"active":"attach-cloud":l==="local"?t.lastPullAt||t.lastPushAt?"active":"provision-local":(t.lastPullAt||t.lastPushAt,"active")}function sw(e){const t=zu();if(!e||typeof e!="object")return{state:t,changed:!1};const n=e,s=n.lastErrorMessage,o=typeof s=="string"&&s.trim().length>0?s:null,l={version:2,enabled:!!(n.enabled??n.cloudSyncEnabled),phase:"idle",setupIntent:ph(n.setupIntent),pullCursor:ei(n.pullCursor),lastPullAt:ei(n.lastPullAt),lastPushAt:ei(n.lastPushAt),lastSyncedAt:ei(n.lastSyncedAt),lastErrorMessage:o,pushBaseline:fh(n.pushBaseline)};l.phase=rw(n,l),l.enabled||(l.phase="idle",l.pullCursor=null);const d=Number(n.version||0)!==2||!!(n.enabled??n.cloudSyncEnabled)!==l.enabled||String(n.phase||"").trim()!==l.phase||ph(n.setupIntent)!==l.setupIntent||ei(n.pullCursor)!==l.pullCursor||ei(n.lastPullAt)!==l.lastPullAt||ei(n.lastPushAt)!==l.lastPushAt||ei(n.lastSyncedAt)!==l.lastSyncedAt||o!==l.lastErrorMessage||JSON.stringify(fh(n.pushBaseline))!==JSON.stringify(l.pushBaseline);return{state:l,changed:d}}const ow="taskforce.sync.lease.v1",iw="taskforce.sync.lease.v1",cw=2500,lw=9e3;function nd(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function Ru(e){const t=String(e||"").trim();return t.length>0?t:null}function hp(e){return`${ow}.${e}`}function dw(e){if(!e)return null;try{const t=JSON.parse(e),n=String(t?.ownerId||"").trim(),s=String(t?.workspaceId||"").trim(),o=String(t?.operation||"").trim(),l=String(t?.heartbeatAt||"").trim(),i=String(t?.expiresAt||"").trim();return!n||!s||!l||!i||o!=="pull"&&o!=="push"&&o!=="repair"?null:{ownerId:n,workspaceId:s,operation:o,heartbeatAt:l,expiresAt:i}}catch{return null}}function uw(e,t,n,s){return{ownerId:e,workspaceId:t,operation:n,heartbeatAt:new Date(s).toISOString(),expiresAt:new Date(s+lw).toISOString()}}function mw(e,t=Date.now()){if(!e)return!0;const n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t}function gp(e,t){const n={...e,...t,version:2,phase:t.phase||e.phase,setupIntent:t.setupIntent===void 0?e.setupIntent??null:t.setupIntent??null,pullCursor:t.pullCursor===void 0?e.pullCursor:Ru(t.pullCursor),lastPullAt:t.lastPullAt===void 0?e.lastPullAt:Ru(t.lastPullAt),lastPushAt:t.lastPushAt===void 0?e.lastPushAt:Ru(t.lastPushAt),lastSyncedAt:t.lastSyncedAt===void 0?e.lastSyncedAt:Ru(t.lastSyncedAt),lastErrorMessage:t.lastErrorMessage===void 0?e.lastErrorMessage:t.lastErrorMessage??null,pushBaseline:t.pushBaseline===void 0?e.pushBaseline??null:t.pushBaseline??null};return n.enabled||(n.phase="idle",n.setupIntent=null,n.pullCursor=null),n}function pw(e){return{...e,pushBaseline:null}}function fw(e){const{currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:n,setWorkspaceSyncPhase:s,setWorkspaceSyncSetupIntent:o,setWorkspaceLastPullAt:l,setWorkspaceLastPushAt:i,setWorkspaceLastErrorMessage:d}=e,[m,y]=r.useState(null),k=r.useRef(null),S=r.useRef(null),h=r.useRef(0),g=r.useRef(!1),v=r.useRef(!1),A=r.useRef(""),_=r.useRef(""),I=r.useRef(new Set),B=r.useRef(new Set),V=r.useRef(new Map),L=r.useRef(null),J=r.useRef(zu()),me=r.useRef(""),ve=r.useRef(null),re=r.useRef(null),x=r.useRef(null),K=r.useRef(null);if(!me.current){const T=Date.now().toString(36),b=Math.random().toString(36).slice(2,10);me.current=`sync-lease-${T}-${b}`}const ue=r.useCallback(()=>{h.current=0,S.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),y(null)},[]),pe=r.useCallback((T,b)=>{if(typeof window>"u")return;const j=Math.max(1,h.current+1);h.current=j;const D=PS(j),te=Number(b?.minDelayMs),P=Number.isFinite(te)&&te>0?Math.max(D,Math.floor(te)):D,H=Date.now()+P;S.current=H,y(new Date(H).toISOString()),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,S.current=null,y(null),T()},P)},[]),X=r.useCallback(()=>{const T=S.current;return typeof T=="number"&&Number.isFinite(T)&&T>Date.now()},[]),M=r.useCallback(T=>{if(typeof window>"u")return null;const b=String(T||"").trim();return nd(b)?dw(window.localStorage.getItem(hp(b))):null},[]),O=r.useCallback(T=>{const b=String(T||"").trim();if(b)try{K.current?.postMessage({workspaceId:b})}catch{}},[]),de=r.useCallback((T,b)=>{if(typeof window>"u")return null;const j=String(T||"").trim();if(!nd(j))return null;const D=uw(me.current,j,b,Date.now());try{window.localStorage.setItem(hp(j),JSON.stringify(D))}catch{return null}return O(j),D},[O]),ge=r.useCallback(()=>{x.current!==null&&typeof window<"u"&&(window.clearInterval(x.current),x.current=null)},[]),$=r.useCallback((T,b)=>{if(typeof window>"u")return;const j=String(T||ve.current||"").trim();if(!j)return;const D=M(j),te=D?.ownerId===me.current;if(!(!b?.force&&D&&!te)){ge();try{window.localStorage.removeItem(hp(j))}catch{}ve.current=null,re.current=null,O(j)}},[O,M,ge]),_e=r.useCallback((T,b)=>{typeof window>"u"||(ge(),x.current=window.setInterval(()=>{const j=String(ve.current||"").trim(),D=re.current;if(!j||!D){ge();return}if(M(j)?.ownerId!==me.current){ge(),ve.current=null,re.current=null;return}de(j,D)},cw),ve.current=T,re.current=b)},[M,ge,de]),je=r.useCallback(async(T,b)=>{if(typeof window>"u")return!0;const j=String(T||"").trim();if(!nd(j))return!1;const D=M(j);if(D?.ownerId===me.current)return de(j,b)?(_e(j,b),!0):!1;if(D&&!mw(D)||!de(j,b))return!1;const H=M(j);return!H||H.ownerId!==me.current?!1:(_e(j,b),!0)},[M,_e,de]),se=r.useCallback(T=>{$(T,{force:!0})},[$]),ce=r.useCallback(T=>{const b=J.current,j=gp(b,{enabled:!!T.enabled,phase:T.phase||b.phase,setupIntent:T.setupIntent,pullCursor:T.pullCursor,lastPullAt:T.lastPullAt,lastPushAt:T.lastPushAt,lastSyncedAt:T.lastSyncedAt,lastErrorMessage:T.lastErrorMessage});J.current=j,L.current=j.pullCursor,n(j.enabled),s(j.phase),o(j.setupIntent??null),l(j.lastPullAt),i(j.lastPushAt),d(j.lastErrorMessage??null)},[n,s,o,l,i,d]),Re=r.useCallback(T=>{const b=gp(J.current,T);return ce(b),b},[ce]),Pe=r.useCallback(()=>J.current,[]),Ce=r.useCallback(async T=>{const b=gp(J.current,T);J.current=b,L.current=b.pullCursor;const j=await df({workspaceId:t,stateKey:"workspace-sync",patch:pw(b),throwOnError:!0,respectFailureCooldown:!1}),D=j.response,te=j.payload;if(j.skipped)return ce(b),b;if(!D)throw new Error("Failed to persist workspace sync state (missing response)");if(!D.ok||te?.success===!1)throw new Error(te?.error||`Failed to persist workspace sync state (${D.status})`);return ce(b),b},[ce,t]),Ee=r.useCallback(async()=>{if(!nd(t)){const T=zu();J.current=T,ce(T);return}try{const T=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!T.ok)return;const b=await T.json().catch(()=>({})),j=sw(b?.state&&typeof b.state=="object"?b.state:null);J.current=j.state,ce(j.state),j.changed&&Ce(j.state)}catch{}},[ce,t,Ce]),U=r.useCallback(async(T,b)=>{if(!nd(t))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!T.enabled)return await Ce({enabled:!1,phase:"idle",setupIntent:null,pullCursor:null}),{success:!0};if(!b.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!b.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const j=await b.ensureCloudWorkspaceReadyForSync();return j.success?(await Ce({enabled:!0,phase:j.provisioned?"provision-local":"attach-cloud",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:j.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[t,Ce]);return r.useEffect(()=>{A.current="",_.current="",I.current=new Set,B.current=new Set,V.current=new Map,L.current=null,J.current=zu(),g.current=!1,v.current=!1,$(),ue()},[ue,t,$]),r.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const T=new BroadcastChannel(iw);return K.current=T,()=>{T.close(),K.current===T&&(K.current=null)}},[]),r.useEffect(()=>()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),$()},[$]),{workspaceRetryAt:m,isWorkspaceRetryPending:X,workspacePushInFlightRef:g,workspacePullInFlightRef:v,workspaceLastPushedSignatureRef:A,workspacePendingSignatureRef:_,workspaceLastPushedTaskIdsRef:I,workspaceDeletedTaskIdsRef:B,workspaceDeletedTaskWatermarksRef:V,workspacePullCursorRef:L,clearWorkspaceRetry:ue,scheduleWorkspaceRetry:pe,persistWorkspaceSyncPatch:Ce,applyWorkspaceSyncPatchLocally:Re,readWorkspaceSyncStateSnapshot:Pe,loadWorkspaceSyncState:Ee,applyWorkspaceSyncStateSnapshot:ce,saveWorkspaceCloudSyncSettings:U,acquireWorkspaceSyncLease:je,releaseWorkspaceSyncLease:$,forceClearWorkspaceSyncLease:se,readWorkspaceSyncLease:M}}class hw{constructor(t=2048){this.maxSeenEventIds=t}seenEventIds=new Set;seenEventIdQueue=[];activeEpoch="";lastSeq=null;telemetry={accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0};process(t){const n=typeof t.eventId=="string"?t.eventId.trim():"";if(n&&this.seenEventIds.has(n))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const s=typeof t.serverEpoch=="string"?t.serverEpoch.trim():"",o=Number(t.seq);if(!(s.length>0&&Number.isFinite(o)&&o>=0))return n?(this.rememberEventId(n),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}):(this.telemetry.invalidDiscarded+=1,{accepted:!1,reason:"invalid",shouldRecover:!1});const i=Math.floor(o);if(this.activeEpoch&&this.activeEpoch!==s)return this.activeEpoch=s,this.lastSeq=i,n&&this.rememberEventId(n),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=s,this.lastSeq=i,n&&this.rememberEventId(n),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const d=this.lastSeq;if(typeof d=="number"){if(i<=d){this.telemetry.outOfOrderDiscarded+=i===d?0:1,this.telemetry.duplicateDiscarded+=i===d?1:0;const m=i<d;return m&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:i===d?"duplicate":"out-of-order",shouldRecover:m}}if(i>d+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=i,n&&this.rememberEventId(n),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}}getTelemetry(){return{...this.telemetry}}rememberEventId(t){for(this.seenEventIds.add(t),this.seenEventIdQueue.push(t);this.seenEventIdQueue.length>this.maxSeenEventIds;){const n=this.seenEventIdQueue.shift();n&&this.seenEventIds.delete(n)}}}function Yg(e){const{enabled:t,workspaceId:n,websocketUrl:s,reconnectBaseMs:o=400,reconnectMaxMs:l=1e4,degradeAfterAttempts:i=5,replayLimit:d=200,onSignal:m,onTelemetry:y,userId:k}=e,[S,h]=r.useState("degraded-fallback"),g=r.useRef(null),v=r.useRef(null),A=r.useRef(0),_=r.useRef(""),I=r.useRef(!1),B=r.useRef(null),V=r.useRef(null),L=r.useRef(new hw),J=r.useRef(m),me=r.useRef(y);r.useEffect(()=>{J.current=m},[m]),r.useEffect(()=>{me.current=y},[y]);const[ve,re]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),x=r.useMemo(()=>String(n||"").trim(),[n]),K=r.useMemo(()=>String(s||"").trim(),[s]);return r.useEffect(()=>{let ue=!1;const pe=()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},X=()=>{const ce=g.current;if(g.current=null,ce)try{ce.close()}catch{}},M=ce=>ce==="taskforce:replay-gap"||ce==="taskforce:replay-reset"?4:ce==="taskforce:mutation"||ce==="taskforce:replay"?3:1,O=ce=>{const Re=V.current;if(Re){const Pe=M(Re.type),Ce=M(ce.type);if(Ce<Pe||Ce===Pe&&Re.eventId&&!ce.eventId)return}V.current=ce,B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{B.current=null;const Pe=J.current;if(!V.current||typeof Pe!="function")return;const Ce=V.current;V.current=null,Pe(Ce)},80)},de=ce=>{try{const Re=JSON.parse(String(ce.data||""));return!Re||typeof Re!="object"?null:Re}catch{return null}},ge=ce=>{const Re=typeof ce.serverEpoch=="string"?ce.serverEpoch.trim():"",Pe=Number(ce.seq);!Re||!Number.isFinite(Pe)||Pe<0||(_.current=`${Re}:${Math.floor(Pe)}`,I.current=!1)},$=()=>{const ce=L.current.getTelemetry();re(ce);const Re=me.current;typeof Re=="function"&&Re(ce)},_e=ce=>{const Re={type:"taskforce:replay",workspaceId:x,limit:d},Pe=_.current;Pe&&(Re.cursor=Pe),ce.send(JSON.stringify(Re))},je=()=>{if(!t||ue)return;pe(),A.current+=1;const ce=A.current,Re=Math.max(50,Math.floor(o)),Pe=Math.max(Re,Math.floor(l)),Ce=Math.min(Pe,Re*Math.pow(2,Math.max(0,ce-1)));h(ce>=i?"degraded-fallback":"reconnecting"),v.current=window.setTimeout(()=>{ue||(v.current=null,se())},Ce)},se=()=>{if(!t||ue||!x||!K)return;X();let ce;try{ce=new WebSocket(K)}catch{je();return}g.current=ce,ce.addEventListener("open",()=>{A.current=0,h("connected"),ce.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:x,userId:k||void 0})),_e(ce)}),ce.addEventListener("message",Re=>{const Pe=de(Re);if(!Pe||typeof Pe.type!="string")return;const Ce=typeof Pe.workspaceId=="string"?Pe.workspaceId.trim():x;if(!(!Ce||Ce!==x)){if(Pe.type==="taskforce:update"){O({type:"taskforce:update",workspaceId:x,eventId:typeof Pe.eventId=="string"?Pe.eventId.trim():void 0});return}if(Pe.type==="taskforce:mutation"){const Ee=L.current.process({eventId:Pe.eventId,serverEpoch:Pe.serverEpoch,seq:Pe.seq});if(!Ee.accepted){$(),Ee.shouldRecover&&(_.current="",I.current||(I.current=!0,O({type:"taskforce:replay-gap",workspaceId:x})));return}ge(Pe),$(),O({type:Pe.type,workspaceId:x,eventId:typeof Pe.eventId=="string"?Pe.eventId.trim():void 0});return}if(Pe.type==="taskforce:replay"){const Ee=Array.isArray(Pe.events)?Pe.events:[];let U=0;for(const T of Ee)L.current.process({eventId:T.eventId,serverEpoch:T.serverEpoch,seq:T.seq}).accepted&&(U+=1,ge(T));I.current=!1,$(),(U>0||Pe.truncated===!0)&&O({type:"taskforce:replay",workspaceId:x}),Pe.truncated===!0&&_e(ce);return}if(Pe.type==="taskforce:replay-gap"||Pe.type==="taskforce:replay-reset"){if(_.current="",I.current)return;I.current=!0,O({type:Pe.type,workspaceId:x})}}}),ce.addEventListener("close",Re=>{if(g.current===ce&&(g.current=null),!ue&&t){const Pe=Number(Re?.code||0),Ce=String(Re?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${x} user=${String(k||"anonymous").trim()||"anonymous"} code=${Pe}${Ce?` reason=${Ce}`:""}`)}je()}),ce.addEventListener("error",()=>{try{ce.close()}catch{}})};return!t||!x||!K?(h("degraded-fallback"),pe(),X(),()=>{pe(),X()}):(h("reconnecting"),se(),()=>{ue=!0,pe(),B.current!==null&&(window.clearTimeout(B.current),B.current=null),V.current=null,X()})},[t,x,K,o,l,i,d,k]),{connectionState:S,telemetry:ve}}const Fp="taskforce:context-assets-mutated";function UO(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Fp,{detail:e}))}const Op="taskforce:ai-profiles-mutated";function zO(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Op,{detail:e}))}const gw=4,ju=100;function id(e,t,n){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(e instanceof Date)return e.toISOString();if(t>=gw)return"[MaxDepth]";if(typeof e=="function"||typeof e=="symbol"||typeof e>"u")return String(e);if(Array.isArray(e))return e.slice(0,ju).map(s=>id(s,t+1,n));if(e instanceof Set)return Array.from(e.values()).slice(0,ju).map(s=>id(s,t+1,n));if(e instanceof Map){const s={};for(const[o,l]of Array.from(e.entries()).slice(0,ju))s[String(o)]=id(l,t+1,n);return s}if(typeof e=="object"){if(n.has(e))return"[Circular]";n.add(e);const s={};for(const[o,l]of Object.entries(e).slice(0,ju))s[o]=id(l,t+1,n);return n.delete(e),s}return String(e)}function Sm(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return id(e,0,new WeakSet)}function yw(e){const t=Sm(e);if(!t)return"null";try{return JSON.stringify(t)}catch{return"[UnserializableSyncEventDetails]"}}const Jg="taskforce.userGlobalSyncMeta.v1",kw="taskforce.syncDebug.v1",vw=12e4,Qg="taskforce.syncWatermarks.v3",Sw=300*1e3,hh="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function ai(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function ww(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(kw)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function Un(e,t){if(!ww())return;console.info("[Taskforce Sync]",e,t&&typeof t=="object"?t:{})}function bw(e){const t=e?.providerMetadata??e?.provider_metadata??null;return{id:String(e?.id||"").trim(),workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),profileToken:String(e?.profileToken||e?.profile_token||"").trim(),name:String(e?.name||"").trim(),username:String(e?.username||"").trim(),icon:String(e?.icon||"Bot").trim()||"Bot",color:String(e?.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:Xc(e?.avatarUrl??e?.avatar_url),avatarSourceUrl:Xc(e?.avatarSourceUrl??e?.avatar_source_url),avatarRevision:Number.isFinite(Number(e?.avatarRevision??e?.avatar_revision))?Math.max(0,Math.floor(Number(e?.avatarRevision??e?.avatar_revision))):0,avatarUpdatedAt:Er(e?.avatarUpdatedAt??e?.avatar_updated_at),description:mn(e?.description),role:mn(e?.role),provider:mn(e?.provider),model:mn(e?.model),surfaceType:qg(e?.surfaceType??e?.surface_type),seatScope:Kg(e?.seatScope??e?.seat_scope),providerMetadata:t&&typeof t=="object"&&!Array.isArray(t)?t:null,archivedAt:Er(e?.archivedAt??e?.archived_at),archivedBy:am(e?.archivedBy??e?.archived_by),archivedReason:mn(e?.archivedReason??e?.archived_reason),mergedIntoProfileId:am(e?.mergedIntoProfileId??e?.merged_into_profile_id),rosterStateUpdatedAt:Er(e?.rosterStateUpdatedAt??e?.roster_state_updated_at),createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),lastActiveAt:Er(e?.lastActiveAt??e?.last_active_at)}}function gh(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Jg);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function _w(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Jg,JSON.stringify(e))}catch{}}function Cw(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function Aw(e){return e.flatMap(t=>{const n=String(t?.id||"").trim();return!n||!Array.isArray(t?.comments)?[]:t.comments.map(s=>({id:String(s?.id||"").trim(),sessionId:n,body:String(s?.body||""),anchor:s?.anchor??null,order:Number.isFinite(Number(s?.order))?Math.max(0,Math.floor(Number(s.order))):0,authorActorId:typeof s?.authorActorId=="string"&&s.authorActorId.trim().length>0?s.authorActorId.trim():null,createdAt:String(s?.createdAt||"").trim(),updatedAt:String(s?.updatedAt||s?.createdAt||"").trim(),deletedAt:typeof s?.deletedAt=="string"&&s.deletedAt.trim().length>0?s.deletedAt.trim():null})).filter(s=>s.id.length>0&&s.sessionId.length>0)})}function Nu(e,t,n=[],s=[]){const o=new Map;for(const l of[...e||[],...t||[]]){const i=Array.isArray(l?.taskEvents)?l.taskEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.taskId||l?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"task",entityId:y,taskId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}for(const l of n||[]){const i=Array.isArray(l?.entityEvents)?l.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||l?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"initiative",entityId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}for(const l of s||[]){const i=Array.isArray(l?.entityEvents)?l.entityEvents:[];for(const d of i){const m=String(d?.id||"").trim(),y=String(d?.entityId||l?.id||"").trim(),k=String(d?.workspaceId||"").trim(),S=String(d?.createdAt||"").trim();if(!m||!y||!k||!S)continue;const h={id:m,workspaceId:k,entityType:"workstream",entityId:y,action:String(d?.action||"").trim(),actor:String(d?.actor||"system").trim()||"system",actorType:d?.actorType==="ai"||d?.actorType==="human"||d?.actorType==="system"?d.actorType:"system",details:d?.details,createdAt:S},g=o.get(m);(!g||h.createdAt>g.createdAt)&&o.set(m,h)}}return Array.from(o.values()).sort((l,i)=>l.createdAt!==i.createdAt?l.createdAt.localeCompare(i.createdAt):l.id.localeCompare(i.id))}function Xg(e){return{taskIds:Array.from(e.taskIds.values()),taskWatermarks:Array.from(e.taskWatermarks.entries()),taskChangeKeys:Array.from((e.taskChangeKeys||new Map).entries()),initiativeWatermarks:Array.from(e.initiativeWatermarks.entries()),workstreamWatermarks:Array.from(e.workstreamWatermarks.entries()),aiProfileWatermarks:Array.from(e.aiProfileWatermarks.entries()),aiProfileChangeKeys:Array.from((e.aiProfileChangeKeys||new Map).entries()),documentWatermarks:Array.from(e.documentWatermarks.entries()),assetWatermarks:Array.from(e.assetWatermarks.entries()),documentReviewSessionWatermarks:Array.from(e.documentReviewSessionWatermarks.entries()),documentReviewCommentWatermarks:Array.from(e.documentReviewCommentWatermarks.entries()),annotatedAttachmentSessionWatermarks:Array.from(e.annotatedAttachmentSessionWatermarks.entries()),taskEventWatermarks:Array.from(e.taskEventWatermarks.entries()),taxonomyStateFingerprint:typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:""}}function ey(e,t){if(!e||typeof e!="object")return null;const n=typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",s=!t||!n||n===t?new Map(Array.isArray(e.taskWatermarks)?e.taskWatermarks:[]):new Map;return{taskIds:new Set(Array.isArray(e.taskIds)?e.taskIds.map(l=>String(l||"").trim()).filter(l=>l.length>0):Array.from(s.keys())),taskWatermarks:s,taskChangeKeys:new Map(Array.isArray(e.taskChangeKeys)?e.taskChangeKeys:[]),initiativeWatermarks:new Map(Array.isArray(e.initiativeWatermarks)?e.initiativeWatermarks:[]),workstreamWatermarks:new Map(Array.isArray(e.workstreamWatermarks)?e.workstreamWatermarks:[]),aiProfileWatermarks:new Map(Array.isArray(e.aiProfileWatermarks)?e.aiProfileWatermarks:[]),aiProfileChangeKeys:new Map(Array.isArray(e.aiProfileChangeKeys)?e.aiProfileChangeKeys:[]),documentWatermarks:new Map(Array.isArray(e.documentWatermarks)?e.documentWatermarks:[]),assetWatermarks:new Map(Array.isArray(e.assetWatermarks)?e.assetWatermarks:[]),documentReviewSessionWatermarks:new Map(Array.isArray(e.documentReviewSessionWatermarks)?e.documentReviewSessionWatermarks:[]),documentReviewCommentWatermarks:new Map(Array.isArray(e.documentReviewCommentWatermarks)?e.documentReviewCommentWatermarks:[]),annotatedAttachmentSessionWatermarks:new Map(Array.isArray(e.annotatedAttachmentSessionWatermarks)?e.annotatedAttachmentSessionWatermarks:[]),taskEventWatermarks:new Map(Array.isArray(e.taskEventWatermarks)?e.taskEventWatermarks:[])}}function yh(e,t){if(typeof window>"u")return null;try{const n=`${Qg}.${e}`,s=window.localStorage.getItem(n);if(!s)return null;const o=JSON.parse(s);return!o||o.v!==2&&o.v!==3&&o.v!==4&&o.v!==5&&o.v!==6&&o.v!==7&&o.v!==8&&o.v!==9&&o.v!==10&&o.v!==11?null:ey(o,t)}catch{return null}}function kh(e,t){if(typeof window>"u")return!1;try{const n=`${Qg}.${e}`;return window.localStorage.setItem(n,JSON.stringify({v:11,savedAt:new Date().toISOString(),...Xg(t)})),!0}catch{return!1}}function xw({currentWorkspaceId:e,workspaceSyncPhase:t,clearWorkspaceRetry:n,setWorkspaceSyncBusy:s,setUserGlobalSyncStatus:o,setUserGlobalSyncError:l,setWorkspaceLastErrorMessage:i,setWorkspaceLastErrorAt:d,reportSyncEvent:m,setAuthBlocked:y,setIsAuthenticated:k,checkAuthSession:S,ensureCloudWorkspaceReadyForSync:h,scheduleWorkspaceSyncRetry:g,persistWorkspaceSyncPatchSafely:v}){const A=async(I,B)=>{n(),s(!1),o("error");const V="Session expired. Sign in again to resume cloud sync.";l(V),i(V),d(new Date().toISOString()),m(e,{eventType:I==="handshake"?"handshake":I,status:"error",statusCode:B,errorMessage:V}),y(!0),k(!1),await S()};return{handleSyncAuthFailure:A,ensureWorkspaceSyncReady:async()=>{if(!ai(e)){const V="Workspace sync blocked: local workspace ID is unresolved.";return i(V),d(new Date().toISOString()),l(V),o("error"),!1}const I=await h();if(I.success)return!0;if(I.statusCode===401)return await A("handshake",401),!1;const B=I.error||"Workspace sync handshake failed.";return i(B),d(new Date().toISOString()),l(B),o("error"),m(e,{eventType:"handshake",status:"error",statusCode:I.statusCode,errorMessage:B}),I.transient||Bs(I.statusCode)?g(I.retryAfterMs):(t==="active"||t==="attach-cloud"||t==="provision-local")&&v({phase:"error",lastErrorMessage:B}),!1}}}function Iw({workspaceSyncPhase:e,lastBootstrapPhaseRef:t,bootstrapPhaseStartedAtRef:n,bootstrapLastProgressAtRef:s}){if(e==="attach-cloud"||e==="provision-local"){t.current=e,n.current===null&&(n.current=Date.now()),s.current=null;return}n.current=null,s.current=null}function Tw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:n,workspacePullInFlightRef:s,workspacePushInFlightRef:o,bootstrapPhaseStartedAtRef:l,bootstrapLastProgressAtRef:i,setWorkspaceLastErrorMessage:d,setWorkspaceLastErrorAt:m,setUserGlobalSyncStatus:y,setUserGlobalSyncError:k,setWorkspaceSyncBusy:S,persistWorkspaceSyncPatchSafely:h}){if(!t||n!=="attach-cloud"&&n!=="provision-local")return;const g=window.setInterval(()=>{if(n!=="attach-cloud"&&n!=="provision-local"||s.current||o.current)return;const v=Math.max(l.current??0,i.current??0);if(v>0&&Date.now()-v<vw)return;const _=`Workspace sync ${n==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;d(_),m(new Date().toISOString()),y("error"),k(_),S(!1),h({phase:"error",lastErrorMessage:_}),Un("workspace_sync_bootstrap_timeout",{workspaceId:e,phase:n})},1e4);return()=>window.clearInterval(g)}function Rw(e){const{workspaceSyncPhase:t,lastBootstrapPhase:n,workspaceLastPullAt:s}=e;return t==="provision-local"?"provision-local":t==="attach-cloud"?"attach-cloud":t==="active"||n==="active"?"active":n==="provision-local"||n==="attach-cloud"?n:s?"attach-cloud":"provision-local"}const ff={allowed:!0};function Jn(e,t){return{allowed:!1,reason:e,retainPendingSignature:t?.retainPendingSignature===!0}}function hf(e,t){return e.cloudAuthConfigured?e.runtimeMode!=="local"?Jn("runtime-not-local"):e.workspaceCloudSyncEnabled?(t?.requireValidWorkspace??!0)&&!ai(e.currentWorkspaceId)?Jn("invalid-workspace"):null:Jn("sync-disabled"):Jn("cloud-auth-unconfigured")}function $p(e){const t=hf(e);return t||(e.repairModeActive&&!e.repairModeBypass?Jn("repair-active",{retainPendingSignature:!0}):e.workspaceSyncPhase==="attach-cloud"?Jn("attach-cloud",{retainPendingSignature:!0}):e.isAuthenticated?e.pushInFlight?Jn("push-in-flight",{retainPendingSignature:!0}):e.pullInFlight?Jn("pull-in-flight",{retainPendingSignature:!0}):ff:Jn("auth-required"))}function Up(e){const t=hf(e);return t||(e.repairModeActive&&!e.repairModeBypass?Jn("repair-active"):e.workspaceSyncPhase==="provision-local"?Jn("provision-local"):e.retryPending?Jn("retry-pending"):e.isAuthenticated?e.pullInFlight?Jn("pull-in-flight"):e.pushInFlight?Jn("push-in-flight"):ff:Jn("auth-required"))}function zp(e){const t=hf(e,{requireValidWorkspace:!1});return t||(e.isAuthenticated?ff:Jn("auth-required"))}function jw(e){return Jn("lease-held",{retainPendingSignature:e==="push"})}function Ad(e){return e.cloudAuthConfigured&&e.runtimeMode==="local"&&e.workspaceCloudSyncEnabled&&e.authSessionResolved}function Nw({enabled:e,phase:t,busy:n,retryAt:s,lastErrorMessage:o}){return e?t==="provision-local"?{status:"syncing",summary:n?"Uploading this workspace to cloud for the first time.":"Preparing the first upload to cloud.",recommendedAction:"Keep this window open while the first upload finishes. If it seems stalled, press Sync."}:t==="attach-cloud"?{status:"syncing",summary:n?"Pulling the cloud workspace into this device.":"Waiting for the first cloud pull into this device.",recommendedAction:"Keep this window open for the first cloud pull. If it does not move, press Repair."}:s?{status:"attention",summary:"Sync hit a temporary problem and will retry automatically.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."}:o||t==="error"?{status:"attention",summary:"Sync needs attention before it can continue.",recommendedAction:"Press Sync to retry. If the same error keeps returning, press Repair."}:n?{status:"syncing",summary:"Sync is currently running.",recommendedAction:"No action needed."}:{status:"healthy",summary:"Sync is healthy.",recommendedAction:"No action needed."}:{status:"off",summary:"Sync is turned off for this workspace.",recommendedAction:"Turn on sync when you are ready to back up this workspace."}}function Pw(e){return Ad(e)&&e.workspaceSyncPhase!=="attach-cloud"&&e.workspaceSyncReferenceSnapshotsReady}function Mw(e){return Ad(e)&&e.workspaceSyncPhase==="active"&&e.workspaceSyncReferenceSnapshotsReady}function Ew(e){return Ad(e)?e.workspaceSyncPhase==="provision-local"||e.workspaceSyncPhase==="error"||e.retryPending?{shouldStart:!1,shouldKickOffImmediately:!1}:{shouldStart:!0,shouldKickOffImmediately:e.workspaceSyncPhase==="attach-cloud"||!e.lastPullAt}:{shouldStart:!1,shouldKickOffImmediately:!1}}function Dw(e){return Ad(e)&&e.isAuthenticated&&e.workspaceSyncPhase==="active"}function Lw(e){return Ad(e)&&e.isAuthenticated&&e.workspaceSyncPhase!=="provision-local"&&e.workspaceSyncPhase!=="attach-cloud"&&!e.alreadyRan}function Bw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,workspaceSyncPhase:s,workspacePullInFlightRef:o,realtimePullDebounceRef:l,realtimeSuppressedEventIdsRef:i,clearWorkspaceRetry:d,isWorkspaceRetryPending:m,pullWorkspaceChangesFromCloud:y}){return{handleRealtimeSignal:g=>{if(!e||t!=="local"||!n||s==="provision-local")return;const v=String(g?.eventId||"").trim();v&&i.current.delete(v)||o.current||(m()&&d(),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>{l.current=null,y()},180))},recordSuppressedEventIds:(g,v)=>{const A=v?.queueRef,_=Number.isFinite(v?.maxQueueSize)?Math.max(1,Number(v?.maxQueueSize)):2048,I=Number.isFinite(v?.ttlMs)?Math.max(0,Number(v?.ttlMs)):null;for(const B of g){const V=String(B||"").trim();!V||i.current.has(V)||(i.current.add(V),A&&A.current.push(V),I!==null&&window.setTimeout(()=>{i.current.delete(V)},I))}if(A)for(;A.current.length>_;){const B=A.current.shift();B&&i.current.delete(B)}},clearRealtimePullDebounce:()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null)}}}function ty(e){e.workspaceLastPushedWatermarksRef.current=new Map,e.workspaceLastPushedTaskChangeKeysRef.current=new Map,e.workspaceLastPushedInitiativeIdsRef.current=new Set,e.workspaceLastPushedInitiativeWatermarksRef.current=new Map,e.workspaceLastPushedWorkstreamIdsRef.current=new Set,e.workspaceLastPushedWorkstreamWatermarksRef.current=new Map,e.workspaceLastPushedAiProfileIdsRef.current=new Set,e.workspaceLastPushedAiProfileWatermarksRef.current=new Map,e.workspaceLastPushedAiProfileChangeKeysRef.current=new Map,e.workspaceLastPushedDocumentPathsRef.current=new Set,e.workspaceLastPushedDocumentWatermarksRef.current=new Map,e.workspaceLastPushedAssetPathsRef.current=new Set,e.workspaceLastPushedAssetWatermarksRef.current=new Map,e.workspaceBaselineResetReasonRef.current="repair-reset"}function Ww(e){ty(e),e.workspaceLastPushedDocumentPathsRef.current=new Set,e.workspaceLastPushedDocumentWatermarksRef.current=new Map,e.workspaceLastPushedAssetPathsRef.current=new Set,e.workspaceLastPushedAssetWatermarksRef.current=new Map,e.workspaceLastPushedDocumentReviewSessionIdsRef.current=new Set,e.workspaceLastPushedDocumentReviewSessionWatermarksRef.current=new Map,e.workspaceLastPushedDocumentReviewCommentIdsRef.current=new Set,e.workspaceLastPushedDocumentReviewCommentWatermarksRef.current=new Map,e.workspaceLastPushedAnnotatedAttachmentSessionIdsRef.current=new Set,e.workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef.current=new Map,e.workspaceLastPushedTaskEventWatermarksRef.current=new Map}function Fw({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:n,workspaceLastPullAt:s,lastBootstrapPhaseRef:o,workspaceRepairModeRef:l,workspaceForceFullAiProfilePushRef:i,workspaceStartupRepairRanRef:d,workspaceStartupFullReconcileRanRef:m,workspaceFullReconcileInFlightRef:y,workspacePullCursorRef:k,workspaceAttachBootstrapBaselineSignatureRef:S,workspaceCaptureAttachBootstrapBaselineRef:h,workspacePendingSignatureRef:g,workspaceLastPushedSignatureRef:v,workspaceLastPushedWatermarksRef:A,workspaceLastPushedTaskChangeKeysRef:_,workspaceLastPushedInitiativeIdsRef:I,workspaceLastPushedInitiativeWatermarksRef:B,workspaceLastPushedWorkstreamIdsRef:V,workspaceLastPushedWorkstreamWatermarksRef:L,workspaceLastPushedAiProfileIdsRef:J,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ve,workspaceLastPushedDocumentPathsRef:re,workspaceLastPushedDocumentWatermarksRef:x,workspaceLastPushedAssetPathsRef:K,workspaceLastPushedAssetWatermarksRef:ue,workspaceLastPushedDocumentReviewSessionIdsRef:pe,workspaceLastPushedDocumentReviewSessionWatermarksRef:X,workspaceLastPushedDocumentReviewCommentIdsRef:M,workspaceLastPushedDocumentReviewCommentWatermarksRef:O,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:de,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ge,workspaceLastPushedTaskEventWatermarksRef:$,workspaceBaselineResetReasonRef:_e,bootstrapPhaseStartedAtRef:je,bootstrapLastProgressAtRef:se,acquireWorkspaceSyncLease:ce,releaseWorkspaceSyncLease:Re,forceClearWorkspaceSyncLease:Pe,clearWorkspaceRetry:Ce,clearWorkspaceIssue:Ee,reportWorkspaceWindowContention:U,reportSyncEvent:T,persistWorkspaceSyncPatch:b,persistWorkspaceSyncWatermarksSnapshotBestEffort:j,buildWorkspaceSyncSignature:D,pullWorkspaceChangesFromCloud:te,pushWorkspaceChangesToCloud:P,cloudAuthConfigured:H,runtimeMode:be,isAuthenticated:z,checkAuthSession:ie}){const ee=n==="provision-local"?"push":n==="attach-cloud"?"bootstrap":"pull";return{retryWorkspaceCloudSync:async()=>{Ce();let Se=zp({cloudAuthConfigured:H,runtimeMode:be,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:z});if(!Se.allowed&&Se.reason==="auth-required"){if(!await ie())return T(e,{eventType:ee,status:"error",errorMessage:"Manual sync retry blocked: sign in is required.",details:{source:"retry.blocked",reason:"auth-required",phase:n}}),!1;Se=zp({cloudAuthConfigured:H,runtimeMode:be,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:!0})}if(!Se.allowed)return T(e,{eventType:ee,status:"error",errorMessage:`Manual sync retry blocked: ${Se.reason}.`,details:{source:"retry.blocked",reason:Se.reason,phase:n}}),!1;if(i.current=!0,n==="provision-local"){const Me=D();return Me?P(Me,{forceAllAiProfiles:!0}):!1}const we=await te();if(n==="attach-cloud")return we;const Te=D();if(Te){g.current=Te;const Me=await P(Te,{forceAllAiProfiles:i.current===!0});return we||Me}return we},resetWorkspaceSyncCursorAndPull:async()=>{if(!await ce(e,"repair")&&(Pe(e),!await ce(e,"repair"))){U("repair"),T(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because another window is already syncing this workspace.",details:{source:"repair.blocked",reason:"lease-held",phase:n}});return}const we=Rw({workspaceSyncPhase:n,lastBootstrapPhase:o.current,workspaceLastPullAt:s}),Te=we==="provision-local",Me=we==="active";Ce(),Ee();try{if(!t){T(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because workspace sync is turned off.",details:{source:"repair.blocked",reason:"sync-disabled",phase:n}});return}if(je.current=null,se.current=null,k.current=null,S.current="",h.current=!1,g.current="",v.current="",i.current=!1,d.current=!1,m.current=!1,y.current=!1,Te?Ww({workspaceLastPushedWatermarksRef:A,workspaceLastPushedTaskChangeKeysRef:_,workspaceLastPushedInitiativeIdsRef:I,workspaceLastPushedInitiativeWatermarksRef:B,workspaceLastPushedWorkstreamIdsRef:V,workspaceLastPushedWorkstreamWatermarksRef:L,workspaceLastPushedAiProfileIdsRef:J,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ve,workspaceLastPushedDocumentPathsRef:re,workspaceLastPushedDocumentWatermarksRef:x,workspaceLastPushedAssetPathsRef:K,workspaceLastPushedAssetWatermarksRef:ue,workspaceLastPushedDocumentReviewSessionIdsRef:pe,workspaceLastPushedDocumentReviewSessionWatermarksRef:X,workspaceLastPushedDocumentReviewCommentIdsRef:M,workspaceLastPushedDocumentReviewCommentWatermarksRef:O,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:de,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:ge,workspaceLastPushedTaskEventWatermarksRef:$,workspaceBaselineResetReasonRef:_e}):Me&&ty({workspaceLastPushedWatermarksRef:A,workspaceLastPushedTaskChangeKeysRef:_,workspaceLastPushedInitiativeIdsRef:I,workspaceLastPushedInitiativeWatermarksRef:B,workspaceLastPushedWorkstreamIdsRef:V,workspaceLastPushedWorkstreamWatermarksRef:L,workspaceLastPushedAiProfileIdsRef:J,workspaceLastPushedAiProfileWatermarksRef:me,workspaceLastPushedAiProfileChangeKeysRef:ve,workspaceLastPushedDocumentPathsRef:re,workspaceLastPushedDocumentWatermarksRef:x,workspaceLastPushedAssetPathsRef:K,workspaceLastPushedAssetWatermarksRef:ue,workspaceBaselineResetReasonRef:_e}),j(),l.current=!0,T(e,{eventType:"bootstrap",status:"success",errorMessage:"Manual sync repair started.",details:{source:"repair.started",phase:n,repairPhase:we,lastBootstrapPhase:o.current}}),await b({phase:we,pullCursor:null,lastErrorMessage:null}),we==="provision-local"){const lt=D();if(!lt)return;await P(lt,{forceAllAiProfiles:!0,repairMode:!0});return}const nt=await te({repairMode:!0});if(we!=="active"||!nt)return;const gt=D();if(!gt)return;g.current=gt,await P(gt,{forceAllAiProfiles:!0,repairMode:!0})}finally{l.current=!1,Re(e)}}}}function Ow({workspaceSyncPhase:e,forceCursorNull:t,currentCursor:n}){const s=e==="attach-cloud";return{bootstrap:s,cursor:s||t===!0?null:n,successEventType:s?"bootstrap":"pull"}}function $w({workspaceSyncPhase:e,forceCursorNull:t,startupFullReconcileRan:n,pendingSignature:s,fallbackSignature:o,lastPushedSignature:l}){const i=e==="attach-cloud",d=s||o,m=!i&&d&&d!==l?d:null;return{successEventType:i?"bootstrap":"pull",shouldCaptureAttachBootstrapBaseline:i,shouldClearPendingSignature:i||m!==null,shouldRefreshReferenceSnapshots:i,shouldSeedWorkspaceSnapshotPushBaseline:i,shouldScheduleStartupFullReconcile:!t&&!i&&!n,deferredPushSignature:m}}function Uw({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,checkAuthSession:i,resolveCloudAuthUrl:d,ensureCloudWorkspaceReadyForSync:m,ensureWorkspaceSyncReady:y,handleSyncAuthFailure:k,clearWorkspaceRetry:S,clearWorkspaceIssue:h,isWorkspaceRetryPending:g,scheduleWorkspaceSyncRetry:v,persistWorkspaceSyncPatchSafely:A,persistWorkspaceSyncPatchBestEffort:_,persistWorkspaceSyncWatermarksSnapshotBestEffort:I,reportSyncEvent:B,acquireWorkspaceSyncLease:V,releaseWorkspaceSyncLease:L,reportWorkspaceWindowContention:J,refreshWorkspaceSyncMarkdownDocumentsSnapshot:me,refreshWorkspaceSyncAiProfilesSnapshot:ve,refreshWorkspaceSyncAssetsSnapshot:re,refreshWorkspaceSyncPlanningEntitiesSnapshot:x,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:K,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:ue,refreshLocalWorkspaceTaskCollections:pe,buildWorkspaceSyncPayload:X,buildWorkspaceSyncSignature:M,seedWorkspaceSnapshotPushBaseline:O,shouldSuppressAttachBootstrapPush:de,recordSuppressedEventIds:ge,workspaceRepairModeRef:$,workspaceForceFullAiProfilePushRef:_e,workspacePushInFlightRef:je,workspacePullInFlightRef:se,workspacePendingPushReplayRef:ce,workspaceLastPushedSignatureRef:Re,workspacePendingSignatureRef:Pe,workspaceLastPushedTaskIdsRef:Ce,workspaceDeletedTaskIdsRef:Ee,workspaceDeletedTaskWatermarksRef:U,workspacePullCursorRef:T,workspaceLastPushedWatermarksRef:b,workspaceLastPushedTaskChangeKeysRef:j,workspaceLastPushedInitiativeIdsRef:D,workspaceLastPushedInitiativeWatermarksRef:te,workspaceLastPushedWorkstreamIdsRef:P,workspaceLastPushedWorkstreamWatermarksRef:H,workspaceLastPushedAiProfileIdsRef:be,workspaceLastPushedAiProfileWatermarksRef:z,workspaceLastPushedAiProfileChangeKeysRef:ie,workspaceLastPushedDocumentPathsRef:ee,workspaceLastPushedDocumentWatermarksRef:Q,workspaceLastPushedAssetPathsRef:q,workspaceLastPushedAssetWatermarksRef:Se,workspaceLastPushedDocumentReviewSessionIdsRef:we,workspaceLastPushedDocumentReviewSessionWatermarksRef:Te,workspaceLastPushedDocumentReviewCommentIdsRef:Me,workspaceLastPushedDocumentReviewCommentWatermarksRef:nt,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:gt,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:lt,workspaceLastPushedTaskEventWatermarksRef:St,workspaceBaselineResetReasonRef:Ke,workspaceCaptureAttachBootstrapBaselineRef:Ct,workspaceStartupFullReconcileRanRef:dt,workspaceFullReconcileInFlightRef:Xe,bootstrapLastProgressAtRef:ct,realtimeSuppressedEventQueueRef:ne,setWorkspaceSyncBusy:st,setUserGlobalSyncStatus:Ye,setUserGlobalSyncError:Pt,setWorkspaceLastErrorMessage:kt,setWorkspaceLastErrorAt:It,setWorkspaceLastPullAt:Ft,setWorkspaceLastPushAt:Mt,setWorkspaceSyncPendingChanges:Be,setTasks:et,setArchivedTasks:Ue}){const Qe=async(ot,ae)=>{let ze=$p({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,repairModeActive:$.current===!0,repairModeBypass:ae?.repairMode===!0,pushInFlight:je.current,pullInFlight:se.current});if(!ze.allowed&&ze.reason==="auth-required"){if(!await i())return!1;ze=$p({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:$.current===!0,repairModeBypass:ae?.repairMode===!0,pushInFlight:je.current,pullInFlight:se.current})}if(!ze.allowed)return ze.retainPendingSignature&&(Pe.current=ot),!1;if(de(ot))return!1;if(!await V(s,"push")){const c=jw("push");return!c.allowed&&c.retainPendingSignature&&(Pe.current=ot),J("push"),!1}je.current=!0,st(!0),Ye("syncing"),Pt(null);const Ot=Date.now(),Bt=ae?.forceAllAiProfiles===!0||_e.current===!0,Oe=ae?.repairMode===!0||$.current===!0;let Lt=null,vt=!1,E=ot;try{if(await me(),await ve(),await re(),await x(),await K(),!await y())return!1;const Y=M();if(Y&&(E=Y),de(E))return!1;const ye=ce.current,He=ye&&ye.signature===E&&(!Bt||ye.forceAllAiProfiles===!0)&&(!Oe||ye.repairMode===!0)?ye:null,Ve=He?.payload||X({forceAllAiProfiles:Bt});Lt=Ve,vt=He!==null,Be(Ve.changes.length);const Ne=await RS({resolveCloudAuthUrl:d,workspaceId:s,payload:Ve,ensureCloudWorkspaceReadyForSync:m,repairMode:He?.repairMode??Oe});if(!Ne.success){if(Ne.status===401)return ce.current=null,await k("push",401),!1;let Et=Ne.error?`Workspace sync push failed (${Ne.status||0}): ${Ne.error}`:`Workspace sync push failed (${Ne.status||0})`;return Ne.status===413&&(Et="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),Ye("error"),Pt(Et),kt(Et),It(new Date().toISOString()),B(s,{eventType:"push",status:"error",statusCode:Ne.status,errorMessage:Et,requestMs:Ne.requestMs,details:{payloadDiagnostics:Ve.deltaDiagnostics||null,replayedPayload:vt}}),Pe.current=E,Ne.transient||Bs(Ne.status)?(ce.current={signature:E,payload:Ve,forceAllAiProfiles:He?.forceAllAiProfiles??Bt,repairMode:He?.repairMode??Oe},v(Ne.retryAfterMs)):(ce.current=null,o==="active"&&A({phase:"error",lastErrorMessage:Et})),!1}ce.current=null,Re.current=E,Ce.current=Ne.currentTaskIds,b.current=Ne.currentTaskWatermarks?new Map(Ne.currentTaskWatermarks):new Map(b.current),j.current=Ne.currentTaskChangeKeys?new Map(Ne.currentTaskChangeKeys):new Map(j.current),D.current=new Set(Ne.currentInitiativeIds),te.current=new Map(Ne.currentInitiativeWatermarks),P.current=new Set(Ne.currentWorkstreamIds),H.current=new Map(Ne.currentWorkstreamWatermarks),be.current=new Set(Ne.currentAiProfileIds),z.current=new Map(Ne.currentAiProfileWatermarks),ie.current=Ne.currentAiProfileChangeKeys?new Map(Ne.currentAiProfileChangeKeys):new Map(ie.current),ee.current=new Set(Ne.currentDocumentPaths),Q.current=new Map(Ne.currentDocumentWatermarks),q.current=new Set(Ne.currentAssetPaths),Se.current=new Map(Ne.currentAssetWatermarks),we.current=new Set(Ne.currentDocumentReviewSessionIds),Te.current=new Map(Ne.currentDocumentReviewSessionWatermarks),Me.current=new Set(Ne.currentDocumentReviewCommentIds),nt.current=new Map(Ne.currentDocumentReviewCommentWatermarks),gt.current=new Set(Ne.currentAnnotatedAttachmentSessionIds),lt.current=new Map(Ne.currentAnnotatedAttachmentSessionWatermarks),St.current=new Map(Ne.currentTaskEventWatermarks),Bt&&(_e.current=!1);for(const[Et,Tt]of Ne.pushedWatermarks)b.current.set(Et,Tt);for(const[Et,Tt]of Ne.pushedTaskChangeKeys||new Map)j.current.set(Et,Tt);if(Ne.deleteTaskIds.size>0)for(const Et of Ne.deleteTaskIds)Ee.current.delete(Et),U.current.delete(Et),b.current.delete(Et),j.current.delete(Et);const Vt=await I();if(Ke.current=Vt?null:"storage-write-failed",Array.isArray(Ne.emittedEventIds)&&Ne.emittedEventIds.length>0&&ge(Ne.emittedEventIds,{queueRef:ne,maxQueueSize:2048}),Array.isArray(Ne.appliedTaskUpserts)&&Ne.appliedTaskUpserts.length>0){const Et=await Bp(s,Ne.appliedTaskUpserts.map(Tt=>({op:"upsert",archived:Tt.archived===!0,task:Tt.task})));if(Et.ok){for(const Tt of Ne.appliedTaskUpserts){const Wt=String(Tt?.task?.id||"").trim(),Ht=String(Tt?.task?.updatedAt||Tt?.task?.createdAt||"").trim();!Wt||!Ht||b.current.set(Wt,Ht)}try{await pe()}catch{Un("push_local_task_refresh_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length})}}else Un("push_local_task_apply_failed",{workspaceId:s,taskCount:Ne.appliedTaskUpserts.length,status:Et.status,failures:Et.failures})}S(),h();const qt=Ne.syncedAt||new Date().toISOString();return Re.current=M(),Mt(qt),Be(0),Ye("idle"),A({phase:"active",lastPushAt:qt,lastSyncedAt:qt,lastErrorMessage:null}),B(s,{eventType:o==="provision-local"?"bootstrap":"push",status:"success",changeCount:Ne.changeCount,requestMs:Ne.requestMs,details:{payloadDiagnostics:Ve.deltaDiagnostics||null,replayedPayload:vt}}),!0}catch(c){const Y="Workspace sync push failed.";return Ye("error"),Pt(Y),kt(Y),It(new Date().toISOString()),Pe.current=E,Lt&&(ce.current={signature:E,payload:Lt,forceAllAiProfiles:Bt,repairMode:Oe}),v(),B(s,{eventType:"push",status:"error",errorMessage:`${Y} ${String(c?.message||"").trim()}`.trim(),details:{replayedPayload:vt}}),Un("push_failed_exception",{workspaceId:s,elapsedMs:Date.now()-Ot}),!1}finally{je.current=!1,st(se.current),L(s);const c=Pe.current,Y=M();c&&Y&&Y!==Re.current&&!se.current&&!g()&&(Pe.current="",window.setTimeout(()=>{Qe(Y)},120))}},yt=async ot=>{let ae=Up({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:l,repairModeActive:$.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:se.current,pushInFlight:je.current});if(!ae.allowed&&ae.reason==="auth-required"){if(!await i())return!1;ae=Up({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:n,currentWorkspaceId:s,workspaceSyncPhase:o,isAuthenticated:!0,repairModeActive:$.current===!0,repairModeBypass:ot?.repairMode===!0,retryPending:g(),pullInFlight:se.current,pushInFlight:je.current})}if(!ae.allowed)return!1;if(!await V(s,"pull"))return J("pull"),!1;se.current=!0,st(!0),Ye("syncing"),Pt(null);const bt=Date.now();try{if(!await y())return!1;const Bt=Ow({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,currentCursor:T.current}),Oe=await jS({resolveCloudAuthUrl:d,workspaceId:s,cursor:Bt.cursor,bootstrap:Bt.bootstrap,ensureCloudWorkspaceReadyForSync:m,maxPages:20,repairMode:ot?.repairMode===!0||$.current===!0,onPagePulled:()=>{ct.current=Date.now()},onChangesApplied:()=>{ct.current=Date.now()}});if(!Oe.success){if(Oe.kind==="pull_http"&&Oe.status===401)return await k("pull",401),!1;if(Oe.kind==="apply_auth")return await k("apply",401),!1;if(Oe.kind==="pull_http"&&Oe.errorCode==="INVALID_SYNC_CURSOR"){const ye="Saved sync cursor was invalid. Clearing it and retrying from the beginning.";return T.current=null,A({pullCursor:null}),Ye("error"),Pt(ye),kt(ye),It(new Date().toISOString()),B(s,{eventType:"pull",status:"error",statusCode:Oe.status,errorMessage:ye,requestMs:Oe.pullRequestMs,details:{recovery:"cursor-reset",...Oe.serverDiagnostics?{serverPullDiagnostics:Oe.serverDiagnostics}:{}}}),v(150),!1}let Y=Oe.kind==="apply_payload"||Oe.kind==="apply_all_candidates"||Oe.kind==="exception"?String(Oe.error||"Workspace sync apply failed."):`Workspace sync pull failed (${Oe.status||0})`;return Oe.status===413&&(Y="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),Ye("error"),Pt(Y),kt(Y),It(new Date().toISOString()),B(s,{eventType:Oe.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:Oe.status,errorMessage:Y,requestMs:Oe.pullRequestMs,details:{pages:Oe.pages,applyMs:Oe.applyMs,...Oe.serverDiagnostics?{serverPullDiagnostics:Oe.serverDiagnostics}:{}}}),Oe.transient||Oe.hasTransientApplyFailure||Bs(Oe.status)?v(Oe.retryAfterMs):A({phase:"error",lastErrorMessage:Y}),!1}Array.isArray(Oe.emittedEventIds)&&ge(Oe.emittedEventIds,{ttlMs:6e4}),Oe.pulledDeleteTaskIds.size>0&&(et(Y=>Y.filter(ye=>!Oe.pulledDeleteTaskIds.has(String(ye.id||"")))),Ue(Y=>Y.filter(ye=>!Oe.pulledDeleteTaskIds.has(String(ye.id||"")))));const Lt=Array.isArray(Oe.documentDecryptFailures)?Oe.documentDecryptFailures.filter(Y=>String(Y||"").trim().length>0):[];if(Lt.length>0&&Un("pull_document_decrypt_failures",{workspaceId:s,failureCount:Lt.length}),T.current=Oe.cursor||null,Oe.appliedChanges>0&&(Oe.pulledActiveUpserts||Oe.pulledArchivedUpserts||Oe.pulledTaskEventUpserts||Oe.pulledPlanningUpserts))try{await pe()}catch{Un("pull_local_refresh_failed",{workspaceId:s,appliedChanges:Oe.appliedChanges})}S(),h();const vt=Oe.syncedAt||new Date().toISOString();Ft(vt),Be(0),Ye("idle");const E=$w({workspaceSyncPhase:o,forceCursorNull:ot?.forceCursorNull===!0,startupFullReconcileRan:dt.current,pendingSignature:Pe.current,fallbackSignature:M(),lastPushedSignature:Re.current});if(E.shouldCaptureAttachBootstrapBaseline&&(Ct.current=!0),E.shouldClearPendingSignature&&(Pe.current="",ce.current=null),await _({phase:"active",pullCursor:T.current,lastPullAt:vt,lastSyncedAt:vt,lastErrorMessage:null}),B(s,{eventType:E.successEventType,status:"success",changeCount:Oe.appliedChanges,requestMs:Oe.pullRequestMs,details:{pages:Oe.pages,applyMs:Oe.applyMs,...Oe.serverDiagnostics?{serverPullDiagnostics:Oe.serverDiagnostics}:{}}}),E.shouldRefreshReferenceSnapshots&&(await me(),await re(),await K(),await ue()),E.shouldSeedWorkspaceSnapshotPushBaseline&&O(),E.shouldRefreshReferenceSnapshots||E.shouldSeedWorkspaceSnapshotPushBaseline)return!0;if(E.shouldScheduleStartupFullReconcile&&(dt.current=!0,window.setTimeout(()=>{Xe.current||(Xe.current=!0,yt({forceCursorNull:!0}).finally(()=>{Xe.current=!1}))},250)),ot?.forceCursorNull===!0&&ot?.repairMode!==!0&&o==="active"){const Y=M();Y&&(_e.current=!0,Pe.current=Y,window.setTimeout(()=>{Qe(Y,{forceAllAiProfiles:!0})},120))}else if(E.deferredPushSignature){const Y=E.deferredPushSignature;window.setTimeout(()=>{Qe(Y)},120)}return!0}catch(Ot){const Bt=String(Ot?.message||"").trim(),Oe=Bt?`Workspace sync pull failed. ${Bt}`:"Workspace sync pull failed.";return Ye("error"),Pt(Oe),kt(Oe),It(new Date().toISOString()),v(),B(s,{eventType:"pull",status:"error",errorMessage:Oe,requestMs:Date.now()-bt}),Un("pull_failed_exception",{workspaceId:s,elapsedMs:Date.now()-bt,error:Bt||null}),!1}finally{se.current=!1,st(je.current),L(s)}};return{pushWorkspaceChangesToCloud:Qe,pullWorkspaceChangesFromCloud:yt}}const vh={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1};function zw(e){const{currentWorkspaceId:t,cloudAuthConfigured:n,runtimeMode:s,authSessionResolved:o,isAuthenticated:l,authUserId:i,projectName:d,resolveCloudAuthUrl:m,resolveWebSocketUrl:y,realtimeSyncEnabled:k,tasks:S,archivedTasks:h,deletedTasks:g=[],initiatives:v,workstreams:A,taxonomies:_,taxonomyState:I,setupState:B,globalTheme:V,locale:L,globalWeekStartsOn:J,themeUseGlobalDefault:me,setTasks:ve,setArchivedTasks:re,setAuthBlocked:x,setIsAuthenticated:K,checkAuthSession:ue,setGlobalTheme:pe,setCurrentTheme:X,setSetupState:M,setLocale:O,setGlobalWeekStartsOn:de,fetchPlanningEntities:ge}=e,$=r.useMemo(()=>Cw(I),[I]),[_e,je]=r.useState("disconnected"),[se,ce]=r.useState(null),[Re,Pe]=r.useState(null),[Ce,Ee]=r.useState(null),[U,T]=r.useState(null),[b,j]=r.useState(null),[D,te]=r.useState(!1),[P,H]=r.useState("idle"),[be,z]=r.useState(null),[ie,ee]=r.useState(!1),[Q,q]=r.useState(0),[Se,we]=r.useState([]),[Te,Me]=r.useState(""),nt=r.useRef(S||[]),gt=r.useRef(h||[]),lt=r.useRef(v||[]),St=r.useRef(A||[]),Ke=r.useRef([]),Ct=r.useRef(new Set),[dt,Xe]=r.useState([]),[ct,ne]=r.useState(""),[st,Ye]=r.useState(null),[Pt,kt]=r.useState(null),[It,Ft]=r.useState(0),[Mt,Be]=r.useState(null),et=r.useRef([]),[Ue,Qe]=r.useState([]),[yt,ot]=r.useState(""),ae=r.useRef([]),ze=r.useRef(new Set),[bt,Ot]=r.useState([]),[Bt,Oe]=r.useState(""),Lt=r.useRef([]),vt=r.useRef([]),[E,c]=r.useState([]),[Y,ye]=r.useState(""),Ie=r.useRef([]),[He,Ve]=r.useState(vh),[Ne,Vt]=r.useState("degraded-fallback"),[qt,Et]=r.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),Tt=r.useRef(!1),Wt=r.useRef(null),Ht=r.useRef("missing-baseline"),sa=r.useRef(0),Kt=r.useRef(!1),Ka=r.useRef(new Set),Fa=r.useRef(""),Xa=r.useRef(""),wa=r.useRef(""),he=r.useRef(""),it=r.useRef(""),xe=r.useRef(""),jt=r.useRef(!1),tt=r.useRef(null),Gt=r.useRef(new Set),ga=r.useRef([]),Na=r.useRef(null),ua=r.useRef(()=>Promise.resolve(!1)),ca=r.useRef(async()=>{}),Dt=r.useRef(null),aa=r.useRef(null),Za=r.useRef("idle"),$t=r.useCallback(()=>{Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null)},[]),Qn=r.useCallback(R=>{if(typeof window>"u")return;$t();const C=Math.max(1,Math.floor(sa.current)+1);sa.current=C;const Ze=1500*2**Math.max(0,C-1),ht=Number.isFinite(Number(R))?Math.max(0,Math.floor(Number(R))):0,De=Math.max(Math.min(12e4,Ze),ht);Wt.current=window.setTimeout(()=>{Wt.current=null,ca.current({preferCloudOnFirstSync:!1})},De)},[$t]),ba=r.useCallback(R=>{Ve(C=>C[R]?C:{...C,[R]:!0})},[]),Qt=Object.values(He).every(Boolean),{workspaceRetryAt:Lr,isWorkspaceRetryPending:Ia,workspacePushInFlightRef:en,workspacePullInFlightRef:Ca,workspaceLastPushedSignatureRef:Jt,workspacePendingSignatureRef:Ta,workspaceLastPushedTaskIdsRef:la,workspaceDeletedTaskIdsRef:vn,workspaceDeletedTaskWatermarksRef:pn,workspacePullCursorRef:Xn,clearWorkspaceRetry:ma,scheduleWorkspaceRetry:_r,persistWorkspaceSyncPatch:Br,applyWorkspaceSyncPatchLocally:Sn,readWorkspaceSyncStateSnapshot:Ba,loadWorkspaceSyncState:Cr,applyWorkspaceSyncStateSnapshot:wn,saveWorkspaceCloudSyncSettings:Pn,acquireWorkspaceSyncLease:tn,releaseWorkspaceSyncLease:Aa,forceClearWorkspaceSyncLease:Wr}=fw({currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:te,setWorkspaceSyncPhase:H,setWorkspaceSyncSetupIntent:z,setWorkspaceLastPullAt:Pe,setWorkspaceLastPushAt:Ee,setWorkspaceLastErrorMessage:j}),_t=r.useCallback(R=>{(R.phase==="attach-cloud"||R.phase==="provision-local")&&(Za.current=R.phase,Dt.current===null&&(Dt.current=Date.now()),aa.current=null),wn(R)},[wn]),bn=r.useRef(new Map),fn=r.useRef(new Map),_n=r.useRef(new Set),Oa=r.useRef(new Map),Mn=r.useRef(new Set),ya=r.useRef(new Map),$a=r.useRef(new Set),Cn=r.useRef(new Map),da=r.useRef(new Map),En=r.useRef(new Set),Xt=r.useRef(new Map),Ua=r.useRef(new Set),_a=r.useRef(new Map),er=r.useRef(new Set),tr=r.useRef(new Map),Pa=r.useRef(new Set),na=r.useRef(new Map),pa=r.useRef(new Set),hn=r.useRef(new Map),an=r.useRef(new Map),fr=r.useCallback(R=>R?(la.current=new Set(R.taskIds),bn.current=R.taskWatermarks,fn.current=R.taskChangeKeys||new Map,_n.current=new Set(Array.from(R.initiativeWatermarks.keys())),Oa.current=R.initiativeWatermarks,Mn.current=new Set(Array.from(R.workstreamWatermarks.keys())),ya.current=R.workstreamWatermarks,$a.current=new Set(Array.from(R.aiProfileWatermarks.keys())),Cn.current=R.aiProfileWatermarks,da.current=R.aiProfileChangeKeys||new Map,En.current=new Set(Array.from(R.documentWatermarks.keys())),Xt.current=R.documentWatermarks,Ua.current=new Set(Array.from(R.assetWatermarks.keys())),_a.current=R.assetWatermarks,er.current=new Set(Array.from(R.documentReviewSessionWatermarks.keys())),tr.current=R.documentReviewSessionWatermarks,Pa.current=new Set(Array.from(R.documentReviewCommentWatermarks.keys())),na.current=R.documentReviewCommentWatermarks,pa.current=new Set(Array.from(R.annotatedAttachmentSessionWatermarks.keys())),hn.current=R.annotatedAttachmentSessionWatermarks,an.current=R.taskEventWatermarks,Ht.current=null,!0):!1,[la]),hr=r.useCallback(()=>({taskIds:la.current,taskWatermarks:bn.current,taskChangeKeys:fn.current,initiativeWatermarks:Oa.current,workstreamWatermarks:ya.current,aiProfileWatermarks:Cn.current,aiProfileChangeKeys:da.current,documentWatermarks:Xt.current,assetWatermarks:_a.current,documentReviewSessionWatermarks:tr.current,documentReviewCommentWatermarks:na.current,annotatedAttachmentSessionWatermarks:hn.current,taskEventWatermarks:an.current}),[]),ea=r.useRef(!1),Ss=r.useRef(!1),za=r.useRef(!1),ar=r.useRef(""),Xr=r.useRef(!1),gn=3e4,zn=k?3e4:15e3,Fr=Math.max(3e4,zn),An=r.useMemo(()=>{const R=Re?Date.parse(Re):NaN,C=Ce?Date.parse(Ce):NaN;return Number.isFinite(R)&&Number.isFinite(C)?R>=C?Re:Ce:Number.isFinite(R)?Re:Number.isFinite(C)?Ce:null},[Re,Ce]),Ha=r.useMemo(()=>Nw({enabled:D,phase:P,busy:ie,retryAt:Lr,lastErrorMessage:b}),[D,P,ie,Lr,b]),Ar=Ha.status,Ra=Ha.summary,ws=Ha.recommendedAction,nn=r.useCallback(R=>{const C=String(R||"").trim();if(!C)return null;const ht=gh()[C]?.updatedAt;return typeof ht=="string"&&ht.trim().length>0?ht.trim():null},[]),xr=r.useCallback((R,C)=>{const Ze=String(R||"").trim(),ht=String(C||"").trim();if(!Ze||!ht)return;const De=gh();De[Ze]={updatedAt:ht},_w(De)},[]),gr=r.useCallback(()=>{const R=B?.mode==="operations"?"operations":"core";return{theme:V,operatingMode:R,localization:{locale:L,weekStartsOn:J}}},[V,B?.mode,L,J]),Or=r.useCallback(async R=>{if(!(!R||typeof R!="object")){Kt.current=!0;try{const C={},Ze=Vc(R.theme);if(Ze&&(pe(Ze),me&&X(Ze),C.theme=Ze),(R.operatingMode==="core"||R.operatingMode==="operations")&&(M(ht=>ht&&{...ht,mode:R.operatingMode}),C.setup={mode:R.operatingMode}),R.localization&&typeof R.localization=="object"){const ht={};if(typeof R.localization.locale=="string"&&R.localization.locale.trim().length>0){const oe=Dg(R.localization.locale.trim());O(oe)}const De=String(R.localization.weekStartsOn||"").trim().toLowerCase();(De==="sunday"||De==="monday")&&(de(De),ht.weekStartsOn=De),Object.keys(ht).length>0&&(C.schedulePreferences=ht)}Object.keys(C).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(C)})}finally{Kt.current=!1}}},[me,pe,X,M,O,de]),yn=r.useCallback(async R=>{const C=R?.preferCloudOnFirstSync!==!1;if(!n)return;if(s!=="local"||!l){$t(),sa.current=0,je("disconnected");return}const Ze=String(i||"").trim();if(!Ze||Ze==="anonymous"){$t(),sa.current=0,je("disconnected");return}if(!Tt.current){je("syncing"),ce(null),Tt.current=!0;try{const ht=await NS({resolveCloudAuthUrl:m,userId:Ze,preferCloudOnFirstSync:C,getLocalUpdatedAt:nn,buildLocalSettings:gr,applyRemoteSettings:Or});if(!ht.success){je("error"),ht.transient?(ce(ht.error||"Sync failed temporarily. Retrying automatically."),Qn(ht.retryAfterMs)):($t(),sa.current=0,ce(ht.error||"Sync failed."));return}$t(),sa.current=0;const De=String(ht.updatedAt||"").trim()||new Date().toISOString();xr(Ze,De),je("idle"),ce(null),Ka.current.add(Ze),ht.mode==="pulled"&&(Fa.current="")}catch{je("error"),ce("Sync failed temporarily. Retrying automatically."),Qn()}finally{Tt.current=!1}}},[n,s,l,i,m,nn,gr,Or,xr,$t,Qn]);r.useEffect(()=>{ca.current=yn},[yn]),r.useEffect(()=>()=>{$t()},[$t]);const yr=r.useCallback(()=>{j(null),T(null)},[]),xn=r.useCallback(R=>{j(hh),T(new Date().toISOString()),je("error"),ce(hh),Un("workspace_sync_window_contention",{workspaceId:t,operation:R})},[t]),Dn=r.useCallback(async R=>{try{return await Br(R)}catch{return Sn(R)}},[Sn,Br]),nr=r.useCallback(R=>{Dn(R).catch(()=>{})},[Dn]),es=r.useCallback(()=>{const R={...hr(),taxonomyStateFingerprint:$},C=kh(t,R);return Dn({pushBaseline:Xg(R)}).catch(()=>{}),C},[hr,t,Dn,$]);r.useEffect(()=>{Xa.current="",wa.current="",he.current="",it.current="",xe.current="",ar.current="",Xr.current=!1,we([]),Me(""),et.current=[],Xe([]),ne(""),Qe([]),ot(""),Lt.current=[],vt.current=[],Ot([]),Oe(""),Ie.current=[],c([]),ye(""),Ve(vh),j(null),T(null),q(0),Gt.current=new Set,ga.current=[],bn.current=new Map,fn.current=new Map,_n.current=new Set,Oa.current=new Map,Mn.current=new Set,ya.current=new Map,$a.current=new Set,Cn.current=new Map,da.current=new Map,En.current=new Set,Xt.current=new Map,Ua.current=new Set,_a.current=new Map,er.current=new Set,tr.current=new Map,Pa.current=new Set,na.current=new Map,pa.current=new Set,hn.current=new Map,an.current=new Map,Ss.current=!1,Ma.current=!1;const R=yh(t,$);fr(R)||(Ht.current="missing-baseline")},[t,fr,$]),r.useEffect(()=>{if(Ht.current!=="missing-baseline")return;const R=yh(t,$);if(fr(R))return;const C=ey(Ba().pushBaseline,$);fr(C)&&kh(t,{...hr(),taxonomyStateFingerprint:$})},[hr,t,fr,Ba,$,D,P]);const $r=r.useCallback(R=>{_r(()=>ua.current(),{minDelayMs:R})},[_r]);r.useEffect(()=>{Iw({workspaceSyncPhase:P,lastBootstrapPhaseRef:Za,bootstrapPhaseStartedAtRef:Dt,bootstrapLastProgressAtRef:aa})},[P]),r.useEffect(()=>Tw({currentWorkspaceId:t,workspaceCloudSyncEnabled:D,workspaceSyncPhase:P,workspacePullInFlightRef:Ca,workspacePushInFlightRef:en,bootstrapPhaseStartedAtRef:Dt,bootstrapLastProgressAtRef:aa,setWorkspaceLastErrorMessage:R=>j(R),setWorkspaceLastErrorAt:R=>T(R),setUserGlobalSyncStatus:je,setUserGlobalSyncError:R=>ce(R),setWorkspaceSyncBusy:ee,persistWorkspaceSyncPatchSafely:nr}),[t,D,P,nr,Ca,en]);const Je=r.useCallback(async()=>IS({cloudAuthConfigured:n,runtimeMode:s,isAuthenticated:l,resolveCloudAuthUrl:m,workspaceId:t,workspaceName:d||t,allowProvisionOnMismatch:P!=="attach-cloud"}),[n,s,l,m,t,d,P]);r.useEffect(()=>{nt.current=S||[]},[S]),r.useEffect(()=>{gt.current=h||[]},[h]),r.useEffect(()=>{vn.current=new Set((g||[]).map(R=>String(R?.taskId||"").trim()).filter(R=>R.length>0)),pn.current=new Map((g||[]).map(R=>[String(R?.taskId||"").trim(),String(R?.deletedAt||"").trim()]).filter(([R,C])=>R.length>0&&Number.isFinite(Date.parse(C))))},[g,vn,pn]),r.useEffect(()=>{lt.current=v||[]},[v]),r.useEffect(()=>{St.current=A||[]},[A]);const Ut=r.useRef(!1),Ma=r.useRef(!1),oa=r.useCallback(R=>{const C=R?.forceAllAiProfiles===!0;return ew({tasks:nt.current,archivedTasks:gt.current,taskEvents:Nu(nt.current,gt.current,lt.current,St.current),lastPushedTaskIds:la.current,pendingDeletedTaskIds:vn.current,pendingDeletedTaskWatermarks:pn.current,initiatives:lt.current,workstreams:St.current,taxonomies:_||[],taxonomyState:I,lastPushedInitiativeIds:_n.current,lastPushedInitiativeWatermarks:Oa.current,lastPushedWorkstreamIds:Mn.current,lastPushedWorkstreamWatermarks:ya.current,aiProfiles:et.current,lastPushedAiProfileIds:C?new Set:$a.current,lastPushedAiProfileWatermarks:C?new Map:Cn.current,lastPushedAiProfileChangeKeys:C?new Map:da.current,documents:Ke.current,assets:ae.current,currentDocumentPaths:Ct.current,currentAssetPaths:ze.current,documentReviewSessions:Lt.current,documentReviewComments:vt.current,annotatedAttachmentSessions:Ie.current,lastPushedDocumentPaths:En.current,lastPushedDocumentWatermarks:Xt.current,lastPushedAssetPaths:Ua.current,lastPushedAssetWatermarks:_a.current,lastPushedDocumentReviewSessionIds:er.current,lastPushedDocumentReviewSessionWatermarks:tr.current,lastPushedDocumentReviewCommentIds:Pa.current,lastPushedDocumentReviewCommentWatermarks:na.current,lastPushedAnnotatedAttachmentSessionIds:pa.current,lastPushedAnnotatedAttachmentSessionWatermarks:hn.current,lastPushedTaskEventWatermarks:an.current,baselineResetReason:Ht.current,lastPushedWatermarks:bn.current,lastPushedTaskChangeKeys:fn.current})},[_,I]),cn=r.useCallback((R,C)=>{if(s==="local")try{const Ze={...C,workspaceId:R,details:Sm(C.details)};fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ze)}).catch(ht=>{Un("sync_event_post_failed",{workspaceId:R,eventType:C.eventType,status:C.status,error:String(ht?.message||ht||"")})})}catch(Ze){Un("sync_event_post_failed",{workspaceId:R,eventType:C.eventType,status:C.status,error:String(Ze?.message||Ze||"")})}},[s]),rn=r.useCallback(()=>tw({workspaceId:t,tasks:nt.current,archivedTasks:gt.current,taskEvents:Nu(nt.current,gt.current,lt.current,St.current),pendingDeletedTaskIds:vn.current,initiatives:lt.current,workstreams:St.current,taxonomies:_||[],aiProfiles:et.current,documents:Ke.current,assets:ae.current,documentReviewSessions:Lt.current,documentReviewComments:vt.current,annotatedAttachmentSessions:Ie.current}),[t,_,I]),bs=r.useMemo(()=>JSON.stringify({tasks:(S||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),status:String(R.status||"").trim(),referenceNumber:R.referenceNumber??null,localReferenceNumber:R.localReferenceNumber??null})).sort((R,C)=>R.id.localeCompare(C.id)),archivedTasks:(h||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),status:String(R.status||"").trim(),referenceNumber:R.referenceNumber??null,localReferenceNumber:R.localReferenceNumber??null})).sort((R,C)=>R.id.localeCompare(C.id)),initiatives:(v||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),isArchived:!!R.isArchived})).sort((R,C)=>R.id.localeCompare(C.id)),workstreams:(A||[]).map(R=>({id:String(R.id||"").trim(),updatedAt:String(R.updatedAt||R.createdAt||"").trim(),initiativeId:typeof R.initiativeId=="string"?R.initiativeId.trim():"",isArchived:!!R.isArchived})).sort((R,C)=>R.id.localeCompare(C.id)),taskEvents:Nu(S||[],h||[],v||[],A||[]).map(R=>({id:String(R.id||"").trim(),entityType:String(R.entityType||"task").trim(),entityId:String(R.entityId||R.taskId||"").trim(),createdAt:String(R.createdAt||"").trim(),action:String(R.action||"").trim()})).sort((R,C)=>R.id.localeCompare(C.id)),deletedTasks:(g||[]).map(R=>({taskId:String(R?.taskId||"").trim(),deletedAt:String(R?.deletedAt||"").trim()})).filter(R=>R.taskId.length>0&&Number.isFinite(Date.parse(R.deletedAt))).sort((R,C)=>R.taskId.localeCompare(C.taskId)),taxonomies:Array.isArray(_)?_:[],taxonomyState:I&&typeof I=="object"?I:null}),[S,h,g,v,A,_,I]),_s=r.useMemo(()=>{const R=[];for(const C of S||[]){const Ze=Array.isArray(C.attachments)?C.attachments.length:0;Ze>0&&R.push(`${C.id}:${Ze}`)}return R.join("|")},[S]),ts=r.useCallback(R=>{if(!R)return!1;if(Xr.current)return Xr.current=!1,ar.current=R,Jt.current=R,q(0),!0;const C=ar.current;return C?R===C?(Jt.current=R,q(0),!0):(ar.current="",!1):!1},[]),Ya=r.useCallback(async()=>{if(s==="local"&&ai(t)&&!(n&&(!o||!l)))try{const R=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.documents)?C.documents.map(oe=>({path:String(oe?.path||"").trim(),updatedAt:String(oe?.updatedAt||"").trim(),content:typeof oe?.content=="string"?oe.content:"",assetId:typeof oe?.assetId=="string"&&oe.assetId.trim().length>0?oe.assetId.trim():void 0,documentId:typeof oe?.documentId=="string"&&oe.documentId.trim().length>0?oe.documentId.trim():null,referenceNumber:Number.isFinite(Number(oe?.referenceNumber))?Math.max(1,Math.floor(Number(oe.referenceNumber))):null,version:Number.isFinite(Number(oe?.version))?Math.max(1,Math.floor(Number(oe.version))):null,taskId:typeof oe?.taskId=="string"&&oe.taskId.trim().length>0?oe.taskId.trim():null,logicalName:typeof oe?.logicalName=="string"&&oe.logicalName.trim().length>0?oe.logicalName.trim():null,caption:typeof oe?.caption=="string"&&oe.caption.trim().length>0?oe.caption.trim():null,originalFilename:typeof oe?.originalFilename=="string"&&oe.originalFilename.trim().length>0?oe.originalFilename.trim():null,linkRole:oe?.linkRole==="reference"?"reference":"attachment"})).filter(oe=>oe.path.length>0):[],ht=new Set(Array.isArray(C?.knownPaths)?C.knownPaths.map(oe=>String(oe||"").trim()).filter(oe=>oe.length>0):Ze.map(oe=>oe.path)),De=typeof C?.fingerprint=="string"?C.fingerprint:JSON.stringify(Ze.map(oe=>`${oe.path}:${oe.updatedAt}:${oe.content.length}`).sort());if(De===Xa.current)return;Xa.current=De,Ke.current=Ze,Ct.current=ht,we(Ze),Me(De)}catch(R){Un("documents_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}finally{ba("documents")}},[s,t,n,o,l,ba]),Wa=r.useCallback(async()=>{if(s!=="local"){Be("runtime-not-local");return}if(!ai(t)){Be("workspace-id-invalid");return}if(n&&(!o||!l)){Be(o?"auth-required":"auth-unresolved");return}Be(null);try{const R=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok){kt(`HTTP ${R.status}`),Ye(new Date().toISOString());return}const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.aiProfiles)?C.aiProfiles:[];Ft(Ze.length);const ht=Array.isArray(C?.aiProfiles)?C.aiProfiles.map(oe=>bw(oe)).filter(oe=>oe.id.length>0&&oe.workspaceId.length>0):[];kt(null),Ye(new Date().toISOString());const De=typeof C?.fingerprint=="string"?C.fingerprint:JSON.stringify(ht.map(oe=>[oe.id,oe.updatedAt,oe.name,oe.username,oe.archivedAt??"",oe.archivedReason??"",oe.mergedIntoProfileId??"",oe.rosterStateUpdatedAt??""].join(":")).sort());if(De===wa.current)return;wa.current=De,et.current=ht,Xe(ht),ne(De)}catch(R){kt(String(R?.message||R||"unknown-error")),Ye(new Date().toISOString()),Un("ai_profiles_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}finally{ba("aiProfiles")}},[s,t,n,o,l,ba]),Rt=r.useCallback(async()=>{if(s==="local"&&ai(t)&&!(n&&(!o||!l)))try{const R=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.assets)?C.assets.map(oe=>({path:String(oe?.path||"").trim(),updatedAt:String(oe?.updatedAt||"").trim(),contentBase64:typeof oe?.contentBase64=="string"?oe.contentBase64:"",assetId:typeof oe?.assetId=="string"&&oe.assetId.trim().length>0?oe.assetId.trim():void 0,kind:oe?.kind==="image"?"image":"file",mimeType:typeof oe?.mimeType=="string"&&oe.mimeType.trim().length>0?oe.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(oe?.referenceNumber))?Math.max(1,Math.floor(Number(oe.referenceNumber))):null,taskId:typeof oe?.taskId=="string"&&oe.taskId.trim().length>0?oe.taskId.trim():null,logicalName:typeof oe?.logicalName=="string"&&oe.logicalName.trim().length>0?oe.logicalName.trim():null,caption:typeof oe?.caption=="string"&&oe.caption.trim().length>0?oe.caption.trim():null,originalFilename:typeof oe?.originalFilename=="string"&&oe.originalFilename.trim().length>0?oe.originalFilename.trim():null,linkRole:oe?.linkRole==="reference"?"reference":oe?.linkRole==="image"?"image":"attachment"})).filter(oe=>oe.path.length>0&&oe.contentBase64.length>0):[],ht=new Set(Array.isArray(C?.knownPaths)?C.knownPaths.map(oe=>String(oe||"").trim()).filter(oe=>oe.length>0):Ze.map(oe=>oe.path)),De=typeof C?.fingerprint=="string"?C.fingerprint:JSON.stringify(Ze.map(oe=>`${oe.path}:${oe.updatedAt}:${oe.contentBase64.length}`).sort());if(De===he.current)return;he.current=De,ae.current=Ze,ze.current=ht,Qe(Ze),ot(De)}catch(R){Un("assets_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}finally{ba("assets")}},[s,t,n,o,l,ba]),kr=r.useCallback(async()=>{if(s==="local"&&ai(t)&&!(n&&(!o||!l)))try{const R=await fetch(`/api/taskforce/planning/bootstrap?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.initiatives)?C.initiatives.filter(De=>!!(De&&typeof De=="object"&&typeof De.id=="string")):[],ht=Array.isArray(C?.workstreams)?C.workstreams.filter(De=>!!(De&&typeof De=="object"&&typeof De.id=="string")):[];lt.current=Ze,St.current=ht}catch(R){Un("planning_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}},[s,t,n,o,l]),Hn=r.useCallback(async()=>{if(s==="local"&&ai(t)&&!(n&&(!o||!l)))try{const R=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.sessions)?C.sessions.map(oe=>({id:String(oe?.id||"").trim(),assetId:String(oe?.assetId||"").trim(),documentId:typeof oe?.documentId=="string"&&oe.documentId.trim().length>0?oe.documentId.trim():null,documentVersion:Number.isFinite(Number(oe?.documentVersion))?Math.max(1,Math.floor(Number(oe.documentVersion))):null,title:typeof oe?.title=="string"&&oe.title.trim().length>0?oe.title.trim():null,status:oe?.status==="resolved"?"resolved":"open",comments:Array.isArray(oe?.comments)?oe.comments:[],createdByActorId:typeof oe?.createdByActorId=="string"&&oe.createdByActorId.trim().length>0?oe.createdByActorId.trim():null,updatedByActorId:typeof oe?.updatedByActorId=="string"&&oe.updatedByActorId.trim().length>0?oe.updatedByActorId.trim():null,createdAt:String(oe?.createdAt||"").trim(),updatedAt:String(oe?.updatedAt||oe?.createdAt||"").trim(),deletedAt:typeof oe?.deletedAt=="string"&&oe.deletedAt.trim().length>0?oe.deletedAt.trim():null})).filter(oe=>oe.id.length>0&&oe.assetId.length>0):[],ht=Array.isArray(C?.comments)?C.comments.map(oe=>({id:String(oe?.id||"").trim(),sessionId:String(oe?.sessionId||"").trim(),body:typeof oe?.body=="string"?oe.body:"",anchor:oe?.anchor??null,order:Number.isFinite(Number(oe?.order))?Math.max(0,Math.floor(Number(oe.order))):0,authorActorId:typeof oe?.authorActorId=="string"&&oe.authorActorId.trim().length>0?oe.authorActorId.trim():null,createdAt:String(oe?.createdAt||"").trim(),updatedAt:String(oe?.updatedAt||oe?.createdAt||"").trim(),deletedAt:typeof oe?.deletedAt=="string"&&oe.deletedAt.trim().length>0?oe.deletedAt.trim():null})).filter(oe=>oe.id.length>0&&oe.sessionId.length>0):Aw(Ze),De=typeof C?.fingerprint=="string"?C.fingerprint:JSON.stringify([...Ze.map(oe=>`${oe.id}:${oe.updatedAt}:${oe.status}:${oe.deletedAt||""}:${oe.comments.length}`).sort(),...ht.map(oe=>`${oe.id}:${oe.sessionId}:${oe.updatedAt}:${oe.deletedAt||""}`).sort()]);if(De===it.current)return;it.current=De,Lt.current=Ze,vt.current=ht,Ot(Ze),Oe(De)}catch(R){Un("document_review_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}finally{ba("documentReviewSessions")}},[s,t,n,o,l,ba]),Ln=r.useCallback(async()=>{if(s==="local"&&ai(t)&&!(n&&(!o||!l)))try{const R=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!R.ok)return;const C=await R.json().catch(()=>({})),Ze=Array.isArray(C?.sessions)?C.sessions.map(De=>({id:String(De?.id||"").trim(),workspaceId:String(De?.workspaceId||"").trim(),taskId:String(De?.taskId||"").trim(),baseImageAssetId:String(De?.baseImageAssetId||"").trim(),title:typeof De?.title=="string"&&De.title.trim().length>0?De.title.trim():null,globalInstruction:typeof De?.globalInstruction=="string"&&De.globalInstruction.trim().length>0?De.globalInstruction.trim():null,annotations:Array.isArray(De?.annotations)?De.annotations:[],createdByActorId:typeof De?.createdByActorId=="string"&&De.createdByActorId.trim().length>0?De.createdByActorId.trim():null,updatedByActorId:typeof De?.updatedByActorId=="string"&&De.updatedByActorId.trim().length>0?De.updatedByActorId.trim():null,createdAt:String(De?.createdAt||"").trim(),updatedAt:String(De?.updatedAt||De?.createdAt||"").trim(),deletedAt:typeof De?.deletedAt=="string"&&De.deletedAt.trim().length>0?De.deletedAt.trim():null})).filter(De=>De.id.length>0&&De.workspaceId.length>0&&De.taskId.length>0&&De.baseImageAssetId.length>0):[],ht=typeof C?.fingerprint=="string"?C.fingerprint:JSON.stringify(Ze.map(De=>`${De.id}:${De.updatedAt}:${De.taskId}:${De.baseImageAssetId}:${De.annotations.length}:${De.deletedAt||""}`).sort());if(ht===xe.current)return;xe.current=ht,Ie.current=Ze,c(Ze),ye(ht)}catch(R){Un("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(R?.message||R||"")})}finally{ba("annotatedAttachmentSessions")}},[s,t,n,o,l,ba]),rr=r.useCallback(()=>{la.current=new Set([...nt.current,...gt.current].map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),bn.current=new Map([...nt.current,...gt.current].map(C=>[String(C?.id||"").trim(),ys.getWatermark(C)]).filter(([C])=>C.length>0)),fn.current=new Map([...nt.current.map(C=>[String(C?.id||"").trim(),ys.getChangeKey({...C,isArchived:!1})]),...gt.current.map(C=>[String(C?.id||"").trim(),ys.getChangeKey({...C,isArchived:!0})])].filter(([C])=>C.length>0)),_n.current=new Set(lt.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),Oa.current=new Map(lt.current.map(C=>[String(C?.id||"").trim(),String(C?.updatedAt||C?.createdAt||"").trim()]).filter(([C])=>C.length>0)),Mn.current=new Set(St.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),ya.current=new Map(St.current.map(C=>[String(C?.id||"").trim(),String(C?.updatedAt||C?.createdAt||"").trim()]).filter(([C])=>C.length>0)),$a.current=new Set(et.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),Cn.current=new Map(et.current.map(C=>[String(C?.id||"").trim(),fd.getWatermark(C)]).filter(([C])=>C.length>0)),da.current=new Map(et.current.map(C=>[String(C?.id||"").trim(),fd.getChangeKey(C)]).filter(([C])=>C.length>0)),En.current=new Set(Ke.current.map(C=>String(C?.path||"").trim()).filter(C=>C.length>0)),Xt.current=new Map(Ke.current.map(C=>[String(C?.path||"").trim(),String(C?.updatedAt||"").trim()]).filter(([C])=>C.length>0)),Ua.current=new Set(ae.current.map(C=>String(C?.path||"").trim()).filter(C=>C.length>0)),_a.current=new Map(ae.current.map(C=>[String(C?.path||"").trim(),String(C?.updatedAt||"").trim()]).filter(([C])=>C.length>0)),er.current=new Set(Lt.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),tr.current=new Map(Lt.current.map(C=>[String(C?.id||"").trim(),String(C?.updatedAt||C?.createdAt||"").trim()]).filter(([C])=>C.length>0)),Pa.current=new Set(vt.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),na.current=new Map(vt.current.map(C=>[String(C?.id||"").trim(),String(C?.updatedAt||C?.createdAt||"").trim()]).filter(([C])=>C.length>0)),pa.current=new Set(Ie.current.map(C=>String(C?.id||"").trim()).filter(C=>C.length>0)),hn.current=new Map(Ie.current.map(C=>[String(C?.id||"").trim(),String(C?.updatedAt||C?.createdAt||"").trim()]).filter(([C])=>C.length>0)),an.current=new Map(Nu(nt.current,gt.current,lt.current,St.current).map(C=>[String(C?.id||"").trim(),String(C?.createdAt||"").trim()]).filter(([C])=>C.length>0));const R=es();Ht.current=R?null:"storage-write-failed"},[es]),Cs=r.useCallback(async()=>{const[R,C]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"})]);if(R.ok){const Ze=await R.json().catch(()=>({})),ht=Array.isArray(Ze?.tasks)?Ze.tasks.map(De=>Po(De)):[];ve(ht)}if(C.ok){const Ze=await C.json().catch(()=>({})),ht=Array.isArray(Ze?.archived)?Ze.archived.map(De=>({...Po(De),isArchived:!0})):[];re(ht)}await ge().catch(()=>{Un("refresh_planning_entities_failed",{workspaceId:t})})},[t,ge,re,ve]),{handleSyncAuthFailure:Ir,ensureWorkspaceSyncReady:Ur}=r.useMemo(()=>xw({currentWorkspaceId:t,workspaceSyncPhase:P,clearWorkspaceRetry:ma,setWorkspaceSyncBusy:ee,setUserGlobalSyncStatus:je,setUserGlobalSyncError:R=>ce(R),setWorkspaceLastErrorMessage:R=>j(R),setWorkspaceLastErrorAt:R=>T(R),reportSyncEvent:cn,setAuthBlocked:x,setIsAuthenticated:K,checkAuthSession:ue,ensureCloudWorkspaceReadyForSync:Je,scheduleWorkspaceSyncRetry:$r,persistWorkspaceSyncPatchSafely:nr}),[t,P,ma,cn,x,K,ue,Je,$r,nr]),Fs=r.useMemo(()=>Uw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,currentWorkspaceId:t,workspaceSyncPhase:P,isAuthenticated:l,checkAuthSession:ue,resolveCloudAuthUrl:m,ensureCloudWorkspaceReadyForSync:Je,ensureWorkspaceSyncReady:Ur,handleSyncAuthFailure:Ir,clearWorkspaceRetry:ma,clearWorkspaceIssue:yr,isWorkspaceRetryPending:Ia,scheduleWorkspaceSyncRetry:$r,persistWorkspaceSyncPatchSafely:nr,persistWorkspaceSyncPatchBestEffort:Dn,persistWorkspaceSyncWatermarksSnapshotBestEffort:es,reportSyncEvent:cn,acquireWorkspaceSyncLease:tn,releaseWorkspaceSyncLease:Aa,reportWorkspaceWindowContention:xn,refreshWorkspaceSyncMarkdownDocumentsSnapshot:Ya,refreshWorkspaceSyncAiProfilesSnapshot:Wa,refreshWorkspaceSyncAssetsSnapshot:Rt,refreshWorkspaceSyncPlanningEntitiesSnapshot:kr,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:Hn,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:Ln,refreshLocalWorkspaceTaskCollections:Cs,buildWorkspaceSyncPayload:oa,buildWorkspaceSyncSignature:rn,seedWorkspaceSnapshotPushBaseline:rr,shouldSuppressAttachBootstrapPush:ts,recordSuppressedEventIds:(...R)=>G.current.recordSuppressedEventIds(...R),workspaceRepairModeRef:za,workspaceForceFullAiProfilePushRef:Ut,workspacePushInFlightRef:en,workspacePullInFlightRef:Ca,workspacePendingPushReplayRef:Na,workspaceLastPushedSignatureRef:Jt,workspacePendingSignatureRef:Ta,workspaceLastPushedTaskIdsRef:la,workspaceDeletedTaskIdsRef:vn,workspaceDeletedTaskWatermarksRef:pn,workspacePullCursorRef:Xn,workspaceLastPushedWatermarksRef:bn,workspaceLastPushedTaskChangeKeysRef:fn,workspaceLastPushedInitiativeIdsRef:_n,workspaceLastPushedInitiativeWatermarksRef:Oa,workspaceLastPushedWorkstreamIdsRef:Mn,workspaceLastPushedWorkstreamWatermarksRef:ya,workspaceLastPushedAiProfileIdsRef:$a,workspaceLastPushedAiProfileWatermarksRef:Cn,workspaceLastPushedAiProfileChangeKeysRef:da,workspaceLastPushedDocumentPathsRef:En,workspaceLastPushedDocumentWatermarksRef:Xt,workspaceLastPushedAssetPathsRef:Ua,workspaceLastPushedAssetWatermarksRef:_a,workspaceLastPushedDocumentReviewSessionIdsRef:er,workspaceLastPushedDocumentReviewSessionWatermarksRef:tr,workspaceLastPushedDocumentReviewCommentIdsRef:Pa,workspaceLastPushedDocumentReviewCommentWatermarksRef:na,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:pa,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:hn,workspaceLastPushedTaskEventWatermarksRef:an,workspaceBaselineResetReasonRef:Ht,workspaceCaptureAttachBootstrapBaselineRef:Xr,workspaceStartupFullReconcileRanRef:Ss,workspaceFullReconcileInFlightRef:Ma,bootstrapLastProgressAtRef:aa,realtimeSuppressedEventQueueRef:ga,setWorkspaceSyncBusy:ee,setUserGlobalSyncStatus:je,setUserGlobalSyncError:ce,setWorkspaceLastErrorMessage:j,setWorkspaceLastErrorAt:T,setWorkspaceLastPullAt:Pe,setWorkspaceLastPushAt:Ee,setWorkspaceSyncPendingChanges:q,setTasks:ve,setArchivedTasks:re}),[n,s,D,t,P,$,l,ue,m,Je,Ur,Ir,ma,yr,$r,nr,Dn,es,cn,tn,Aa,xn,Ya,Wa,Rt,kr,Hn,Ln,Cs,oa,rn,rr,ts,ve,re]),{pushWorkspaceChangesToCloud:Bn,pullWorkspaceChangesFromCloud:Wn}=Fs,G=r.useRef({handleRealtimeSignal:()=>{},recordSuppressedEventIds:()=>{},clearRealtimePullDebounce:()=>{}}),qe=r.useMemo(()=>Bw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,workspaceSyncPhase:P,workspacePullInFlightRef:Ca,realtimePullDebounceRef:tt,realtimeSuppressedEventIdsRef:Gt,clearWorkspaceRetry:ma,isWorkspaceRetryPending:Ia,pullWorkspaceChangesFromCloud:Wn}),[n,s,D,P,ma,Ia,Wn]);G.current=qe;const At=y("/taskforce-ws"),Nt=String(i||"").trim(),In=Yg({enabled:!!(k&&n&&s==="local"&&D&&o&&l&&Nt&&Nt!=="anonymous"&&At),workspaceId:t,websocketUrl:At,onSignal:qe.handleRealtimeSignal,onTelemetry:Et,userId:Nt||void 0});r.useEffect(()=>{Vt(In.connectionState)},[In.connectionState]),r.useEffect(()=>()=>qe.clearRealtimePullDebounce(),[qe]);const Tn=r.useCallback(async R=>Pn(R,{cloudAuthConfigured:n,isAuthenticated:l,ensureCloudWorkspaceReadyForSync:Je}),[Pn,n,l,Je]),Mo=r.useCallback(async()=>{await yn({preferCloudOnFirstSync:!1})},[yn]),Eo=r.useMemo(()=>Fw({currentWorkspaceId:t,workspaceCloudSyncEnabled:D,workspaceSyncPhase:P,workspaceLastPullAt:Re,lastBootstrapPhaseRef:Za,workspaceRepairModeRef:za,workspaceForceFullAiProfilePushRef:Ut,workspaceStartupRepairRanRef:ea,workspaceStartupFullReconcileRanRef:Ss,workspaceFullReconcileInFlightRef:Ma,workspacePullCursorRef:Xn,workspaceAttachBootstrapBaselineSignatureRef:ar,workspaceCaptureAttachBootstrapBaselineRef:Xr,workspacePendingSignatureRef:Ta,workspaceLastPushedSignatureRef:Jt,workspaceLastPushedWatermarksRef:bn,workspaceLastPushedTaskChangeKeysRef:fn,workspaceLastPushedInitiativeIdsRef:_n,workspaceLastPushedInitiativeWatermarksRef:Oa,workspaceLastPushedWorkstreamIdsRef:Mn,workspaceLastPushedWorkstreamWatermarksRef:ya,workspaceLastPushedAiProfileIdsRef:$a,workspaceLastPushedAiProfileWatermarksRef:Cn,workspaceLastPushedAiProfileChangeKeysRef:da,workspaceLastPushedDocumentPathsRef:En,workspaceLastPushedDocumentWatermarksRef:Xt,workspaceLastPushedAssetPathsRef:Ua,workspaceLastPushedAssetWatermarksRef:_a,workspaceLastPushedDocumentReviewSessionIdsRef:er,workspaceLastPushedDocumentReviewSessionWatermarksRef:tr,workspaceLastPushedDocumentReviewCommentIdsRef:Pa,workspaceLastPushedDocumentReviewCommentWatermarksRef:na,workspaceLastPushedAnnotatedAttachmentSessionIdsRef:pa,workspaceLastPushedAnnotatedAttachmentSessionWatermarksRef:hn,workspaceLastPushedTaskEventWatermarksRef:an,workspaceBaselineResetReasonRef:Ht,bootstrapPhaseStartedAtRef:Dt,bootstrapLastProgressAtRef:aa,acquireWorkspaceSyncLease:tn,releaseWorkspaceSyncLease:Aa,forceClearWorkspaceSyncLease:Wr,clearWorkspaceRetry:ma,clearWorkspaceIssue:yr,reportWorkspaceWindowContention:xn,reportSyncEvent:cn,persistWorkspaceSyncPatch:Br,persistWorkspaceSyncWatermarksSnapshotBestEffort:es,buildWorkspaceSyncSignature:rn,pullWorkspaceChangesFromCloud:Wn,pushWorkspaceChangesToCloud:Bn,cloudAuthConfigured:n,runtimeMode:s,isAuthenticated:l,checkAuthSession:ue}),[t,$,D,P,Re,tn,Aa,Wr,ma,yr,xn,cn,Br,es,rn,Wn,Bn,n,s,l,ue]),{retryWorkspaceCloudSync:ao,resetWorkspaceSyncCursorAndPull:Ga}=Eo,vr=r.useCallback(()=>{const R=$p({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,currentWorkspaceId:t,workspaceSyncPhase:P,isAuthenticated:l,repairModeActive:za.current===!0,repairModeBypass:!1,pushInFlight:en.current,pullInFlight:Ca.current}),C=Ia(),Ze=Up({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,currentWorkspaceId:t,workspaceSyncPhase:P,isAuthenticated:l,repairModeActive:za.current===!0,repairModeBypass:!1,retryPending:C,pushInFlight:en.current,pullInFlight:Ca.current}),ht=zp({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,currentWorkspaceId:t,isAuthenticated:l});return{workspaceId:t,enabled:D,phase:P,status:Ar,summary:Ra,lastSuccessfulSyncAt:An,lastPullAt:Re,lastPushAt:Ce,lastErrorAt:U,pendingChanges:Q,lastErrorMessage:b,recommendedAction:ws,pushBlockedReason:R.allowed?null:R.reason,pullBlockedReason:Ze.allowed?null:Ze.reason,retryBlockedReason:ht.allowed?null:ht.reason,repairActive:za.current===!0,pushInFlight:en.current===!0,pullInFlight:Ca.current===!0,retryPending:C,documentSnapshotCount:Se.length,aiProfileSnapshotCount:dt.length,aiProfileSnapshotRawCount:It,aiProfileSnapshotLastFetchAt:st,aiProfileSnapshotLastFetchError:Pt,aiProfileSnapshotLastSkipReason:Mt,assetSnapshotCount:Ue.length,documentReviewSessionSnapshotCount:bt.length,documentReviewSessionSnapshotFingerprint:Bt,annotatedAttachmentSessionSnapshotCount:E.length,annotatedAttachmentSessionSnapshotFingerprint:Y,lastPushedAiProfileCount:$a.current.size,lastPushedAiProfileWatermarkCount:Cn.current.size,forceFullAiProfilePushQueued:Ut.current===!0}},[n,t,s,D,P,l,Ar,Ra,An,Re,Ce,U,Q,b,ws,Se.length,dt.length,It,st,Pt,Mt,Ue.length,bt.length,Bt,E.length,Y,Ia]);r.useEffect(()=>{ua.current=ao},[ao]);const Da=r.useCallback(()=>{Ya(),Rt()},[Ya,Rt]);return r.useEffect(()=>{if(!n||s!=="local"||!D||!o||!l)return;Ya(),Wa(),Rt(),Hn(),Ln();const R=as=>{const sn=as.detail;(String(sn?.workspaceId||"").trim()||"default")===t&&Da()},C=as=>{const sn=as.detail;(String(sn?.workspaceId||"").trim()||"default")===t&&(Wa(),Rt())};window.addEventListener(Fp,R),window.addEventListener(Op,C);const Ze=window.setInterval(()=>{Ya()},gn),ht=window.setInterval(()=>{Wa()},gn),De=window.setInterval(()=>{Rt()},gn),oe=window.setInterval(()=>{Hn()},gn),sr=window.setInterval(()=>{Ln()},gn);return()=>{window.removeEventListener(Fp,R),window.removeEventListener(Op,C),window.clearInterval(Ze),window.clearInterval(ht),window.clearInterval(De),window.clearInterval(oe),window.clearInterval(sr)}},[n,s,D,o,l,t,Da,Ya,Wa,Rt,Hn,Ln,gn]),r.useEffect(()=>{!n||s!=="local"||!D||!o||!l||_s&&Da()},[n,s,D,o,l,_s,Da]),r.useEffect(()=>{if(!Pw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,authSessionResolved:o,workspaceSyncPhase:P,workspaceSyncReferenceSnapshotsReady:Qt}))return;const R=rn();if(ts(R)||!R||R===Jt.current)return;const C=oa();if(q(C.changes.length),en.current||Ca.current){Ta.current=R;return}const Ze=window.setTimeout(()=>{Bn(R)},1500);return()=>window.clearTimeout(Ze)},[n,s,D,o,P,Qt,rn,ts,oa,bs,ct,Te,yt,Bt,Y,Bn,en,Ca]),r.useEffect(()=>{if(!Mw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,authSessionResolved:o,workspaceSyncPhase:P,workspaceSyncReferenceSnapshotsReady:Qt}))return;const R=window.setInterval(()=>{if(en.current||Ca.current||Ia())return;const C=Ta.current||rn();if(!C||C===Jt.current)return;const Ze=oa();q(Ze.changes.length),Ze.changes.length!==0&&Bn(C)},Fr);return()=>window.clearInterval(R)},[n,s,D,o,P,Qt,rn,oa,Bn,Ia,Fr]),r.useEffect(()=>{n&&s==="local"&&D||(ma(),ee(!1))},[n,s,D,ma]),r.useEffect(()=>{const R=Ew({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,authSessionResolved:o,workspaceSyncPhase:P,lastPullAt:Re,retryPending:Ia()});if(!R.shouldStart)return;R.shouldKickOffImmediately&&Wn();const C=window.setInterval(()=>{Wn()},zn);return()=>{window.clearInterval(C)}},[n,s,D,o,P,Re,Ia,Wn,zn]),r.useEffect(()=>{if(!Dw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,authSessionResolved:o,isAuthenticated:l,workspaceSyncPhase:P}))return;const R=window.setInterval(()=>{Ma.current||(Ma.current=!0,Wn({forceCursorNull:!0}).finally(()=>{Ma.current=!1}))},Sw);return()=>window.clearInterval(R)},[n,s,D,o,l,P,Wn]),r.useEffect(()=>{s!=="local"||!l||!i||i==="anonymous"||yn({preferCloudOnFirstSync:!0})},[s,l,i,yn]),r.useEffect(()=>{if(s!=="local"||!l||!i||i==="anonymous"||!Ka.current.has(i)||Kt.current)return;const R=gr(),C=JSON.stringify(R);if(!Fa.current){Fa.current=C;return}if(C===Fa.current)return;Fa.current=C,xr(i,new Date().toISOString());const Ze=window.setTimeout(()=>{yn({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(Ze)},[s,l,i,gr,xr,yn]),r.useEffect(()=>{Lw({cloudAuthConfigured:n,runtimeMode:s,workspaceCloudSyncEnabled:D,authSessionResolved:o,isAuthenticated:l,workspaceSyncPhase:P,alreadyRan:ea.current})&&(ea.current=!0,fetch("/api/taskforce/sync/workspace/repair-startup",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t})}).then(async R=>{if(!R.ok)return;const C=await R.json().catch(()=>({}));C?.applied>0&&(Un("startup_repair_applied",{workspaceId:t,applied:C.applied,skipped:C.skipped,failed:C.failed}),Ya(),Wa(),Rt(),Hn())}).catch(()=>{}))},[n,s,D,o,l,P,t,Ya,Wa,Rt,Hn]),{userGlobalSyncStatus:_e,setUserGlobalSyncStatus:je,userGlobalSyncError:se,setUserGlobalSyncError:ce,workspaceLastPullAt:Re,workspaceLastPushAt:Ce,workspaceLastErrorAt:U,workspaceLastErrorMessage:b,workspaceLastSuccessfulSyncAt:An,workspaceCloudSyncEnabled:D,workspaceSyncPhase:P,workspaceSyncSetupIntent:be,workspaceSyncStatus:Ar,workspaceSyncSummary:Ra,workspaceSyncRecommendedAction:ws,workspaceSyncBusy:ie,workspaceSyncPendingChanges:Q,syncInFlightRef:jt,workspaceRetryAt:Lr,isWorkspaceRetryPending:Ia,workspacePushInFlightRef:en,workspacePullInFlightRef:Ca,workspaceLastPushedSignatureRef:Jt,workspacePendingSignatureRef:Ta,workspaceLastPushedTaskIdsRef:la,workspaceDeletedTaskIdsRef:vn,workspaceDeletedTaskWatermarksRef:pn,workspacePullCursorRef:Xn,clearWorkspaceRetry:ma,persistWorkspaceSyncPatch:Br,loadWorkspaceSyncState:Cr,applyWorkspaceSyncStateSnapshot:_t,syncUserGlobalSettings:yn,buildWorkspaceSyncSignature:rn,pushWorkspaceChangesToCloud:Bn,pullWorkspaceChangesFromCloud:Wn,saveWorkspaceCloudSyncSettings:Tn,retryUserGlobalSettingsSync:Mo,retryWorkspaceCloudSync:ao,resetWorkspaceSyncCursorAndPull:Ga,getWorkspaceSyncDiagnostics:vr}}function Hw(e,t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e==="error"?3600:2600}function Gw(){const[e,t]=r.useState(null),n=r.useRef(null),s=r.useCallback(()=>{n.current!==null&&(window.clearTimeout(n.current),n.current=null),t(null)},[]),o=r.useCallback((l,i="info",d)=>{if(!l)return;n.current!==null&&(window.clearTimeout(n.current),n.current=null),t({message:l,tone:i,ttlMs:d});const m=Hw(i,d);n.current=window.setTimeout(()=>{n.current=null,t(null)},m)},[]);return r.useEffect(()=>()=>{n.current!==null&&(window.clearTimeout(n.current),n.current=null)},[]),{uiNotice:e,pushNotice:o,clearNotice:s}}function Vw({storagePath:e,shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:n}){const[s,o]=r.useState("antigravity"),[l,i]=r.useState([]),[d,m]=r.useState(".agent/workflows"),[y,k]=r.useState(null),[S,h]=r.useState(null),g=r.useRef(null),v=t||n;r.useEffect(()=>{const B=l.find(V=>V.id===s);B&&m(B.directory)},[s,l]);const A=r.useCallback(()=>{typeof window>"u"||(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null,h(null)},5e3))},[]),_=r.useCallback(async()=>{if(v)return;const B=await fetch("/api/taskforce/environments");if(!B.ok)return;const V=await B.json().catch(()=>({}));V.environments&&i(V.environments)},[v]),I=r.useCallback(async(B,V)=>{k("workflows"),h(null);try{const J=await(await fetch("/api/taskforce/export-resources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"workflows",environment:B,workflowNames:V,variables:{STORAGE_PATH:e.replace(/\/$/,"")||".Taskforce"}})})).json();J.success?h({type:"success",message:`Successfully exported ${J.count} workflows to ${B}`}):h({type:"error",message:J.error||"Export failed"})}catch{h({type:"error",message:"Network error exporting workflows"})}finally{k(null),A()}},[A,e]);return r.useEffect(()=>()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),{exportEnvironment:s,setExportEnvironment:o,availableEnvironments:l,loadAvailableEnvironments:_,exportWorkflowsPath:d,setExportWorkflowsPath:m,exportingResource:y,exportResult:S,handleExportWorkflows:I}}function qw(e){const{resolveCloudAuthUrl:t,currentWorkspaceId:n,normalizedCloudAuthBaseUrl:s,normalizedCloudMcpBaseUrl:o,mergedConfig:l,availableWorkspaces:i,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:A,supportedLocales:_,jsonBackupUseGlobalDefault:I,manualComplexityEnabled:B,checklistDropdownEnabled:V,showTaskCardStatusLabel:L,exportWorkflowsPath:J,exportingResource:me,exportResult:ve,pathSaved:re,settingsSection:x,exportEnvironment:K,setupState:ue,buildInfo:pe,saveSetupMode:X,saveWorkspaceProfile:M,setCurrentTheme:O,handleSaveTheme:de,handleSaveGlobalTheme:ge,setKeyShortcut:$,handleJsonBackupEnabledChange:_e,handleSaveGlobalJsonBackupEnabled:je,handleSaveGlobalWeekStartsOn:se,handleSaveLocale:ce,handleManualComplexityEnabledChange:Re,handleChecklistDropdownEnabledChange:Pe,handleShowTaskCardStatusLabelChange:Ce,handleResetProjectToGlobal:Ee,handleSaveSettings:U,setExportWorkflowsPath:T,setExportEnvironment:b,availableWorkflows:j,initiativeTemplates:D,availableEnvironments:te,fetchWorkflows:P,fetchInitiativeTemplates:H,createInitiativeFromTemplate:be,fetchWorkflowTemplate:z,fetchWorkflowOverrideNames:ie,saveWorkflowTemplateDraft:ee,resetWorkflowTemplateDraft:Q,handleExportWorkflows:q,setShowFolderBrowser:Se,setBrowserTarget:we,fetchFolders:Te,activeCategories:Me,pathValidation:nt,taxonomyDisplayLabels:gt,handleUpdateCategory:lt,handleRemoveCategory:St,handleSaveCategory:Ke,handleAddPath:Ct,handleRemovePath:dt,handleUpdateCategoryIcon:Xe,handleUpdateCategoryColor:ct,activeTypes:ne,handleSaveType:st,handleRemoveType:Ye,handleUpdateType:Pt,taxonomies:kt,handleUpdateTaxonomies:It,priorities:Ft,handleUpdatePriorities:Mt,analyzeSystemTaxonomyPack:Be,handleApplySystemTaxonomyPack:et,handleUpdateTaxonomyDisplayLabels:Ue,projectRoot:Qe,projectName:yt,mcpHostRoot:ot,serverHostRoot:ae,mcpScriptPath:ze,tenantId:bt,runtimeMode:Ot,workspaceSwitchingEnabled:Bt,deleteWorkspace:Oe,setMcpHostRoot:Lt,isAuthenticated:vt}=e,E=r.useCallback(async(Y,ye)=>{const Ie=t(Y),He=new Headers(ye?.headers||void 0);if(Y.startsWith("/api/taskforce/settings/mcp/")){const Ne=String(n||"").trim();Ne&&Ne!=="default"&&!He.has("x-taskforce-workspace-id")&&He.set("x-taskforce-workspace-id",Ne)}const Ve={...ye,headers:He,credentials:ye?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(Ie))try{new URL(Ie,window.location.origin).origin!==window.location.origin&&Ve.mode===void 0&&(Ve.mode="cors")}catch{}return fetch(Ie,Ve)},[n,t]),c=i.find(Y=>Y.id===n);return{fetchCloudAuthApi:E,currentTheme:d,configLoaded:m,globalTheme:y,themeUseGlobalDefault:k,keyShortcut:S,jsonBackupEnabled:h,globalJsonBackupEnabled:g,globalWeekStartsOn:v,locale:A,supportedLocales:_,jsonBackupUseGlobalDefault:I,manualComplexityEnabled:B,checklistDropdownEnabled:V,showTaskCardStatusLabel:L,exportWorkflowsPath:J,exportingResource:me,exportResult:ve,pathSaved:re,initialSection:x,exportEnvironment:K,setupState:ue,buildInfo:pe,onSaveSetupMode:X,onSaveWorkspaceProfile:M,onThemeChange:O,onSaveTheme:de,onSaveGlobalTheme:ge,onKeyShortcutChange:$,onJsonBackupEnabledChange:_e,onSaveGlobalJsonBackupEnabled:je,onSaveGlobalWeekStartsOn:se,onSaveLocale:ce,onManualComplexityEnabledChange:Re,onChecklistDropdownEnabledChange:Pe,onShowTaskCardStatusLabelChange:Ce,onResetProjectToGlobal:Ee,onSaveSettings:U,onExportWorkflowsPathChange:T,onExportEnvironmentChange:b,availableWorkflows:j,initiativeTemplates:D,availableEnvironments:te,onRefreshWorkflows:P,onRefreshInitiativeTemplates:H,onCreateInitiativeFromTemplate:be,onFetchWorkflowTemplate:z,onFetchWorkflowOverrideNames:ie,onSaveWorkflowTemplateDraft:ee,onResetWorkflowTemplateDraft:Q,onExportWorkflows:q,onShowFolderBrowserChange:Se,onBrowserTargetChange:we,onFetchFolders:Te,categories:Me,pathValidation:nt,taxonomyDisplayLabels:gt,onUpdateCategory:lt,onRemoveCategory:St,onSaveCategory:Ke,onAddPath:Ct,onRemovePath:dt,onUpdateCategoryIcon:Xe,onUpdateCategoryColor:ct,types:ne,onSaveType:st,onRemoveType:Ye,onUpdateType:Pt,taxonomies:kt,onUpdateTaxonomies:It,priorities:Ft,onUpdatePriorities:Mt,onAnalyzeSystemTaxonomyPack:Be,onApplySystemTaxonomyPack:et,onUpdateTaxonomyDisplayLabels:Ue,projectRoot:Qe,projectName:yt,mcpHostRoot:ot,serverHostRoot:ae,mcpScriptPath:ze,tenantId:bt,workspaceId:n,runtimeMode:Ot,cloudAuthBaseUrl:s||l.cloudAuthBaseUrl,cloudMcpBaseUrl:o||void 0,workspaceSwitchingEnabled:Bt,currentWorkspaceRole:c?.role||"member",currentWorkspaceName:String(c?.name||""),onDeleteWorkspace:Oe,onMcpHostRootChange:Lt,isAuthenticated:vt}}function Kw(e){const{keyShortcut:t,themeUseGlobalDefault:n,runtimeMode:s,jsonBackupUseGlobalDefault:o,globalTheme:l,globalJsonBackupEnabled:i,setCurrentTheme:d,setThemeUseGlobalDefault:m,setGlobalTheme:y,setJsonBackupEnabled:k,setJsonBackupUseGlobalDefault:S,setGlobalJsonBackupEnabled:h,setGlobalWeekStartsOn:g,setLocale:v,setManualComplexityEnabled:A,setChecklistDropdownEnabled:_,setShowTaskCardStatusLabel:I,setShowChecklist:B}=e,V=r.useCallback(async()=>{try{const M=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:t})});if(!M.ok)throw new Error(`Failed to save global settings (${M.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[t]),L=r.useCallback(async M=>{d(M),m(!1);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[d,m]),J=r.useCallback(async M=>{y(M),n&&d(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:M})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[y,n,d]),me=r.useCallback(async M=>{if(s==="cloud")return k(!1),S(!1),!1;k(M),S(!1);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[s,k,S]),ve=r.useCallback(async M=>{if(s==="cloud")return h(!1),o&&k(!1),!1;h(M),o&&k(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:M})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[s,h,o,k]),re=r.useCallback(async M=>{g(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:M}})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[g]),x=r.useCallback(async M=>{const O=Dg(M);return v(O),!0},[v]),K=r.useCallback(async M=>{A(M);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[A]),ue=r.useCallback(async M=>{_(M),M||B(!1);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[_,B]),pe=r.useCallback(async M=>{I(M);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save task card status label setting"),!1}},[I]),X=r.useCallback(async()=>{m(!0),S(!0),d(l),k(i),A(!1),_(!0),I(!0),B(!1);try{const M=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:null,jsonBackupEnabled:null,manualComplexityEnabled:null,checklistDropdownEnabled:null,showTaskCardStatusLabel:null})});if(!M.ok)throw new Error(`Failed to save config (${M.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[m,S,d,l,k,i,A,_,I,B]);return{handleSaveSettings:V,handleSaveTheme:L,handleSaveGlobalTheme:J,handleJsonBackupEnabledChange:me,handleSaveGlobalJsonBackupEnabled:ve,handleSaveGlobalWeekStartsOn:re,handleSaveLocale:x,handleManualComplexityEnabledChange:K,handleChecklistDropdownEnabledChange:ue,handleShowTaskCardStatusLabelChange:pe,handleResetProjectToGlobal:X}}function Zw(e){const{activeCategories:t,activeTab:n,activeTypes:s,archivedTasks:o,browserTarget:l,category:i,configLoaded:d,customCategories:m,refreshTaskCollections:y,fetchTasks:k,filterCategories:S,getCategoryPaths:h,normalizePath:g,pathValidation:v,setBrowserTarget:A,setCategory:_,setCustomCategories:I,setCustomTypes:B,setFilterCategories:V,setPathValidation:L,setPriorities:J,setShowFolderBrowser:me,setTaxonomies:ve,tasks:re}=e,x=r.useCallback(async(T,b)=>{const j=await T.json().catch(()=>({}));return String(j?.error||b)},[]),K=r.useCallback(()=>[...re,...o],[o,re]),ue=r.useCallback(T=>T.priorities.find(b=>b.value===2)?.value||T.priorities[0]?.value||2,[]),pe=r.useCallback(async T=>{if(T.length!==0)try{const b=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:T})});if(b.ok){const j=await b.json();L(D=>({...D,...j.results}))}}catch(b){console.error("[Taskforce] Failed to validate paths:",b)}},[L]);r.useEffect(()=>{if(n!=="settings"||!d)return;const T=[];t.forEach(j=>{h(j).forEach(te=>{T.includes(te)||T.push(te)})});const b=T.filter(j=>!v[j]);b.length>0&&pe(b)},[t,n,d,h,v,pe]);const X=r.useCallback(async(T,b)=>{if(d){I(j=>(j.length>0?j:t).map(te=>te.value===T.value?T:te)),b&&b!==T.label&&(i===b&&_(T.label),S.includes(b)&&V(j=>j.map(D=>D===b?T.label:D)));try{const te={categories:(m.length>0?m:t).map(P=>P.value===T.value?T:P)};b&&b!==T.label&&(te.reassignFrom=b,te.reassignTo=T.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)}),b&&await k()}catch(j){console.error("[Taskforce] Failed to update category",j)}}},[t,i,d,m,k,S,_,I,V]),M=r.useCallback(async T=>{if(!d)return;const b=T.trim().toLowerCase().replace(/\s+/g,"-");if(t.some(D=>D.value===b))return;const j={value:b,label:T.trim(),color:"blue-200",icon:"Folder"};I(D=>[...D.length>0?D:t,j]);try{const te=[...m.length>0?m:t,j];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:te})})}catch(D){console.error("[Taskforce] Failed to create category",D)}},[t,d,m,I]),O=r.useCallback((T,b)=>{if(!b.trim())return;const j=t.find(H=>H.value===T);if(!j)return;const D=h(j),te=b.trim();if(D.includes(te))return;const P=[...D,te];X({...j,path:void 0,paths:P}),pe(P)},[t,h,X,pe]),de=r.useCallback((T,b)=>{const j=t.find(D=>D.value===T);j&&X({...j,icon:b})},[t,X]),ge=r.useCallback((T,b)=>{const j=t.find(D=>D.value===T);j&&X({...j,color:b})},[t,X]),$=r.useCallback((T,b)=>{const j=t.find(P=>P.value===T);if(!j)return;const te=h(j).filter(P=>P!==b);X({...j,path:void 0,paths:te})},[t,h,X]),_e=r.useCallback(T=>{const b=g(T);if(l&&typeof l=="object"&&l.type==="category"){const j=t.find(D=>D.value===l.value);if(j){const D=h(j);if(!D.includes(b)){const te=[...D,b];X({...j,path:void 0,paths:te})}}}me(!1),A(null)},[t,l,h,X,g,A,me]),je=r.useCallback(async T=>{if(!d)return;const b=Yc,j=t.find(H=>H.value===b),D=j?{...j}:{value:b,label:ym,icon:"Inbox"},te=D.label,P=t.find(H=>H.value===T);I(H=>{let z=(H.length>0?H:t).filter(ie=>ie.value!==T);return z.some(ie=>ie.value===b)||(z=[D,...z]),z}),P&&((i===P.label||i===P.value)&&_(b),(S.includes(P.label)||S.includes(P.value))&&V(H=>{const be=H.filter(z=>z!==P.label&&z!==P.value);return be.includes(b)?be:[...be,b]}));try{let H=(m.length>0?m:t).filter(be=>be.value!==T);H.some(be=>be.value===b)||(H=[D,...H]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:H,reassignFrom:P?.label||T,reassignTo:te})}),await k()}catch(H){console.error("[Taskforce] Failed to remove category",H)}},[t,i,d,m,k,S,_,I,V]),se=r.useCallback(async T=>{if(!T.trim())return;const b=T.trim().toLowerCase().replace(/\s+/g,"-");if(s.some(D=>D.value===b))return;const j=[...s,{value:b,label:T.trim(),status:"active"}];B(j);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:j})})}catch(D){console.error("Failed to save type",D)}},[s,B]),ce=r.useCallback(async T=>{const b=s.map(j=>j.value===T?{...j,status:"retired"}:j);B(b);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:b})}),await k()}catch(j){console.error("Failed to save type",j)}},[s,k,B]),Re=r.useCallback(async(T,b)=>{const j=s.find(H=>H.value===T);if(!j)return;const D=typeof b.label=="string"?b.label.trim():j.label;if(!D)return;const te=s.map(H=>H.value===T?{...H,...b,label:D}:H);if(JSON.stringify(te)!==JSON.stringify(s)){B(te);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:te})})}catch(H){console.error("Failed to update type",H)}}},[s,B]),Pe=r.useCallback(async T=>{if(d){ve(T);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:T})})}catch(b){console.error("[Taskforce] Failed to save taxonomies",b)}}},[d,ve]),Ce=r.useCallback(async T=>{if(d){J(T);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:T})})}catch(b){console.error("[Taskforce] Failed to save priorities",b)}}},[d,J]),Ee=r.useCallback(T=>{const b=K(),j=new Set(T.categories.map(z=>z.value)),D=new Set(T.types.map(z=>z.value)),te=new Set(T.priorities.map(z=>Number(z.value))),P=Array.from(new Set(b.map(z=>String(z.category||"").trim()).filter(z=>z.length>0&&!j.has(z)))).sort(),H=Array.from(new Set(b.map(z=>String(z.type||"").trim()).filter(z=>z.length>0&&!D.has(z)))).sort(),be=Array.from(new Set(b.map(z=>Number(z.priority)).filter(z=>Number.isFinite(z)&&z>0&&!te.has(z)))).sort((z,ie)=>z-ie);return{unmatchedCategoryValues:P,unmatchedTypeValues:H,incompatiblePriorityValues:be}},[K]),U=r.useCallback(async T=>{if(!d)return{success:!1,error:"Settings are still loading."};const{pack:b,sections:j,remapExistingValuesToDefault:D,workspaceIdOverride:te}=T,P=String(te||"").trim(),H=P.length>0,be=H?[]:K(),z=ee=>{if(!P)return ee;const Q=ee.includes("?")?"&":"?";return`${ee}${Q}workspaceId=${encodeURIComponent(P)}`},ie=()=>{const ee={"Content-Type":"application/json"};return P&&(ee["x-taskforce-workspace-id"]=P),ee};try{if(j.categories){const ee=new Set(b.categories.map(Se=>Se.value)),Q=D?[...b.categories]:[...b.categories,...t.filter(Se=>!ee.has(Se.value)).map(Se=>({...Se,disabled:!0}))];H||I(Q);const q=await fetch(z("/api/taskforce/categories"),{method:"POST",headers:ie(),body:JSON.stringify({categories:Q})});if(!q.ok)return{success:!1,error:await x(q,"Failed to apply category library pack.")}}if(j.types){const ee=new Set(b.types.map(we=>we.value)),Q=b.types.find(we=>we.value===Dr)?.value||b.types[0]?.value||Dr;if(D){const we=be.filter(Te=>Te.type&&!ee.has(String(Te.type))).map(Te=>({id:Te.id,type:Q}));if(we.length>0){const Te=await fetch(z("/api/taskforce/bulk-update-fields"),{method:"POST",headers:ie(),body:JSON.stringify({updates:we})});if(!Te.ok)return{success:!1,error:await x(Te,"Failed to remap task types to the pack default.")}}}const q=D?[...b.types]:[...b.types,...s.filter(we=>!ee.has(we.value)).map(we=>({...we,status:"retired"}))];H||B(q);const Se=await fetch(z("/api/taskforce/types"),{method:"POST",headers:ie(),body:JSON.stringify({types:q})});if(!Se.ok)return{success:!1,error:await x(Se,"Failed to apply task type library pack.")}}if(j.priorities){const ee=new Set(b.priorities.map(we=>we.value)),Q=Array.from(new Set(be.map(we=>Number(we.priority)).filter(we=>Number.isFinite(we)&&we>0&&!ee.has(we)))).sort((we,Te)=>we-Te);if(Q.length>0&&!D)return{success:!1,error:`This workspace still uses priority levels ${Q.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(Q.length>0){const we=ue(b),Te=be.filter(Me=>Q.includes(Number(Me.priority))).map(Me=>({id:Me.id,priority:we}));if(Te.length>0){const Me=await fetch(z("/api/taskforce/bulk-update-fields"),{method:"POST",headers:ie(),body:JSON.stringify({updates:Te})});if(!Me.ok)return{success:!1,error:await x(Me,"Failed to remap task priorities to the pack default.")}}}const q=b.priorities.map(we=>({...we,value:Number(we.value)}));H||J(q);const Se=await fetch(z("/api/taskforce/priorities"),{method:"POST",headers:ie(),body:JSON.stringify({priorities:q})});if(!Se.ok)return{success:!1,error:await x(Se,"Failed to apply priority library pack.")}}return H||await y({isSilent:!0}),{success:!0}}catch(ee){return console.error("[Taskforce] Failed to apply system taxonomy pack",ee),{success:!1,error:ee instanceof Error?ee.message:"Failed to apply system taxonomy pack."}}},[t,s,d,K,ue,x,y,I,B,J]);return{getCategoryPaths:h,validatePaths:pe,handleUpdateCategory:X,handleSaveCategory:M,handleAddPath:O,handleUpdateCategoryIcon:de,handleUpdateCategoryColor:ge,handleRemovePath:$,handleSelectPath:_e,handleRemoveCategory:je,handleSaveType:se,handleRemoveType:ce,handleUpdateType:Re,handleUpdateTaxonomies:Pe,handleUpdatePriorities:Ce,analyzeSystemTaxonomyPack:Ee,handleApplySystemTaxonomyPack:U}}function Yw({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:t}){const[n,s]=r.useState([]),[o,l]=r.useState([]),i=e||t,d=r.useCallback(async()=>{if(!i)try{const g=await fetch("/api/taskforce/workflow-templates");if(g.ok){const v=await g.json();s(v.templates||[])}}catch{}},[i]),m=r.useCallback(async()=>{if(i)return[];try{const g=await fetch("/api/taskforce/initiative-templates");if(!g.ok)return[];const v=await g.json(),A=Array.isArray(v?.templates)?v.templates:[];return l(A),A}catch{return[]}},[i]),y=r.useCallback(async g=>{if(!g||i)return null;const v=[`/api/taskforce/workflow-template/${encodeURIComponent(g)}`,`/api/taskforce/workflow-templates/${encodeURIComponent(g)}`];try{for(const A of v){const _=await fetch(A);if(!_.ok)continue;const I=await _.json();if(I?.template)return I.template}return null}catch{return null}},[i]),k=r.useCallback(async()=>{if(i)return[];try{const g=await fetch("/api/taskforce/workflow-editor/overrides");if(!g.ok)return[];const v=await g.json();return Array.isArray(v?.names)?v.names:[]}catch{return[]}},[i]),S=r.useCallback(async(g,v)=>{try{const A=await fetch("/api/taskforce/workflow-editor/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g,draft:v})}),_=await A.json().catch(()=>({}));return!A.ok||!_.success?{success:!1,error:_.error||`Save failed (${A.status})`}:(d(),{success:!0})}catch(A){return{success:!1,error:A.message}}},[d]),h=r.useCallback(async g=>{try{const v=await fetch(`/api/taskforce/workflow-editor/reset/${encodeURIComponent(g)}`,{method:"POST"}),A=await v.json().catch(()=>({}));return!v.ok||!A.success?{success:!1,error:A.error||`Reset failed (${v.status})`}:(d(),{success:!0})}catch(v){return{success:!1,error:v.message}}},[d]);return{availableWorkflows:n,initiativeTemplates:o,fetchWorkflows:d,fetchInitiativeTemplates:m,fetchWorkflowTemplate:y,fetchWorkflowOverrideNames:k,saveWorkflowTemplateDraft:S,resetWorkflowTemplateDraft:h}}function Jw(){const[e,t]=r.useState(!1),n=r.useCallback(async()=>{if(!document.fullscreenElement){try{await document.documentElement.requestFullscreen(),t(!0)}catch(s){console.error(`Error attempting to enable full-screen mode: ${s}`)}return}document.exitFullscreen&&(await document.exitFullscreen(),t(!1))},[]);return r.useEffect(()=>{const s=()=>{t(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",s),()=>document.removeEventListener("fullscreenchange",s)},[]),{zenMode:e,setZenModeState:t,toggleZenMode:n}}async function Qw(e,t,n){if(e.current){t.current=!0;return}e.current=!0;try{do t.current=!1,await n();while(t.current)}finally{e.current=!1}}function Xw({tasks:e,archivedTasks:t,setTasks:n,setArchivedTasks:s,setLoadingTasks:o,getCurrentWorkspaceId:l,workspaceResetKey:i,shouldDeferProtectedApiCalls:d,shouldBlockProtectedApiCalls:m,handleUnauthorized:y,authRequiredForApi:k}){const S=r.useRef(new Map),h=r.useRef(!1),g=r.useRef([]),v=r.useRef([]),A=r.useRef(!1),_=r.useRef(!1),I=r.useRef(null),B=r.useRef(null);r.useEffect(()=>{g.current=e},[e]),r.useEffect(()=>{v.current=t},[t]);const V=r.useCallback(M=>`${M.updatedAt||M.createdAt||""}|${M.status}|${M.priority}|${M.title}`,[]),L=r.useCallback((M,O)=>O.aborted?M===O.reason?!0:M instanceof DOMException?M.name==="AbortError":String(M?.name||"").toLowerCase()==="aborterror":!1,[]),[J,me]=r.useState([]),ve=r.useRef(new Map),re=r.useCallback(M=>{!M.length||typeof window>"u"||(me(O=>Array.from(new Set([...O,...M]))),M.forEach(O=>{const de=ve.current.get(O);de&&window.clearTimeout(de);const ge=window.setTimeout(()=>{ve.current.delete(O),me($=>$.filter(_e=>_e!==O))},4e3);ve.current.set(O,ge)}))},[]);r.useEffect(()=>()=>{typeof window>"u"||(ve.current.forEach(M=>window.clearTimeout(M)),ve.current.clear())},[]),r.useEffect(()=>{S.current=new Map,h.current=!1,A.current=!1,_.current=!1,I.current?.abort("workspace-reset"),I.current=null,B.current?.abort("workspace-reset"),B.current=null,typeof window<"u"&&(ve.current.forEach(M=>window.clearTimeout(M)),ve.current.clear()),me([])},[i]);const x=r.useCallback(async(M=!1,O)=>{if(!(O?.ignoreAuthGuard===!0)&&(d||m))return;o(!M);const ge=String(l()||"").trim();I.current?.abort("superseded");const $=new AbortController;I.current=$;try{const _e=await fetch("/api/taskforce/tasks",{signal:$.signal});if(_e.status===401){y(),n([]),M||o(!1);return}if(_e.ok){const se=((await _e.json()).tasks||[]).map(Ce=>Po(Ce));if(String(l()||"").trim()!==ge)return;const Re=new Map,Pe=[];for(const Ce of se){const Ee=V(Ce);if(Re.set(Ce.id,Ee),!h.current)continue;const U=S.current.get(Ce.id);(!U||U!==Ee)&&Pe.push(Ce.id)}S.current=Re,h.current?re(Pe):h.current=!0,n(se)}}catch(_e){if(L(_e,$.signal))return;console.error("[Taskforce] Failed to fetch tasks:",_e)}finally{I.current===$&&(I.current=null,o(!1))}},[V,l,re,y,n,o,k,d,m]),K=r.useCallback(async(M=!1,O)=>{if(!(O?.ignoreAuthGuard===!0)&&(d||m))return;const ge=String(l()||"").trim();B.current?.abort("superseded");const $=new AbortController;B.current=$;try{const _e=await fetch("/api/taskforce/archive",{signal:$.signal});if(_e.ok){const je=await _e.json();if(String(l()||"").trim()!==ge)return;const ce=(je.archived||[]).map(Re=>({...Po(Re),isArchived:!0}));s(ce)}}catch(_e){if(L(_e,$.signal))return;console.error("[Taskforce] Failed to fetch archive:",_e)}finally{B.current===$&&(B.current=null)}},[l,L,s,d,m]),ue=r.useCallback(async M=>{const O=M?.isSilent!==!1,de=M?.ignoreAuthGuard===!0;await Promise.all([x(O,{ignoreAuthGuard:de}),K(O,{ignoreAuthGuard:de})])},[K,x]),pe=r.useCallback(async()=>{await Qw(A,_,async()=>{await ue({isSilent:!0})})},[ue]),X=r.useCallback(M=>{const O=Lv(M,g.current,v.current);g.current=O.tasks,v.current=O.archivedTasks,n(O.tasks),s(O.archivedTasks)},[n,s]);return{tasksRef:g,archivedTasksRef:v,recentlyChangedTaskIds:J,markRecentlyChangedTasks:re,fetchTasks:x,fetchArchive:K,refreshTaskCollections:ue,refreshTaskCollectionsFromInvalidation:pe,mergeTaskFromServer:X,getTaskRevisionKey:V}}function eb(e){const{editingTaskId:t,relationshipTasks:n,initiatives:s=[],workstreams:o=[],supplementalTasks:l=[],setComments:i}=e,d=r.useMemo(()=>{if(l.length===0)return n;const S=new Map;return n.forEach(h=>S.set(h.id,h)),l.forEach(h=>S.set(h.id,h)),Array.from(S.values())},[n,l]),m=r.useMemo(()=>{if(t)return d.find(S=>S.id===t)},[d,t]);r.useEffect(()=>{t&&i(m?.comments||[])},[t,m?.id,m?.updatedAt,m?.comments,i]);const y=r.useMemo(()=>{if(m?.workstreamId)return o.find(S=>S.id===m.workstreamId)},[m,o]),k=r.useMemo(()=>{if(y?.initiativeId)return s.find(S=>S.id===y.initiativeId)},[y,s]);return{currentTask:m,currentTaskWorkstream:y,currentTaskInitiative:k}}const gf="WS-",yf="IN-";function No(e){return Qc(gf,e)}function ay(e){return nf(gf,e)}function rm(e){return km(gf,e)}function Jr(e){return Qc(yf,e)}function tb(e){return nf(yf,e)}function ny(e){return km(yf,e)}function yp(e,t){const n=String(t||"").trim();if(!n)return null;const s=tb(n);return e.find(o=>o.id===n||Jr(o)===n||s!==null&&o.referenceNumber===s)||null}function ab(e){const t={};return e.forEach(n=>{const s=n.defaultValue;if(s!=null){if(Array.isArray(s)){s.length>0&&(t[n.id]=s.map(o=>typeof o=="number"?o:String(o)));return}t[n.id]=typeof s=="number"?s:String(s)}}),t}function nb(e,t){return e.filter(n=>{const s=t[n.id],o=Array.isArray(s)?s.length>0:s!=null&&s!=="";return n.status==="retired"&&!o?!1:n.formEnabled!==!1||n.isRequired===!0||o})}function rb(e){const{activeCategories:t,activeTypes:n,activeTab:s,attachments:o,checklistItems:l,comments:i,description:d,editingTaskId:m,flushPendingAutoSave:y,getPreferredCategoryValue:k,lastUsedCategory:S,newCommentText:h,relationshipTasks:g,workstreams:v,showArchive:A,taxonomies:_,setActiveTab:I,setApproach:B,setAssignee:V,setAttachments:L,setAttachmentsDirty:J,setCategory:me,setChecklistItems:ve,setComments:re,setComplexity:x,setDescription:K,setDueDate:ue,setEditingTaskId:pe,setError:X,setFormTaxonomies:M,setIsOpen:O,setNewCommentText:de,setPendingNavigation:ge,setWorkstreamInput:$,setPriority:_e,setScheduledDate:je,setShowArchive:se,setStatus:ce,setTaskReturnTrail:Re,setTitle:Pe,setType:Ce,setUnsavedModalOpen:Ee,taskReturnTrail:U,title:T}=e,b=r.useCallback(()=>n.find(Q=>String(Q.value||"").trim().length>0)?.value||Dr,[n]),j=r.useCallback(Q=>{if(m){y(),Q();return}if(!(T.trim()!==""||d.trim()!==""||l.length>0||h.trim()!==""||i.length>0||o.length>0)){Q();return}ge(()=>Q),Ee(!0)},[o,i.length,d,m,y,l,h,ge,Ee,T]),D=r.useCallback(()=>{O(!1)},[O]),te=r.useCallback(()=>{pe(null),Pe(""),K("");const Q=S,q=t.some(Se=>Se.label===Q||Se.value===Q);if(Q&&q){const Se=t.find(we=>we.label===Q||we.value===Q);me(Se?.value||Q)}else me(k(t));Ce(b()),_e(2),x(3),ce("task"),B("default"),V("unassigned"),je(""),ue(""),$(""),ve([]),M(ab(_)),re([]),de(""),L([]),J(!1),X("")},[t,k,b,S,B,V,L,J,me,ve,re,x,K,ue,pe,X,M,de,_e,je,ce,Pe,Ce,_]),P=r.useCallback(Q=>{const q=Q.trim();if(!q)return null;const Se=Rg(q);if(Se){const Me=g.find(nt=>nt.referenceNumber===Se);if(Me)return Me}const we=g.find(Me=>Me.id===q);if(we)return we;const Te=g.find(Me=>Qi(Me)===q);return Te||null},[g]),H=r.useCallback(Q=>{const q=Q.trim();if(!q)return null;const Se=q.toLowerCase(),we=ay(q);if(we){const nt=v.find(gt=>gt.referenceNumber===we);if(nt)return nt}const Te=v.find(nt=>nt.id===q);if(Te)return Te;const Me=v.find(nt=>nt.title.trim().toLowerCase()===Se);return Me||null},[v]),be=r.useCallback((Q,q)=>{q?.preserveReturnTrail||Re([]),pe(Q.id),Pe(Q.title),K(Q.description||""),me(Q.category||k(t)),Ce(Q.type||b()),_e(typeof Q.priority=="number"?Q.priority:2),x(typeof Q.complexity=="number"?Q.complexity:3),ce(Q.status||"task"),B(Q.approach||"default"),V(Q.assignee||"unassigned"),je(Q.scheduledDate||""),ue(Q.dueDate||"");const Se=Q.workstreamId&&v.find(we=>we.id===Q.workstreamId)||null;$(Se?No(Se)||Se.id:""),ve(Q.checklistItems||[]),re(Q.comments||[]),M(Q.taxonomies||{}),Q.taxonomies?.approach&&B(Q.taxonomies.approach),L(Q.attachments||[]),J(!1),I("add")},[t,k,b,I,B,V,L,J,me,ve,re,x,K,ue,pe,M,_e,je,ce,Re,Pe,Ce,v]),z=r.useCallback(Q=>{const q=g.find(Se=>Se.id===Q);q&&(s==="add"&&m&&m!==q.id&&Re(Se=>Se[Se.length-1]===m?Se:[...Se,m]),q.isArchived&&!A&&se(!0),be(q,{preserveReturnTrail:!0}))},[s,m,be,g,se,Re,A]),ie=r.useCallback(()=>{if(s!=="add"||!m||U.length===0)return!1;const Q=[...U];for(;Q.length>0;){const q=Q.pop();if(!q)continue;const Se=g.find(we=>we.id===q);if(Se)return Se.isArchived&&!A&&se(!0),Re(Q),be(Se,{preserveReturnTrail:!0}),!0}return Re([]),!1},[s,m,be,g,se,Re,A,U]),ee=r.useCallback(()=>{Re([])},[Re]);return{handleNavigation:j,handleClose:D,resetForm:te,resolveTaskIdInput:P,resolveWorkstreamIdInput:H,handleEdit:be,handleOpenTaskById:z,returnToPreviousTask:ie,clearReturnToParentTask:ee}}function sb(e){return e.map(t=>({...t}))}function ob(e){return e.map(t=>({...t}))}function ib(e){return e.map(t=>({...t}))}const cb={id:"software-development",label:"Software Development",description:"A software-oriented starter pack with developer-focused work types and a 4-level priority scale.",categories:[{value:"default",label:"General",icon:"Inbox"},{value:"product",label:"Product",icon:"Layers",color:"blue-500"},{value:"ui-ux",label:"UI/UX",icon:"Palette",color:"violet-500"},{value:"backend",label:"Backend",icon:"Server",color:"emerald-500"}],types:[{value:"feature",label:"Feature",icon:"Star",color:"teal-500",status:"active"},{value:"bug",label:"Bug",icon:"Bug",color:"red-500",status:"active"},{value:"chore",label:"Chore",icon:"Zap",color:"amber-500",status:"active"},{value:"refactor",label:"Refactor",icon:"Code",color:"blue-500",status:"active"},{value:"documentation",label:"Docs",icon:"Book",color:"sky-500",status:"active"}],priorities:[{value:1,label:"Low",color:"amber-200",icon:"ArrowDown"},{value:2,label:"Medium",color:"yellow-500",icon:"Minus"},{value:3,label:"High",color:"orange-500",icon:"ArrowUp"},{value:4,label:"Critical",color:"red-500",icon:"AlertTriangle"}]},lb=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",isDefaultStarter:!0,categories:[{value:Yc,label:ym,icon:"Inbox"}],types:[{value:"task",label:"Task",icon:"CheckSquare",color:"blue-500",status:"active"},{value:"deliverable",label:"Deliverable",icon:"Package",color:"teal-500",status:"active"},{value:"issue",label:"Issue",icon:"AlertCircle",color:"red-500",status:"active"},{value:"idea",label:"Idea",icon:"Lightbulb",color:"amber-500",status:"active"},{value:"review",label:"Review",icon:"Search",color:"violet-500",status:"active"}],priorities:[{value:1,label:"Low",color:"teal-500",icon:"ArrowDown"},{value:2,label:"Medium",color:"blue-500",icon:"Minus"},{value:3,label:"High",color:"amber-500",icon:"ArrowUp"}]},cb];function ry(){return lb.map(e=>({...e,categories:sb(e.categories),types:ob(e.types),priorities:ib(e.priorities)}))}const Kc=[{value:"task",label:"To Do",shortLabel:"To Do",icon:"Square",color:"blue-200"},{value:"on-hold",label:"Blocked",shortLabel:"Blocked",icon:"Pause",color:"amber-500"},{value:"in-progress",label:"Working",shortLabel:"Working",icon:"Play",color:"blue-500"},{value:"review",label:"Review",shortLabel:"Review",icon:"ScanSearch",color:"violet-500"},{value:"done",label:"Done",shortLabel:"Done",icon:"SquareCheck",color:"green-500"},{value:"cancelled",label:"Cancelled",shortLabel:"Cancelled",icon:"Ban",color:"red-500"}],Xs=Kc.map(({value:e,label:t,icon:n,color:s})=>({value:e,label:t,icon:n,color:s}));function hd(e){const t=String(e||"task").trim().toLowerCase();return t==="completed"?Kc.find(n=>n.value==="done")||Kc[0]:Kc.find(n=>n.value===t)||Kc[0]}const sy=["Folder","Code","FileText","Terminal","Database","Cpu","Globe","Layout","Server","Search","Settings","Zap","Shield","Star","Layers","Bug","Box","Book","MessageSquare","Image","Music","Video","Map","Mail","Camera","Heart","Anchor","Rocket","Target","Flag","Bookmark","Briefcase","Puzzle","SquareUserRound","Users","User","Unplug","Clock","Lock","Pencil","TrafficCone","CircleDollarSign","Activity","Wrench","Microscope","Palette","Webhook","FlaskConical","Bot","Cloud","Kanban","Infinity","Monitor","Smartphone","History","Brain","Calendar","Play","Pause","Sparkles","Check","Ban","Circle","CheckCircle","Wind","Github","Square","SquareCheck","CheckSquare","Package","AlertCircle","Lightbulb","ScanSearch","Inbox","HelpCircle","Gauge","FileCode","ArrowDown","Minus","ArrowUp","AlertTriangle","CircleQuestionMark","TriangleAlert"],ec=sy.reduce((e,t)=>(e[t]=ks[t]||Yi,e),{}),HO=sy,sm=Object.fromEntries(ry().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,t)=>(e.some(([n])=>n===t.value)||e.push([t.value,{icon:t.icon,color:t.color}]),e),[])),db={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"},Sh={"red-200":"#eb7a7a","orange-200":"#eba87a","amber-200":"#ebc17a","yellow-200":"#ebd07a","green-200":"#7aeba4","teal-200":"#7aebdf","sky-200":"#7ac8eb","blue-200":"#7aa5eb","indigo-200":"#7a7ceb","violet-200":"#9c7aeb","red-500":"#e42525","orange-500":"#e47325","amber-500":"#e49d25","yellow-500":"#e4b625","green-500":"#25e46b","teal-500":"#25e4cf","sky-500":"#25a9e4","blue-500":"#256ee4","indigo-500":"#2529e4","violet-500":"#5f25e4","red-700":"#951818","orange-700":"#954b18","amber-700":"#956718","yellow-700":"#957718","green-700":"#189546","teal-700":"#189587","sky-700":"#186e95","blue-700":"#184895","indigo-700":"#181b95","violet-700":"#3e1895"},GO=["red-200","orange-200","amber-200","yellow-200","green-200","teal-200","sky-200","blue-200","indigo-200","violet-200","red-500","orange-500","amber-500","yellow-500","green-500","teal-500","sky-500","blue-500","indigo-500","violet-500","red-700","orange-700","amber-700","yellow-700","green-700","teal-700","sky-700","blue-700","indigo-700","violet-700"];function Nn(e){if(e)return Sh[e]?Sh[e]:e}function ub(e){const t=String(e||"").trim().toLowerCase();return Nn(sm[t]?.color)||Nn("violet-200")||"#9c7aeb"}function VO(e){switch(Number(e)){case 1:return"var(--text-muted)";case 2:return"var(--text-secondary)";case 3:return"var(--priority-high)";case 4:return"var(--priority-critical)";default:return"var(--text-secondary)"}}function mb(e){const t=String(e||"").trim().toUpperCase();return Nn(db[t])||"var(--text-muted)"}const pb=/[\u2010-\u2015\u2212]/g;function kf(e){return String(e??"").trim().replace(pb,"-").replace(/\s+/g," ").toLowerCase()}function wm(e){const t=kf(e);if(!t)return null;const n=t.match(/^(l\s*t|t)\s*(?:-\s*)?(\d+)$/i);return n?`${n[1].replace(/\s+/g,"").toLowerCase()}-${n[2]}`:null}function bm(e){const t=kf(e);return{raw:t,tokens:t?t.split(" ").filter(Boolean):[],referenceToken:wm(e)}}function Yr(e,t){const n=String(t??"").trim();n&&e.push(n)}function Hc(e,t,n){const s=String(n??"").trim();if(!s)return;const o=t?.find(l=>String(l.value)===s);Yr(e,o?.label)}function fb(e,t={}){const n=[];return Yr(n,e.title),Yr(n,e.description),Yr(n,e.id),Yr(n,Qi(e)),Yr(n,e.category),Yr(n,e.type),Yr(n,e.priority),Yr(n,e.status),Yr(n,e.assignee||"unassigned"),Yr(n,e.canceledReason),Hc(n,t.categories,e.category),Hc(n,t.types,e.type),Hc(n,t.priorities,e.priority),Hc(n,Xs,e.status),Hc(n,t.assigneeOptions,e.assignee||"unassigned"),Object.entries(e.taxonomies||{}).forEach(([s,o])=>{const l=t.taxonomies?.find(d=>d.id===s);Yr(n,l?.label),(Array.isArray(o)?o:[o]).forEach(d=>{Yr(n,d),Hc(n,l?.options,d)})}),n}function om(e,t,n={}){const s=typeof t=="string"?bm(t):t;if(!s.raw)return!0;const o=fb(e,n),i=o.map(kf).filter(Boolean).join(" ");return i.includes(s.raw)||s.referenceToken&&o.map(wm).some(m=>m?.includes(s.referenceToken))?!0:s.tokens.length>0&&s.tokens.every(d=>i.includes(d))}function hb(e,t){const n=e.taxonomies?.[t];return n==null||n===""?!1:Array.isArray(n)?n.some(s=>String(s).trim().length>0):String(n).trim().length>0}function xd(e,t){const n=e.filter(o=>o.status!=="retired"),s=e.filter(o=>o.status==="retired"&&t.some(l=>hb(l,o.id)));return[...n,...s.filter(o=>!n.some(l=>l.id===o.id))]}function oy(e,t=[]){return xd(e,t).filter(n=>n.sortEnabled===!0).map(n=>({value:`taxonomy:${n.id}`,label:n.status==="retired"?`${n.label} (Retired)`:n.label}))}function wh(e,t){const n=e.taxonomies?.[t.id];if(n==null||n==="")return null;const s=Array.isArray(n)?n.map(o=>String(o)):[String(n)];for(let o=0;o<t.options.length;o+=1)if(s.includes(String(t.options[o]?.value)))return o;return null}function zi(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}function im(e,t,n,s,o=[]){let l=0;if(n==="created")return l=zi(e,t),s==="desc"?l:-l;if(n==="updated"){const i=e.updatedAt||e.createdAt,d=t.updatedAt||t.createdAt;return l=new Date(d).getTime()-new Date(i).getTime(),s==="desc"?l:-l}if(n==="priority"){const i=Qu(e.priority),d=Qu(t.priority);return l=i!==d?d-i:zi(e,t),s==="desc"?l:-l}if(n==="complexity"){const i=typeof e.complexity=="number"?e.complexity:3,d=typeof t.complexity=="number"?t.complexity:3;return l=i!==d?d-i:zi(e,t),s==="desc"?l:-l}if(n.startsWith("taxonomy:")){const i=n.slice(9),d=o.find(k=>k.id===i);if(!d)return l=zi(e,t),s==="desc"?l:-l;const m=wh(e,d),y=wh(t,d);return m===null&&y===null?zi(e,t):m===null?1:y===null?-1:m!==y?s==="desc"?y-m:m-y:zi(e,t)}return l=zi(e,t),s==="desc"?l:-l}function gb(e,t,n){const s=e.taxonomies?.[t];return s==null||s===""?!1:Array.isArray(s)?s.some(o=>String(o)===String(n)):String(s)===String(n)}function vf(e,t){const n=e.options.filter(o=>o.status!=="retired"),s=e.options.filter(o=>o.status==="retired"&&t.some(l=>gb(l,e.id,o.value)));return[...n,...s.filter(o=>!n.some(l=>String(l.value)===String(o.value)))]}function yb({tasks:e,archivedTasks:t,activeCategories:n,activeTypes:s,priorities:o,taxonomies:l,configLoaded:i,referenceDataLoaded:d,assigneeOptionsLoaded:m,assigneeOptions:y}){const k=r.useMemo(()=>$g(y),[y]),S=r.useMemo(()=>xd(l,[...e,...t]).filter(z=>z.filterEnabled!==!1).map(z=>({...z,options:vf(z,[...e,...t])})),[t,e,l]),h=r.useMemo(()=>k.map(z=>z.value),[k]),[g,v]=r.useState(""),[A,_]=r.useState([]),[I,B]=r.useState([]),[V,L]=r.useState([]),[J,me]=r.useState(!1),[ve,re]=r.useState(Xs.map(z=>z.value)),[x,K]=r.useState(h),[ue,pe]=r.useState(!0),[X,M]=r.useState({}),[O,de]=r.useState("created"),[ge,$]=r.useState("desc"),_e=r.useCallback(()=>{$(z=>z==="asc"?"desc":"asc")},[]),[je,se]=r.useState("status"),[ce,Re]=r.useState("show"),[Pe,Ce]=r.useState({}),Ee=r.useCallback((z,ie)=>ie.length===0?!0:ie.every(ee=>z.includes(ee)),[]),U=r.useCallback((z,ie)=>z.length===ie.length&&z.every((ee,Q)=>ee===ie[Q]),[]);r.useEffect(()=>{je==="approach"&&se("status")},[je]),r.useEffect(()=>{if(!(!i||!d)&&m&&!J&&n.length>0&&s.length>0&&o.length>0){_(n.map(ie=>ie.value)),B(o.map(ie=>ie.value)),L(s.map(ie=>ie.value)),K(h),pe(!0);const z={};S.forEach(ie=>{z[ie.id]=ie.options.map(ee=>ee.value)}),M(z),me(!0)}},[i,d,m,n,s,o,S,J,h]),r.useEffect(()=>{if(!J||!m)return;const z=new Set(h),ie=x.filter(q=>z.has(q)),ee=ue?h:ie.length>0||x.length===0?ie:h;(ee.length!==x.length||ee.some((q,Se)=>q!==x[Se]))&&K(ee)},[h,x,ue,J,m]),r.useEffect(()=>{if(!J||!m)return;const z=x.filter(ee=>h.includes(ee)),ie=h.length>0&&h.every(ee=>z.includes(ee));ie!==ue&&pe(ie)},[h,x,ue,J,m]),r.useEffect(()=>{if(!i||!d||!J||n.length===0)return;const z=Wv(A,n);(z.length!==A.length||z.some((ee,Q)=>ee!==A[Q]))&&_(z)},[i,d,n,J,A]),r.useEffect(()=>{if(!i||!d||!J||o.length===0||I.length===0)return;const z=Bv(I,o),ie=Array.from(new Set(I.map(Q=>Number(Q)).filter(Q=>Number.isFinite(Q))));(z.length!==ie.length||z.some((Q,q)=>Q!==ie[q]))&&B(z)},[i,d,J,o,I]),r.useEffect(()=>{if(!i||!d||!J||s.length===0)return;const z=new Set(s.map(Q=>Q.value)),ie=V.filter(Q=>z.has(Q)),ee=ie.length>0||V.length===0?ie:s.map(Q=>Q.value);U(ee,V)||L(ee)},[s,i,V,J,U,d]),r.useEffect(()=>{if(!i||!d||!J)return;const z={};S.forEach(Se=>{const we=Se.options.map(nt=>nt.value);if(we.length===0)return;const Te=Array.isArray(X[Se.id])?X[Se.id]:[],Me=Te.filter(nt=>we.includes(nt));z[Se.id]=Me.length>0||Te.length===0?Me:we});const ie=Object.keys(X).sort(),ee=Object.keys(z).sort(),Q=ie.length!==ee.length||ie.some((Se,we)=>Se!==ee[we]),q=ee.some(Se=>!U(X[Se]||[],z[Se]||[]));(Q||q)&&M(z)},[i,X,S,J,U,d]);const T=r.useCallback(()=>{v(""),_(n.map(ie=>ie.value)),B(o.map(ie=>ie.value)),L(s.map(ie=>ie.value)),re(Xs.map(ie=>ie.value)),K(h),pe(!0);const z={};S.forEach(ie=>{z[ie.id]=ie.options.map(ee=>ee.value)}),M(z),de("created"),$("desc")},[n,o,s,S,h]),b=r.useCallback(z=>{K(ie=>{const ee=typeof z=="function"?z(ie):z,Q=Array.from(new Set(ee.filter(Se=>typeof Se=="string"&&Se.trim().length>0))),q=h.length>0&&h.every(Se=>Q.includes(Se));return pe(q),Q})},[h]),j=r.useMemo(()=>bm(g),[g]),D=r.useMemo(()=>({categories:n,types:s,priorities:o,assigneeOptions:k,taxonomies:l}),[n,s,o,k,l]),te=r.useMemo(()=>{const z=Ee(A,n.map(q=>q.value)),ie=Ee(V,s.map(q=>q.value)),ee=Ee(Array.from(new Set(I.map(q=>Number(q)).filter(q=>Number.isFinite(q)))),o.map(q=>Number(q.value)).filter(q=>Number.isFinite(q))),Q=Ee(ve,Xs.map(q=>q.value));return e.filter(q=>{const Se=om(q,j,D),we=!J||z||A.includes(q.category),Te=!J||ee||lp(q.priority,I),Me=!J||ie||V.includes(q.type||Dr),nt=!J||Q||ve.includes(q.status),gt=!J||ue||x.includes(q.assignee||"unassigned"),lt=Object.entries(X).every(([St,Ke])=>{const Ct=S.find(ct=>ct.id===St);if(!Ct)return!0;const dt=Ct?.options.every(ct=>Ke.includes(ct.value))??!0;if(dt)return!0;const Xe=q.taxonomies?.[St];return Xe?Array.isArray(Xe)?Xe.some(ct=>Ke.includes(ct)):Ke.includes(Xe):dt||Ke.includes("")});return Se&&we&&Te&&Me&&nt&>&<}).sort((q,Se)=>im(q,Se,O,ge,l))},[e,t,j,D,A,I,V,ve,x,ue,X,O,ge,J,S,n,s,o,Ee,l]),P=r.useMemo(()=>{const z=Ee(A,n.map(q=>q.value)),ie=Ee(V,s.map(q=>q.value)),ee=Ee(Array.from(new Set(I.map(q=>Number(q)).filter(q=>Number.isFinite(q)))),o.map(q=>Number(q.value)).filter(q=>Number.isFinite(q))),Q=Ee(ve,Xs.map(q=>q.value));return e.filter(q=>{const Se=!J||z||A.includes(q.category),we=!J||ee||lp(q.priority,I),Te=!J||ie||V.includes(q.type||Dr),Me=!J||Q||ve.includes(q.status),nt=!J||ue||x.includes(q.assignee||"unassigned"),gt=Object.entries(X).every(([lt,St])=>{const Ke=S.find(Xe=>Xe.id===lt);if(!Ke)return!0;const Ct=Ke?.options.every(Xe=>St.includes(Xe.value))??!0;if(Ct)return!0;const dt=q.taxonomies?.[lt];return dt?Array.isArray(dt)?dt.some(Xe=>St.includes(Xe)):St.includes(dt):Ct||St.includes("")});return Se&&we&&Te&&Me&&nt&>})},[e,t,A,I,V,ve,x,ue,X,J,S,n,s,o,Ee]),H=r.useMemo(()=>{const z=n.every(Q=>A.includes(Q.value)),ie=Ee(V,s.map(Q=>Q.value)),ee=Ee(Array.from(new Set(I.map(Q=>Number(Q)).filter(Q=>Number.isFinite(Q)))),o.map(Q=>Number(Q.value)).filter(Q=>Number.isFinite(Q)));return t.filter(Q=>{const q=om(Q,j,D),Se=!J||z||A.includes(Q.category),we=!J||ee||lp(Q.priority,I),Te=!J||ie||V.includes(Q.type||Dr),Me=!J||ue||x.includes(Q.assignee||"unassigned"),nt=Object.entries(X).every(([gt,lt])=>{const St=S.find(dt=>dt.id===gt);if(!St)return!0;const Ke=St?.options.every(dt=>lt.includes(dt.value))??!0;if(Ke)return!0;const Ct=Q.taxonomies?.[gt];return Ct?Array.isArray(Ct)?Ct.some(dt=>lt.includes(dt)):lt.includes(Ct):Ke||lt.includes("")});return q&&Se&&we&&Te&&Me&&nt}).sort((Q,q)=>im(Q,q,O,ge,l))},[t,j,D,A,I,V,x,ue,X,O,ge,J,n,s,o,S,Ee,l]),be=r.useMemo(()=>{const z={};return te.forEach(ie=>{const ee=n.find(q=>q.value===ie.category),Q=ee?ee.label:ie.category||"General";z[Q]||(z[Q]=[]),z[Q].push(ie)}),z},[te,n]);return{searchQuery:g,setSearchQuery:v,filterCategories:A,setFilterCategories:_,filterPriorities:I,setFilterPriorities:B,filterTypes:V,setFilterTypes:L,filterStatus:ve,setFilterStatus:re,filterAssignees:x,setFilterAssignees:b,filterAssigneesAllSelected:ue,setFilterAssigneesAllSelected:pe,filterTaxonomies:X,setFilterTaxonomies:M,hasInitedFilters:J,setHasInitedFilters:me,sortBy:O,setSortBy:de,sortOrder:ge,setSortOrder:$,toggleSortOrder:_e,groupBy:je,setGroupBy:se,emptyColumnMode:ce,setEmptyColumnMode:Re,collapsedCategories:Pe,setCollapsedCategories:Ce,clearFilters:T,filteredTasks:te,searchAgnosticTasks:P,filteredArchive:H,groupedTasks:be}}const kb=yb;function vb(e){const{activeCategories:t,activeTab:n,apiEndpoint:s,approach:o,assignee:l,attachments:i,attachmentsDirty:d,category:m,checklistItems:y,comments:k,complexity:S,description:h,dueDate:g,editingTaskId:v,fetchTasks:A,formTaxonomies:_,getPreferredCategoryValue:I,mergeTaskFromServer:B,workstreamInput:V,priority:L,pushNotice:J,queueWorkspaceSyncFromAuthoritativeTaskState:me,relationshipTasks:ve,resetForm:re,resolveWorkstreamIdInput:x,scheduledDate:K,setActiveTab:ue,setAttachmentsDirty:pe,setComments:X,setError:M,setLastUsedCategory:O,setLoading:de,setNewCommentText:ge,status:$,title:_e,taxonomies:je,type:se}=e,[ce,Re]=r.useState(null),[Pe,Ce]=r.useState("idle"),[Ee,U]=r.useState(null),T=r.useRef(null),b=r.useCallback(()=>JSON.stringify({title:_e.trim(),description:h||"",category:typeof m=="string"?m:m.label||I(t),type:typeof se=="string"?se:se.label||Dr,priority:Number(L),complexity:Number(S)||3,approach:o||"default",assignee:l||"agent",scheduledDate:K||"",dueDate:g||"",workstreamInput:V.trim(),checklistItems:y,comments:k,taxonomies:_,attachments:i}),[t,o,l,i,m,y,k,S,h,g,_,I,L,K,_e,se,V]),j=r.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),D=r.useCallback(async ee=>{const Q=ee?.quiet??!1,q=ee?.source??"manual";if(!_e.trim())return M("Title is required"),v&&Ce(q==="autosave"?"error":"idle"),!1;const Se=je.filter(we=>we.isRequired).filter(we=>{const Te=_[we.id];return Array.isArray(Te)?Te.filter(Me=>String(Me).trim().length>0).length===0:typeof Te!="string"&&typeof Te!="number"||String(Te).trim().length===0}).map(we=>we.label);if(Se.length>0)return M(`Required taxonomy values are missing: ${Se.join(", ")}`),v&&Ce(q==="autosave"?"error":"idle"),!1;if(v&&ve.find(Te=>Te.id===v)?.isArchived)return M("Archived tasks are read-only. Unarchive first to make changes."),Ce(q==="autosave"?"error":"idle"),!1;de(!0),M(""),v&&Ce("saving");try{const we=v?`/api/taskforce/task/${v}`:s.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),Te=v?"PATCH":"POST",Me=typeof m=="string"?m:m.label||I(t),nt=typeof se=="string"?se:se.label||Dr,gt=V.trim()?x(V):null,lt={title:_e,description:h||null,category:Me||I(t),type:nt,priority:L,complexity:Number(S)||3,status:v?void 0:$,completedAt:v?void 0:$==="done"?new Date().toISOString():null,approach:o||"default",assignee:l||"agent",scheduledDate:K||null,dueDate:g||null,workstreamId:V.trim()?gt?.id||V.trim():null,checklistItems:y,comments:k,taxonomies:_,...v?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};(!v||d)&&(lt.attachments=i),v&&(lt.saveSource=q);const St=await fetch(we,{method:Te,headers:{"Content-Type":"application/json"},body:JSON.stringify(lt)});if(!St.ok){const dt=(await St.json()).message||`Failed to ${v?"update":"save"} task`;return M(dt),Q||J(dt,"error"),de(!1),v&&Ce("error"),!1}const Ke=await St.json().catch(()=>null);return v&&Ke&&typeof Ke=="object"&&(B(Ke),me()),O(Me),pe(!1),de(!1),v&&Ce("saved"),!0}catch{return M("Failed to connect to server"),Q||J("Failed to connect to server","error"),de(!1),v&&Ce("error"),!1}},[t,s,o,l,i,d,m,y,k,S,h,g,v,_,I,B,V,L,J,me,x,pe,M,O,de,K,$,_e,je,se]),te=r.useCallback(async()=>{await D({source:"manual"})&&(v||J("Task added successfully","success"),n==="add"&&!v&&(re(),ue("tasks"),await A()))},[n,v,A,J,re,D,ue]);r.useEffect(()=>{if(j(),!v){U(null),Ce("idle");return}U(b()),Ce("idle")},[j,v]);const P=r.useCallback(async()=>{if(j(),!v||Ee===null)return;const ee=b();if(ee===Ee||!_e.trim()||g&&K&&g<K)return;await D({quiet:!0,source:"autosave"})&&U(ee)},[b,j,g,v,Ee,D,K,_e]);r.useEffect(()=>{if(!v||Ee===null)return;const ee=b();if(ee!==Ee){if(!_e.trim()){Ce("idle");return}if(g&&K&&g<K){Ce("error");return}return Ce(Q=>Q==="error"?"error":"idle"),j(),T.current=window.setTimeout(async()=>{await D({quiet:!0,source:"autosave"})&&U(ee)},700),()=>{j()}}},[b,j,g,v,Ee,D,K,_e]);const H=r.useCallback(async ee=>{if(ee.preventDefault(),g&&K&&g<K){Re({dueDate:g,scheduledDate:K});return}await te()},[g,te,K]),be=r.useCallback(async()=>{Re(null),await te()},[te]),z=r.useCallback(()=>{Re(null)},[]),ie=r.useCallback(async ee=>{if(!v||!ee.trim())return;const Q=ee.trim();try{const q=await fetch(`/api/taskforce/task/${v}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:Q,author:"user"})});if(!q.ok){const Te=(await q.json().catch(()=>({}))).error||"Failed to add comment.";M(Te),J(Te,"error");return}const Se=await q.json().catch(()=>null);if(ge(""),Se&&typeof Se=="object"){const we=Po(Se);X(we.comments||[]),B(Se),U(b()),Ce("saved")}else await A(!0);me()}catch(q){console.error("Failed to add comment",q),M("Failed to add comment."),J("Failed to add comment.","error")}},[v,A,b,B,J,me,X,M,ge]);return{autoSaveState:Pe,flushAutoSave:P,scheduleWarningPrompt:ce,saveTask:D,handleSubmit:H,confirmScheduleWarning:be,cancelScheduleWarning:z,handleAddComment:ie}}function Sb(e){const{editingTaskId:t,fetchTasks:n,mergeTaskFromServer:s,workstreamInput:o,pushNotice:l,queueWorkspaceSyncFromAuthoritativeTaskState:i,relationshipTasks:d,resolveWorkstreamIdInput:m,setError:y}=e;return{handleSetWorkstreamForCurrentTask:r.useCallback(async S=>{if(!t)return;const h=d.find(_=>_.id===t);if(!h)return;const g=typeof S=="string"?S.trim():S===null?"":o.trim(),v=g?m(g):null,A=g.length>0?v?.id||g:null;if((h.workstreamId||null)===A){l(A?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const _=await fetch(`/api/taskforce/task/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:A})});if(!_.ok){const V=(await _.json().catch(()=>({}))).error||"Failed to set workstream.";y(V),l(V,"error");return}y(""),l(A?"Workstream set":"Workstream removed","info");const I=await _.json().catch(()=>null);I?(s(I),i()):(await n(!0),i())}catch{y("Failed to set workstream."),l("Failed to set workstream.","error")}},[t,n,s,o,l,i,d,m,y])}}function wb({tasks:e,archivedTasks:t,editingTaskId:n,setTasks:s,setArchivedTasks:o,setDeletedTasks:l,setError:i,resetForm:d,setActiveTab:m,fetchTasks:y,fetchArchive:k,fetchDeletedTasks:S,mergeTaskFromServer:h,pushNotice:g,cloudAuthConfigured:v,runtimeMode:A,isAuthenticated:_,workspaceCloudSyncEnabled:I,buildWorkspaceSyncSignature:B,pushWorkspaceChangesToCloud:V,workspacePendingSignatureRef:L,workspaceDeletedTaskIdsRef:J,workspaceDeletedTaskWatermarksRef:me}){const[ve,re]=r.useState(null),x=r.useRef(null),K=r.useRef(null),ue=r.useRef(null);r.useEffect(()=>()=>{typeof window>"u"||(K.current!==null&&(window.clearTimeout(K.current),K.current=null),ue.current=null)},[]);const pe=r.useCallback((U=0)=>{if(!(v&&A==="local"&&_&&I)||typeof window>"u")return;const T=Math.max(0,U),b=Date.now()+T,j=ue.current;if(K.current!==null){if(T<=0||j!==null&&j>=b)return;window.clearTimeout(K.current),K.current=null}ue.current=b,K.current=window.setTimeout(()=>{K.current=null,ue.current=null;const D=B();D&&(L.current=D,V(D))},T)},[v,A,_,I,B,L,V]),X=r.useCallback(async(U,T)=>{let b=await fetch(`/api/taskforce/deleted${U}`,T);return b.status===404&&(b=await fetch(`/api/taskforce/trash${U}`,T)),b},[]),M=async(U,T=!1,b={})=>{if(!b.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const j=T||t.some(D=>D.id===U);try{const D=await fetch(`/api/taskforce/task/${U}`,{method:"DELETE"});if(!D.ok){const be=(await D.json().catch(()=>({}))).error||"Failed to delete task.";return i(be),g(be,"error"),!1}const te=await D.json().catch(()=>({})),P=te?.deleted&&typeof te.deleted=="object"&&te.deleted.taskSnapshot?{...te.deleted,taskSnapshot:Po(te.deleted.taskSnapshot)}:null;if(window.location.search.includes(U)){const H=new URL(window.location.href);H.searchParams.delete("task"),window.history.pushState({},"",H.toString())}if(j?o(H=>H.filter(be=>be.id!==U)):s(H=>H.filter(be=>be.id!==U)),P){l(be=>[P,...be.filter(z=>z.taskId!==U)]);const H=String(P.deletedAt||"").trim();Number.isFinite(Date.parse(H))&&me.current.set(U,H)}else await S(!0),me.current.set(U,new Date().toISOString());if(J.current.add(U),v&&A==="local"&&_&&I){const H=B();L.current=H,V(H)}return n===U&&(d(),m("tasks")),i(""),g("Task moved to Trash.","info"),!0}catch(D){return console.error("Failed to delete task:",D),i("Failed to delete task."),g("Failed to delete task.","error"),!1}},O=r.useCallback(async U=>{try{const T=await X(`/${U}/restore`,{method:"POST"});if(!T.ok){const te=(await T.json().catch(()=>({}))).error||"Failed to restore deleted task.";return i(te),g(te,"error"),null}const b=await T.json().catch(()=>null);b?h(b):await y(!0),l(D=>D.filter(te=>te.id!==U&&te.taskId!==U));const j=String(b?.id||"").trim();return J.current.delete(U),me.current.delete(U),j&&(J.current.delete(j),me.current.delete(j)),pe(),i(""),g("Task restored from Trash.","info"),b?Po(b):null}catch(T){return console.error("Failed to restore deleted task:",T),i("Failed to restore deleted task."),g("Failed to restore deleted task.","error"),null}},[y,h,g,pe,X,l,i]),de=r.useCallback(async U=>{try{const T=await X(`/${U}`,{method:"DELETE"});if(!T.ok){const j=(await T.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return i(j),g(j,"error"),!1}return l(b=>b.filter(j=>j.id!==U&&j.taskId!==U)),pe(),i(""),g("Deleted task permanently removed.","info"),!0}catch(T){return console.error("Failed to permanently delete deleted task:",T),i("Failed to permanently delete deleted task."),g("Failed to permanently delete deleted task.","error"),!1}},[g,pe,X,l,i]),ge=r.useCallback(async()=>{try{const U=await X("/empty",{method:"POST"});if(!U.ok){const D=(await U.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return i(D),g(D,"error"),null}const T=await U.json().catch(()=>({})),b=Number(T?.deleted||0);return l([]),pe(),i(""),g(b===1?"Deleted task permanently removed.":`${b} deleted tasks permanently removed.`,"info"),b}catch(U){return console.error("Failed to empty deleted tasks:",U),i("Failed to permanently delete deleted tasks."),g("Failed to permanently delete deleted tasks.","error"),null}},[g,pe,X,l,i]),$=r.useCallback(async(U,T)=>{const b=e,j=t;s(D=>D.map(te=>te.id===U?{...te,...T}:te)),o(D=>D.map(te=>te.id===U?{...te,...T}:te));try{const D=await fetch(`/api/taskforce/task/${U}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!D.ok){const H=(await D.json().catch(()=>({}))).error||`Failed to update task ${U}.`;i(H),g(H,"error"),s(b),o(j);return}const te=await D.json().catch(()=>null);h(te),pe(T.attachments!==void 0?150:0),i("")}catch(D){console.error("Failed to update task",D);const te=`Failed to update task ${U}.`;i(te),g(te,"error"),s(b),o(j)}},[e,t,g,h,pe]);return{copiedId:ve,handleDelete:M,handleUpdateTask:$,handleToggleComplete:async U=>{const T=U.status==="done"?"task":"done",b=T==="done"?new Date().toISOString():void 0,j={status:T,completedAt:b,completed:T==="done",inProgress:!1,readyForReview:!1,cancelled:!1},D=e,te=t;s(P=>P.map(H=>H.id===U.id?{...H,...j}:H)),o(P=>P.map(H=>H.id===U.id?{...H,...j}:H));try{const P=await fetch(`/api/taskforce/task/${U.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T,completedAt:b})});if(!P.ok){const z=(await P.json().catch(()=>({}))).error||"Failed to update task status.";i(z),g(z,"error"),s(D),o(te);return}const H=await P.json().catch(()=>null);H?(h(H),pe()):(await y(!0),pe()),i("")}catch(P){console.error("Failed to toggle complete",P),i("Failed to update task status."),g("Failed to update task status.","error"),s(D),o(te)}},handleToggleCancel:async U=>{const T=U.status==="cancelled"?"task":"cancelled";try{const b=await fetch(`/api/taskforce/task/${U.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!b.ok){const te=(await b.json().catch(()=>({}))).error||"Failed to update task status.";i(te),g(te,"error"),await y(!0);return}const j=await b.json().catch(()=>null);j?(h(j),pe()):(await y(!0),pe()),i("")}catch(b){console.error("Failed to toggle cancel",b),i("Failed to update task status."),g("Failed to update task status.","error"),y()}},handleToggleInProgress:async U=>{const T=U.status==="in-progress"?"task":"in-progress";s(b=>b.map(j=>j.id===U.id?{...j,status:T}:j));try{const b=await fetch(`/api/taskforce/task/${U.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!b.ok){await y(!0);return}const j=await b.json().catch(()=>null);h(j),pe()}catch{y()}},handleToggleReview:async U=>{const T=U.status==="review"?"task":"review";s(b=>b.map(j=>j.id===U.id?{...j,status:T}:j));try{const b=await fetch(`/api/taskforce/task/${U.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:T})});if(!b.ok){await y(!0);return}const j=await b.json().catch(()=>null);h(j),pe()}catch{y()}},handleArchiveTask:async U=>{try{const b=U.status==="cancelled"?"cancel":"complete",j=await fetch(`/api/taskforce/task/${U.id}/${b}`,{method:"POST"});if(j.ok){const D=await j.json().catch(()=>null),te=[];if(D&&typeof D=="object"&&te.push(D),te.length>0){for(const H of te)h(H);pe()}else k();const P=new Set(te.map(H=>String(H?.id||"").trim()).filter(H=>H.length>0));n&&P.has(n)&&(d(),m("tasks"))}else{const te=(await j.json().catch(()=>({}))).error||"Failed to archive task.";i(te),g(te,"error")}}catch(T){console.error("Failed to archive",T),i("Failed to archive task."),g("Failed to archive task.","error")}},handleBulkArchive:async()=>{const U=e.filter(T=>T.status==="done"||T.status==="cancelled");if(U.length!==0&&confirm(`Archive ${U.length} completed/cancelled tasks?`))try{const T=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:U.map(b=>b.id)})});if(T.ok){const b=await T.json(),j=Array.isArray(b?.results?.archived)?b.results.archived:[];if(j.length>0){for(const D of j)h(D);pe()}else s(D=>D.filter(te=>!["done","cancelled"].includes(te.status))),k();g(`${b.archived||U.length} tasks archived`,"info"),i("")}else{const j=(await T.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";i(j),g(j,"error")}}catch(T){console.error("Failed to bulk archive",T),i("Failed to bulk archive tasks."),g("Failed to bulk archive tasks.","error")}},handleUnarchive:async U=>{try{const T=await fetch(`/api/taskforce/task/${U}/unarchive`,{method:"POST"});if(T.ok){const b=await T.json().catch(()=>null);b?(h(b),pe()):(o(j=>j.filter(D=>D.id!==U)),await y(!0),pe()),i(""),g("Task restored from archive.","info")}}catch(T){console.error("Failed to unarchive",T),i("Failed to unarchive task."),g("Failed to unarchive task.","error")}},handleRestoreDeletedTask:O,handlePermanentlyDeleteDeletedTask:de,handleEmptyDeletedTasks:ge,handleCopyId:(U,T)=>{U.stopPropagation(),navigator.clipboard.writeText(T),re(T),x.current!==null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{x.current=null,re(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:pe}}const bb=wb;function Pu(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function _b(e){try{return typeof window>"u"?null:typeof e=="string"?new URL(e,window.location.origin):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,window.location.origin):null}catch{return null}}function Cb({currentWorkspaceIdRef:e,resolveApiUrl:t,runtimeMode:n}){r.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const s=window.fetch.bind(window),o=l=>{if(typeof l=="string")return n!=="cloud"?l:l.startsWith("/api/taskforce")&&!Pu(l)?t(l):l;if(l instanceof URL)return n!=="cloud"?l:l.origin===window.location.origin&&l.pathname.startsWith("/api/taskforce")?Pu(l.pathname)?l:new URL(t(`${l.pathname}${l.search}${l.hash}`)):l;if(typeof Request<"u"&&l instanceof Request){if(n!=="cloud")return l;const i=new URL(l.url,window.location.origin);if(i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce"))return Pu(i.pathname)?l:t(`${i.pathname}${i.search}${i.hash}`)}return l};return window.fetch=((l,i)=>{const d=o(l),m=_b(d);if(!!!(m&&m.pathname.startsWith("/api/taskforce")&&!Pu(m.pathname)))return s(d,i);const k=String(e.current||"").trim();if(typeof Request<"u"&&d instanceof Request){const h=new Headers(d.headers);i?.headers&&new Headers(i.headers).forEach((A,_)=>h.set(_,A)),k&&k!=="default"&&!h.has("x-taskforce-workspace-id")&&(h.set("x-taskforce-workspace-id",k),h.set("x-taskforce-workspace-authoritative","1"));const g=new Request(d,{...i,headers:h});return s(g)}const S=new Headers(i?.headers);return k&&k!=="default"&&!S.has("x-taskforce-workspace-id")&&(S.set("x-taskforce-workspace-id",k),S.set("x-taskforce-workspace-authoritative","1")),s(d,{...i,headers:S})}),()=>{window.fetch=s}},[e,t,n])}const cd=12e3,Ab=3e4,xb=2e4;function Mu(e){return e==="cloud"?Ab:cd}function bh(){return typeof performance<"u"?performance.now():Date.now()}function Ib({runtimeConfigReady:e,shouldProbeCloudAuth:t,authSessionResolved:n,resolveCloudAuthUrl:s,authOnlyCloudMode:o,authRequiredError:l,runtimeMode:i,workspaceSelectionScope:d,markBootstrapPhase:m,markBootstrapStalled:y,setRuntimeMode:k,setAuthRequiredForApi:S,setIsAuthenticated:h,setAuthUserId:g,setAuthWorkspaceId:v,setAuthUserEmail:A,setAuthUserDisplayName:_,setAuthUserAvatarUrl:I,setUserGlobalSyncStatus:B,setUserGlobalSyncError:V,setHasBetaAccess:L,setAvailableWorkspaces:J,setHydratedWorkspaceRole:me,setAssigneeOptions:ve,setAuthBlocked:re,setAuthSessionResolved:x,setError:K,applyResolvedWorkspaceId:ue,readPersistedWorkspaceId:pe,authSessionRequestRef:X,authSessionEpochRef:M,authSessionLastCheckedAtRef:O,authSessionLastResultRef:de,isLoopbackHost:ge,setAuthStateReadyRefs:$}){const _e=r.useCallback(async se=>{const ce=se?.force===!0;if(m("auth"),!e)return de.current;if(!t)return k("local"),S(!1),h(!1),g("anonymous"),v(""),od(null),A(""),_(""),I(""),B("disconnected"),V(null),L(!0),J([]),me(null),ve(si()),re(!1),x(!0),$(!1,!0,!1),de.current=!1,O.current=Date.now(),!1;const Re=s("/api/taskforce/auth/session"),Pe=Date.now();if(!ce&&X.current)return X.current;if(!ce&&n&&Pe-O.current<1500)return de.current;const Ce=++M.current;let Ee=null;return Ee=(async()=>{const U=bh(),T=new AbortController,b=typeof window<"u"?window.setTimeout(()=>T.abort(),xb):null,j=()=>M.current!==Ce,D=(te,P)=>{zt(te,{durationMs:Math.max(0,Math.round(bh()-U)),force:ce,sessionUrl:Re,...P})};try{const te=await fetch(Re,{method:"GET",credentials:"include",mode:"cors",signal:T.signal});if(j())return de.current;if(te.status===429)return x(!0),$(de.current,!0,!1),D("auth_session_rate_limited",{status:te.status}),de.current;if(!te.ok)return j()?de.current:(ge&&od(null),x(!0),$(!1,!0,!1),de.current=!1,D("auth_session_request_failed",{status:te.status}),!1);const P=await te.json();if(j())return de.current;const H=!!P.authRequiredForApi,be=!!P.authenticated,z=be?P.betaAccess!==!1:!0,ie=typeof P.workspaceId=="string"&&P.workspaceId.trim().length>0?P.workspaceId.trim():"",ee=typeof P.userId=="string"&&P.userId.trim().length>0?P.userId.trim():"anonymous",Q=typeof P.email=="string"&&P.email.trim().length>0?P.email.trim().toLowerCase():"",q=typeof P.displayName=="string"?P.displayName.trim():"",Se=typeof P.avatarUrl=="string"?P.avatarUrl.trim():"",we=i==="local",Te=i==="local"||o,Me=o||we?!1:H;return S(Me),h(be),g(be?ee:"anonymous"),v(be?ie:""),ge&&od(be?ee:null),A(be?Q:""),_(be?q:""),I(be?Se:""),be&&K(nt=>nt===l?"":nt),B(be?"idle":"disconnected"),V(null),L(z),Te||ue(ie||pe(d)||"default",{preserveNonDefaultDefault:!0}),re(o||we?!1:H&&!be),x(!0),$(be,!0,Me),de.current=be,be&&m("ready"),D("auth_session_resolved",{status:te.status,authenticated:be,workspaceId:be?ie:"",userId:be?ee:"anonymous",authRequiredForApi:Me}),be}catch(te){return j()||(ge&&od(null),x(!0),$(!1,!0,!1),de.current=!1,y("Unable to verify your session."),D("auth_session_exception",{error:te instanceof Error?te.message:String(te)})),de.current}finally{b!==null&&typeof window<"u"&&window.clearTimeout(b),j()||(O.current=Date.now()),Ee&&X.current===Ee&&(X.current=null)}})(),X.current=Ee,Ee},[e,t,n,s,o,l,i,d,m,y,k,S,h,g,v,A,_,I,B,V,L,J,me,ve,re,x,K,ue,pe,X,M,O,de,ge,$]),je=i==="local"&&ge&&t?mf():"";return r.useEffect(()=>{je&&(h(!0),x(!0),g(je),$(!0,!0,!1),de.current=!0)},[je,x,$,g,h,de]),r.useEffect(()=>{if(i!=="local"||!t||typeof window>"u")return;const se=()=>{_e()},ce=()=>{document.visibilityState==="visible"&&se()};window.addEventListener("focus",se),window.addEventListener("online",se),document.addEventListener("visibilitychange",ce);const Re=window.setInterval(se,3e4);return()=>{window.removeEventListener("focus",se),window.removeEventListener("online",se),document.removeEventListener("visibilitychange",ce),window.clearInterval(Re)}},[i,t,_e]),{checkAuthSession:_e}}function Tb(e){const t=e.runtimeMode==="cloud",n=!!(e.shouldGateProtectedApiCalls&&t&&!e.authSessionResolved),s=!!(e.shouldGateProtectedApiCalls&&t&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:n,shouldBlockProtectedApiCalls:s,canCallProtectedApi:!(n||s)}}function Rb(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function jb(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}function _h(e){if(!Array.isArray(e))return;const t=e.filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());return t.length>0?t:void 0}function Nb(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Array.isArray(t.categories)||Array.isArray(t.types)||Array.isArray(t.priorities)||Array.isArray(t.taxonomies)||!!t.displayLabels&&typeof t.displayLabels=="object"&&!Array.isArray(t.displayLabels)}function Pb(e){const t=e||{};return{categories:Array.isArray(t.categories)?t.categories.map(s=>typeof s=="string"?{value:s.toLowerCase().replace(/\s+/g,"-"),label:s}:s):[],types:Array.isArray(t.types)?t.types.map(s=>({...wv(s.value),...s,aliases:Array.isArray(s.aliases)?s.aliases.filter(l=>typeof l=="string"&&l.trim().length>0).map(l=>l.trim()):void 0,status:s.status==="retired"?"retired":"active"})):[],priorities:Array.isArray(t.priorities)?t.priorities:[],taxonomies:Array.isArray(t.taxonomies)?t.taxonomies.map(s=>({...s,aliases:_h(s.aliases),options:Array.isArray(s.options)?s.options.map(o=>({...o,aliases:_h(o.aliases),status:o.status==="retired"?"retired":"active"})):[],status:s.status==="retired"?"retired":"active",formEnabled:s.formEnabled!==!1,filterEnabled:s.filterEnabled!==!1,sortEnabled:s.sortEnabled===!0})):[],displayLabels:{category:typeof t.displayLabels?.category=="string"&&t.displayLabels.category.trim().length>0?t.displayLabels.category.trim():void 0,type:typeof t.displayLabels?.type=="string"&&t.displayLabels.type.trim().length>0?t.displayLabels.type.trim():void 0,priority:typeof t.displayLabels?.priority=="string"&&t.displayLabels.priority.trim().length>0?t.displayLabels.priority.trim():void 0}}}function qa(){return typeof performance<"u"?performance.now():Date.now()}function Mb(e){const{shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:n,getWorkspaceRequestState:s,isWorkspaceRequestStale:o,isWorkspaceEpochStale:l,isAbortError:i,isBootstrapTimeoutError:d,fetchWithTimeout:m,handleUnauthorized:y,applyBootstrapConfig:k,loadPersistedUiState:S,fetchBuildInfo:h,markBootstrapPhase:g,markBootstrapStalled:v,fetchWorkflows:A,fetchInitiativeTemplates:_,loadAvailableEnvironments:I,setReferenceDataLoaded:B,setCustomCategories:V,setCustomTypes:L,setPriorities:J,setTaxonomies:me,setTaxonomyDisplayLabels:ve,setConfigLoaded:re,hasLoadedUiStateRef:x,currentWorkspaceIdRef:K,referenceDataRequestRef:ue,referenceDataAbortRef:pe,bootstrapConfigAbortRef:X,workspaceListAbortRef:M,assigneeOptionsAbortRef:O,workspaceListHydratedRef:de,setAvailableWorkspaces:ge,runtimeMode:$,applyResolvedWorkspaceId:_e,workspaceSwitchingEnabled:je,authSessionResolved:se,isAuthenticated:ce,authUserId:Re,authUserAvatarUrl:Pe,setHydratedWorkspaceRole:Ce,setAssigneeOptions:Ee,setAssigneeOptionsLoaded:U,commitCurrentWorkspaceId:T,currentWorkspaceId:b,workspaceSelectionScope:j,abortWorkspaceScopedRequests:D,setWorkspaceBootstrapPending:te,checkAuthSession:P,lastConfigRefreshKeyRef:H,lastAssigneeOptionsLoadKeyRef:be,lastWorkspaceSyncStateLoadKeyRef:z,lastTaskSurfaceLoadKeyRef:ie,lastSettingsSurfaceLoadKeyRef:ee,isOpen:Q,activeTab:q,showArchive:Se,taskScope:we,settingsSection:Te,workspaceBootstrapPending:Me,fetchTasks:nt,fetchArchive:gt,fetchPlanningEntities:lt,refreshTaskCollections:St,loadWorkspaceSyncState:Ke,archiveBootstrapTimerRef:Ct,hasBootstrappedDataRef:dt}=e,Xe=r.useCallback(async Be=>{const et=Be?.ignoreAuthGuard===!0,Ue=Be?.force===!0;if(!et&&(t||n)){zt("bootstrap_reference_data_skipped",{reason:n?"auth_blocked":"auth_deferred",runtimeMode:$,workspaceId:String(s().workspaceId||"").trim()||"default",force:Ue});return}const Qe=s(),yt=String(Qe.workspaceId||"").trim()||"default";if(!($!=="cloud"||!se||!ce||yt!==""&&yt!=="default")){zt("bootstrap_reference_data_skipped",{reason:"workspace_unresolved",runtimeMode:$,workspaceId:yt,force:Ue});return}if(!Ue&&ue.current?.workspaceId===Qe.workspaceId){zt("bootstrap_reference_data_reused",{workspaceId:yt,force:Ue}),await ue.current.promise;return}B(!1);const ae=qa(),ze=new AbortController;pe.current=ze;const bt=(async()=>{await Promise.allSettled([(async()=>{let Ot="empty-taxonomy-state";const Bt=await fetch("/api/taskforce/taxonomy-state",{signal:ze.signal});if(!Bt.ok)return;const Oe=await Bt.json().catch(()=>({}));if(Nb(Oe))Ot="taxonomy-state";else{Ot="fallback-endpoints";const[vt,E,c,Y]=await Promise.all([fetch("/api/taskforce/categories",{signal:ze.signal}),fetch("/api/taskforce/types",{signal:ze.signal}),fetch("/api/taskforce/priorities",{signal:ze.signal}),fetch("/api/taskforce/taxonomies",{signal:ze.signal})]),[ye,Ie,He,Ve]=await Promise.all([vt.ok?vt.json().catch(()=>({})):Promise.resolve({}),E.ok?E.json().catch(()=>({})):Promise.resolve({}),c.ok?c.json().catch(()=>({})):Promise.resolve({}),Y.ok?Y.json().catch(()=>({})):Promise.resolve({})]);Oe.categories=ye.categories,Oe.types=Ie.types,Oe.priorities=He.priorities,Oe.taxonomies=Ve.taxonomies}const Lt=Pb(Oe);if(o(Qe)){zt("bootstrap_reference_data_stale_drop",{workspaceId:yt,source:Ot});return}Lt.categories.length>0&&V(Lt.categories),Lt.types.length>0&&L(Lt.types),Lt.priorities.length>0&&J(Lt.priorities),me(Lt.taxonomies),ve(Lt.displayLabels||{}),zt("bootstrap_reference_data_source",{workspaceId:yt,source:Ot,categories:Lt.categories.length,types:Lt.types.length,priorities:Lt.priorities.length,taxonomies:Lt.taxonomies.length})})(),A(),_(),I()]),!o(Qe)&&(B(!0),zt("bootstrap_reference_data_loaded",{durationMs:Math.max(0,Math.round(qa()-ae)),workspaceId:yt,force:Ue}))})();ue.current={workspaceId:Qe.workspaceId,promise:bt};try{await bt}finally{ue.current?.promise===bt&&(ue.current=null),pe.current===ze&&(pe.current=null)}},[se,_,A,s,ce,o,I,pe,ue,$,V,L,J,B,me,ve,n,t]),ct=r.useCallback(async Be=>{if(!(Be?.ignoreAuthGuard===!0)&&(t||n))return;g("config");const Ue=s(),Qe=qa(),yt=new AbortController;X.current=yt;try{const ot=await m("/api/taskforce/config",void 0,Mu($),{signal:yt.signal});if(l(Ue))return;if(ot.status===401){y(),re(!0);return}let ae="";if(ot.ok){const ze=await ot.json();if(l(Ue))return;ae=typeof ze?.workspaceId=="string"&&ze.workspaceId.trim().length>0?ze.workspaceId.trim():"",k(ze)}if(l(Ue)){const ze=String(K.current||"default").trim()||"default";if(!ae||ze!==ae)return}if(x.current||(x.current=!0,await S(ae||Ue.workspaceId)),l(Ue)){const ze=String(K.current||"default").trim()||"default";if(!ae||ze!==ae)return}re(!0),g("ready"),zt("bootstrap_config_loaded",{durationMs:Math.max(0,Math.round(qa()-Qe)),status:ot.status,workspaceId:ae||Ue.workspaceId}),h()}catch(ot){if(i(ot)||l(Ue))return;x.current||(x.current=!0,await S(Ue.workspaceId)),v(d(ot)?"Startup checks timed out.":"Unable to finish startup checks."),re(!0),zt("bootstrap_config_failed",{durationMs:Math.max(0,Math.round(qa()-Qe)),workspaceId:Ue.workspaceId,error:ot instanceof Error?ot.message:String(ot)})}finally{X.current===yt&&(X.current=null)}},[k,X,K,h,m,s,y,x,i,d,l,S,g,v,$,re,n,t]),ne=r.useCallback(async Be=>{await ct(Be),await Xe(Be)},[ct,Xe]),st=r.useCallback(()=>{typeof window>"u"||(Ct.current!==null&&window.clearTimeout(Ct.current),Ct.current=window.setTimeout(()=>{Ct.current=null,gt(!0).then(()=>zt("bootstrap_archive_loaded_deferred",{}))},1500))},[Ct,gt]),Ye=r.useCallback(async()=>{if(!je)return ge([]),de.current=!1,{success:!0,workspaces:[]};const Be=s(),et=qa(),Ue=new AbortController;M.current=Ue;try{const Qe=await m("/api/taskforce/workspaces",{method:"GET",credentials:"include"},Mu($),{signal:Ue.signal});if(l(Be))return{success:!1,error:"Workspace changed while loading workspaces."};if(Qe.status===401)return ge([]),de.current=!1,{success:!1,error:"Authentication required."};const yt=await Qe.json().catch(()=>({}));if(l(Be))return{success:!1,error:"Workspace changed while loading workspaces."};if(!Qe.ok||yt?.success===!1)return ge([]),de.current=!1,{success:!1,error:yt?.error||`Failed to load workspaces (${Qe.status})`};const ot=Array.isArray(yt?.workspaces)?yt.workspaces.map(ae=>({id:String(ae?.id||"").trim(),name:String(ae?.name||"").trim(),role:String(ae?.role||"member").trim().toLowerCase(),slug:typeof ae?.slug=="string"?ae.slug:null,description:typeof ae?.description=="string"?ae.description:null,status:typeof ae?.status=="string"?ae.status:"",betaAccess:ae?.betaAccess===!0})).filter(ae=>ae.id&&ae.name):[];return ge(ot),de.current=!0,$!=="local"&&typeof yt?.currentWorkspaceId=="string"&&yt.currentWorkspaceId.trim().length>0&&_e(yt.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),zt("bootstrap_workspaces_loaded",{durationMs:Math.max(0,Math.round(qa()-et)),workspaceId:Be.workspaceId,count:ot.length,status:Qe.status}),{success:!0,workspaces:ot}}catch(Qe){return d(Qe)&&v("Startup checks timed out."),ge([]),de.current=!1,zt("bootstrap_workspaces_failed",{durationMs:Math.max(0,Math.round(qa()-et)),workspaceId:Be.workspaceId,error:Qe instanceof Error?Qe.message:String(Qe)}),{success:!1,error:i(Qe)?"Workspace list request aborted.":"Failed to load workspaces."}}finally{M.current===Ue&&(M.current=null)}},[_e,m,s,i,d,l,v,$,ge,M,de,je]),Pt=r.useCallback(async()=>{const Be=s(),et=qa(),Ue=new AbortController;O.current=Ue,U(!1);try{const[Qe,yt]=await Promise.all([m("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},Mu($),{signal:Ue.signal}),se&&ce?m("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},Mu($),{signal:Ue.signal}).catch(()=>null):Promise.resolve(null)]);if(o(Be))return{success:!1,error:"Workspace changed while loading assignee options."};if(Qe.status===401)return Ee(si()),U(!0),{success:!1,error:"Authentication required."};const ot=await Qe.json().catch(()=>({}));if(o(Be))return{success:!1,error:"Workspace changed while loading assignee options."};if(!Qe.ok)return Ee(si()),U(!0),{success:!1,error:ot?.error||`Failed to load assignee options (${Qe.status})`};const ae=String(Re||"").trim(),ze=String(Pe||"").trim(),bt=(E,c)=>{const Y=typeof E?.avatarUrl=="string"&&E.avatarUrl.trim().length>0?E.avatarUrl.trim():"";if(Y)return Y;const ye=String(E?.userId||c||"").trim();return ae&&ye===ae&&ze?ze:null},Ot=Array.isArray(ot?.assignees)?ot.assignees:[],Bt=Ot.map(E=>{const c=String(E?.value||"").trim(),Y=String(E?.kind||"").trim().toLowerCase();return c?Y==="agent"||Y==="ai"?{value:c,label:String(E?.label||c).trim()||c,icon:String(E?.icon||"Bot"),color:String(E?.color||"#8b5cf6"),kind:"agent",avatarUrl:typeof E?.avatarUrl=="string"&&E.avatarUrl.trim().length>0?E.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(E?.avatarRevision))?Math.max(0,Math.floor(Number(E.avatarRevision))):null,avatarUpdatedAt:typeof E?.avatarUpdatedAt=="string"&&E.avatarUpdatedAt.trim().length>0?E.avatarUpdatedAt.trim():null,username:typeof E?.username=="string"&&E.username.trim().length>0?E.username.trim():null,archivedAt:typeof E?.archivedAt=="string"&&E.archivedAt.trim().length>0?E.archivedAt.trim():null,createdAt:typeof E?.createdAt=="string"&&E.createdAt.trim().length>0?E.createdAt.trim():null,updatedAt:typeof E?.updatedAt=="string"&&E.updatedAt.trim().length>0?E.updatedAt.trim():null}:Y==="member"||Y==="human"?{value:c,label:String(E?.label||c).trim()||c,icon:String(E?.icon||"User"),color:String(E?.color||"#22c55e"),kind:"member",avatarUrl:bt(E,c)}:null:null}).filter(Boolean),Oe=Ot.map(E=>({userId:String(E?.userId||"").trim(),email:String(E?.email||"").trim().toLowerCase(),displayName:typeof E?.displayName=="string"?E.displayName:null,avatarUrl:bt(E)})).filter(E=>E.userId);let Lt=Oe;if(yt?.ok){const E=await yt.json().catch(()=>({})),c=Array.isArray(E?.users)?E.users:[],Y=c.find(He=>String(He?.userId||"").trim()===ae),ye=String(Y?.role||"").trim().toLowerCase();ye==="owner"||ye==="admin"||ye==="member"||ye==="read-only"?Ce(ye):!je&&c.length===0&&Ce(null);const Ie=c.map(He=>({userId:String(He?.userId||"").trim(),email:String(He?.email||"").trim().toLowerCase(),displayName:typeof He?.displayName=="string"?He.displayName:null,avatarUrl:bt(He)})).filter(He=>He.userId);Lt=Array.from(new Map([...Oe,...Ie].map(He=>[He.userId,He])).values())}else!je&&!Oe.length&&Ce(null);const vt=wd([...Bt,...cS(Lt).filter(E=>E.kind==="member")]);return o(Be)?{success:!1,error:"Workspace changed while loading assignee options."}:(Ee(vt),U(!0),zt("bootstrap_assignee_options_loaded",{durationMs:Math.max(0,Math.round(qa()-et)),workspaceId:Be.workspaceId,count:vt.length}),{success:!0})}catch(Qe){return o(Be)||(Ee(si()),U(!0)),zt("bootstrap_assignee_options_failed",{durationMs:Math.max(0,Math.round(qa()-et)),workspaceId:Be.workspaceId,error:Qe instanceof Error?Qe.message:String(Qe)}),{success:!1,error:i(Qe)?"Assignee options request aborted.":"Failed to load assignee options."}}finally{O.current===Ue&&(O.current=null)}},[O,se,Pe,Re,m,s,i,ce,o,$,Ee,U,Ce,je]),kt=r.useCallback(async(Be,et)=>{if(!je)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const Ue=String(Be||"").trim();if(!Ue)return{success:!1,error:"workspaceId is required."};const Qe=String(K.current||"").trim()||"default",yt=qa();try{zt("bootstrap_workspace_switch_started",{fromWorkspaceId:Qe,toWorkspaceId:Ue,hydrate:et?.hydrate!==!1});const ot=await fetch("/api/taskforce/session/workspace",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Ue})}),ae=await ot.json().catch(()=>({}));if(!ot.ok||ae?.success===!1)return{success:!1,error:ae?.error||`Failed to switch workspace (${ot.status})`,code:ae?.code};T(Ue,{clearExplicitSelection:!1}),D(),te(!0),g("workspace");const ze=await P({force:!0});return et?.hydrate===!1?await Ye():(H.current=`${$}:${Ue}:${j}`,be.current=`${$}:${ze?"auth":"guest"}:${Ue}`,z.current=Ue,Q&&q==="tasks"&&(ie.current=`${Ue}:${q}:${Se?"archive":"active"}:${we}`),Q&&q==="settings"&&(ee.current=`${Ue}:${q}:${Te}`),await Promise.all([ne(),Ye(),St({isSilent:!1}),Ke()]),lt({ignoreAuthGuard:!0})),zt("bootstrap_workspace_switch_completed",{fromWorkspaceId:Qe,toWorkspaceId:Ue,hydrate:et?.hydrate!==!1,durationMs:Math.max(0,Math.round(qa()-yt))}),{success:!0}}catch(ot){return zt("bootstrap_workspace_switch_failed",{fromWorkspaceId:Qe,toWorkspaceId:Ue,hydrate:et?.hydrate!==!1,durationMs:Math.max(0,Math.round(qa()-yt)),error:ot instanceof Error?ot.message:String(ot)}),{success:!1,error:"Failed to switch workspace."}}finally{te(!1)}},[D,q,P,T,K,ne,lt,Ye,Q,be,H,ee,ie,z,Ke,g,St,$,Te,te,Se,we,j,je]),It=r.useCallback(async Be=>{g("workspace"),te(!0);try{if(!je){const bt=String(b||"").trim()||"default";return T(bt),{success:!0,workspaceSetupRequired:!1,workspaceId:bt}}const et=String(Be?.preferredWorkspaceId||"").trim(),Ue=Dp(j),Qe=await Ye();if(!Qe.success)return{success:!1,workspaceSetupRequired:!1,error:Qe.error||"Failed to load workspaces after authentication."};const yt=Array.isArray(Qe.workspaces)?Qe.workspaces:[];if(yt.length===0)return T("default"),{success:!0,workspaceSetupRequired:!0};const ot=new Set(yt.map(bt=>String(bt.id||"").trim()).filter(Boolean)),ae=String(K.current||"").trim(),ze=(et&&ot.has(et)?et:"")||(ae&&ot.has(ae)?ae:"")||(Ue&&ot.has(Ue)?Ue:"")||String(yt[0]?.id||"").trim();if(!ze)return T("default"),{success:!0,workspaceSetupRequired:!0};if(ae!==ze){const bt=await kt(ze,{hydrate:!1});if(!bt.success)return{success:!1,workspaceSetupRequired:!1,error:bt.error||"Failed to set workspace after authentication.",code:bt.code}}else T(ze);return{success:!0,workspaceSetupRequired:!1,workspaceId:ze}}catch{return v("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{te(!1)}},[T,b,K,Ye,g,v,te,kt,j,je]),Ft=r.useCallback(async()=>{g("auth");const Be=qa();zt("bootstrap_retry_started",{workspaceId:String(K.current||"default").trim()||"default"});const et=await P({force:!0});let Ue=!1;if(je&&et){const Qe=await It();if(!Qe.success||Qe.workspaceSetupRequired){await ne({ignoreAuthGuard:!0}),zt("bootstrap_retry_completed",{workspaceId:String(K.current||"default").trim()||"default",authenticated:et,workspaceSetupRequired:Qe.workspaceSetupRequired===!0,success:Qe.success,durationMs:Math.max(0,Math.round(qa()-Be))});return}}te(!0);try{await ne({ignoreAuthGuard:!0}),et&&!Ue&&(await Promise.all([nt(!0,{ignoreAuthGuard:!0}),Xe({ignoreAuthGuard:!0,force:!0})]),lt({ignoreAuthGuard:!0})),zt("bootstrap_retry_completed",{workspaceId:String(K.current||"default").trim()||"default",authenticated:et,workspaceSetupRequired:Ue,success:!0,durationMs:Math.max(0,Math.round(qa()-Be))})}finally{te(!1)}},[P,K,ne,lt,Xe,nt,g,It,te,je]),Mt=r.useCallback(async Be=>{const et=Be?.reason||"initial-load",Ue=Be?.ignoreAuthGuard===!0,Qe=Be?.tasksSilent!==!1,yt=Be?.includeDeferredArchive!==!1,ot=qa();if(g("auth"),!await P({force:!0}))return await ne({ignoreAuthGuard:!0}),zt("cloud_bootstrap_completed",{reason:et,durationMs:Math.max(0,Math.round(qa()-ot)),authenticated:!1,workspaceSetupRequired:!1,success:!1}),{success:!1,authenticated:!1,workspaceSetupRequired:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};if(je){const ze=await It();if(!ze.success)return await ne({ignoreAuthGuard:!0}),zt("cloud_bootstrap_completed",{reason:et,durationMs:Math.max(0,Math.round(qa()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!1,error:ze.error||"Workspace resolution failed."}),{success:!1,authenticated:!0,workspaceSetupRequired:!1,error:ze.error||"Unable to resolve workspace access.",code:ze.code};if(ze.workspaceSetupRequired)return await ne({ignoreAuthGuard:!0}),zt("cloud_bootstrap_completed",{reason:et,durationMs:Math.max(0,Math.round(qa()-ot)),authenticated:!0,workspaceSetupRequired:!0,success:!0}),{success:!0,authenticated:!0,workspaceSetupRequired:!0}}te(!0);try{return await ct({ignoreAuthGuard:Ue}),await Promise.all([nt(Qe,{ignoreAuthGuard:Ue}),Xe({ignoreAuthGuard:Ue})]),lt({ignoreAuthGuard:Ue}),yt&&st(),zt("cloud_bootstrap_completed",{reason:et,durationMs:Math.max(0,Math.round(qa()-ot)),authenticated:!0,workspaceSetupRequired:!1,success:!0,workspaceId:String(K.current||"default").trim()||"default"}),{success:!0,authenticated:!0,workspaceSetupRequired:!1}}finally{te(!1)}},[P,K,ct,lt,Xe,nt,g,It,st,te,je]);return r.useEffect(()=>{!t&&!n&&!dt.current&&(dt.current=!0,(async()=>{const Be=qa();if($==="cloud"&&se&&ce){const et=await Mt({reason:"initial-load",tasksSilent:!1,includeDeferredArchive:!0});if(!et.success||et.workspaceSetupRequired)return}else await Promise.all([ct(),nt(!1),Xe()]),lt();$!=="cloud"&&st(),zt("bootstrap_initial_load_completed",{durationMs:Math.max(0,Math.round(qa()-Be)),runtimeMode:$,workspaceId:String(K.current||"default").trim()||"default"})})())},[se,K,ct,lt,Xe,nt,dt,ce,Mt,$,st,n,t]),r.useEffect(()=>{if(t||n||Me||j==="bootstrap"||!dt.current)return;const Be=`${$}:${b}:${j}`;H.current!==Be&&(H.current=Be,ne())},[b,ne,dt,H,$,n,t,Me,j]),r.useEffect(()=>{if(t||n||Me)return;const Be=b;z.current!==Be&&(z.current=Be,Ke())},[b,z,Ke,n,t,Me]),r.useEffect(()=>{if($!=="cloud"||!se||!ce){$!=="cloud"&&ge([]),de.current=!1;return}Me||!dt.current||de.current||Ye()},[se,Ye,dt,ce,$,ge,Me,de]),{fetchReferenceData:Xe,fetchBootstrapConfig:ct,fetchConfig:ne,fetchWorkspaces:Ye,fetchAssigneeOptions:Pt,switchWorkspace:kt,resolveWorkspaceAfterAuth:It,retryBootstrapChecks:Ft,runCloudBootstrap:Mt}}function Eb({isOpen:e,authBlocked:t,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:o,shouldGateProtectedApiCalls:l,authSessionResolvedRef:i,authRequiredForApiRef:d,isAuthenticatedRef:m,dataVersionRef:y,refreshTaskCollectionsForDataVersion:k}){r.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||Rb({isOpen:e,authBlocked:t,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:o}))return;let S=!1;const h=async()=>{if(!(S||document.visibilityState!=="visible")&&!jb({shouldGateProtectedApiCalls:l,authSessionResolved:i.current,authRequiredForApi:d.current,isAuthenticated:m.current}))try{const A=await fetch("/api/taskforce/data-version");if(!A.ok)return;const _=await A.json(),I=Number(_?.dataVersion);if(!Number.isFinite(I))return;if(y.current===null){y.current=I;return}I!==y.current&&(y.current=I,await k())}catch{}},g=()=>{document.visibilityState==="visible"&&h()},v=window.setInterval(()=>{h()},3e3);return document.addEventListener("visibilitychange",g),h(),()=>{S=!0,window.clearInterval(v),document.removeEventListener("visibilitychange",g)}},[e,t,n,s,o,l,i,d,m,y,k])}const Db={};function ti(e,t){const n=e.findIndex(s=>s.id===t.id);return n===-1?[...e,t]:e.map((s,o)=>o===n?t:s)}const To=lf(Db),kp=(()=>{const e=To.baseUrl,t=To.cloudAuthBaseUrl;if(t)return t;const n=To.apiBaseUrl;return n||e||"https://app.taskforcehq.ai"})(),Eu=2e4,Lb=new Set(["external-abort","superseded","workspace-reset","workspace-transition"]);function Hu(e){return typeof DOMException<"u"&&e instanceof DOMException?e.name==="AbortError":String(e?.name||"").toLowerCase()==="aborterror"}function Hp(e){return typeof e=="string"&&Lb.has(e)}function vp(e,t){return t.aborted?e===t.reason||Hp(e)||Hp(t.reason)?!0:Hu(e):!1}function Ch(e){const t=new Error(`Startup checks timed out after ${e}ms.`);return t.name="BootstrapTimeoutError",t}function Ah(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.initiatives)?t.initiatives.filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string")):[],s=Array.isArray(t.workstreams)?t.workstreams.filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string")):[],o=Array.isArray(t.workstreamTaskSummaries)?t.workstreamTaskSummaries.flatMap(l=>{if(!l||typeof l!="object")return[];const i=String(l.workstreamId||"").trim();if(!i)return[];const d=Array.isArray(l.tasks)?l.tasks:[],m=Math.max(0,Number(l.taskCount)||0),y=Math.max(0,Number(l.completedTaskCount)||0);return[{workstreamId:i,taskCount:m,completedTaskCount:y,tasks:d.filter(k=>!!(k&&typeof k=="object"&&typeof k.id=="string")).map(k=>({id:String(k.id||"").trim(),referenceNumber:typeof k.referenceNumber=="number"?k.referenceNumber:null,title:String(k.title||"").trim()||"Untitled Task",status:typeof k.status=="string"?k.status:null}))}]}):[];return{initiatives:n,workstreams:s,workstreamTaskSummaries:o}}function Bb({config:e={},initialTaskId:t,onTaskCountChange:n,onClose:s}){const o={...Cv,...e},{categories:l,types:i,apiEndpoint:d,apiBaseUrl:m,cloudAuthBaseUrl:y,cloudMcpBaseUrl:k,wsBaseUrl:S,shortcut:h}=o,g=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",v=g==="localhost"||g==="127.0.0.1"||g==="::1",A=typeof window<"u"&&!v,[_,I]=r.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null}),[B,V]=r.useState(!1),L=r.useCallback(f=>typeof f=="string"?f.trim().replace(/\/+$/,""):"",[]);r.useEffect(()=>{if(typeof window>"u"){V(!0);return}let f=!1;return(async()=>{try{const W=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include"});if(!W.ok)return;const F=await W.json().catch(()=>({})),Z=F?.config&&typeof F.config=="object"?F.config:{};if(f)return;const Le=String(Z.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",Ge=String(Z.workspaceMode||"").trim(),ha=Ge==="single-local"||Ge==="multi-cloud"?Ge:Le==="cloud"?"multi-cloud":"single-local";j(Le),I({cloudEnvironment:typeof Z.cloudEnvironment=="string"?String(Z.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:L(Z.cloudBaseUrl),cloudMcpBaseUrl:L(Z.cloudMcpBaseUrl),baseUrl:L(Z.baseUrl),apiBaseUrl:L(Z.apiBaseUrl),cloudAuthBaseUrl:L(Z.cloudAuthBaseUrl),wsBaseUrl:L(Z.wsBaseUrl),cloudAuthViaLocalProxy:!!Z.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:ha,workspaceSwitchingEnabled:typeof Z.workspaceSwitchingEnabled=="boolean"?!!Z.workspaceSwitchingEnabled:ha==="multi-cloud"})}catch{}finally{f||V(!0)}})(),()=>{f=!0}},[L]);const J=typeof window>"u"?"":v?kp:"",me=L(To.baseUrl),ve=L(To.apiBaseUrl),re=L(To.cloudBaseUrl),x=L(To.cloudMcpBaseUrl),K=L(To.cloudAuthBaseUrl),ue=L(To.wsBaseUrl),pe=L(m),X=L(y),M=L(k),O=_.apiBaseUrl||_.baseUrl,ge=pe||O||(v?"":ve||me)||"",$=X||K||me,_e=_.cloudAuthBaseUrl||_.baseUrl,se=((v?_e||$:$||_e)||ge||J).trim().replace(/\/+$/,""),ce=L(eS(_.cloudMcpBaseUrl||_.cloudAuthBaseUrl||_.cloudBaseUrl||M||X||x||K||re||se)),Re=(_.cloudMcpBaseUrl||M||ce||_.cloudBaseUrl||x||re||se||J).trim().replace(/\/+$/,""),Pe=!A&&!!se&&!ge,Ce=A||B&&!!(se||ge),Ee=Ce&&!Pe,U=!!(se||ge||A),T=A?"cloud":"local",[b,j]=r.useState(()=>T),D=T==="local"&&v&&U?mf():"",te=D.length>0,P=r.useCallback(f=>!f||/^https?:\/\//i.test(f)||!ge||!f.startsWith("/")?f:`${ge}${f}`,[ge]),H=r.useCallback(f=>{if(!f||/^https?:\/\//i.test(f)||!f.startsWith("/"))return f;const W=f.startsWith("/api/taskforce/auth/")||f.startsWith("/api/taskforce/account/")||f.startsWith("/api/taskforce/billing/")||f.startsWith("/api/taskforce/sync/")||f.startsWith("/api/taskforce/settings/mcp/");if(!A&&W&&(b==="cloud"||!B||_.cloudAuthViaLocalProxy||_.workspaceMode==="multi-cloud"))return f;const F=se||ge;if(F){const Z=`${F}${f}`;if(typeof window<"u"&&!A&&W)try{if(new URL(Z,window.location.origin).origin===window.location.origin)return`${kp}${f}`}catch{return`${kp}${f}`}return Z}return f},[B,_.cloudAuthViaLocalProxy,_.workspaceMode,se,ge,A,b]),be=r.useCallback(f=>{const W=String(f||"").trim()||"/taskforce-ws",F=W.startsWith("/")?W:`/${W}`,Z=String(S||_.wsBaseUrl||ue||ge||"").trim().replace(/\/+$/,""),We=typeof window<"u"?window.location.origin:"",Le=Z||We;if(!Le)return"";try{const Ge=new URL(F,Le);return Ge.protocol==="https:"&&(Ge.protocol="wss:"),Ge.protocol==="http:"&&(Ge.protocol="ws:"),Ge.toString()}catch{return""}},[S,_.wsBaseUrl,ue,ge]),[z,ie]=r.useState("tasks"),[ee,Q]=r.useState(!1),[q,Se]=r.useState(!1),[we,Te]=r.useState("open"),[Me,nt]=r.useState(Vc(o.theme)||Ju),[gt,lt]=r.useState(Vc(o.theme)||Ju),[St,Ke]=r.useState(!0),[Ct]=r.useState(".taskforce"),dt=!1,[Xe,ct]=r.useState(!1),[ne,st]=r.useState([]),[Ye,Pt]=r.useState([]),[kt,It]=r.useState(""),[Ft,Mt]=r.useState(null),[Be,et]=r.useState(null),[Ue,Qe]=r.useState(""),[yt,ot]=r.useState(""),ae=r.useMemo(()=>qv({projectRoot:Ue,runtimeMode:T}),[Ue,T]),[ze,bt]=r.useState(""),[Ot,Bt]=r.useState(""),Oe=Jv(b),Lt=_.workspaceMode==="single-local"||_.workspaceMode==="multi-cloud"?_.workspaceMode:Oe.workspaceMode,vt=typeof _.workspaceSwitchingEnabled=="boolean"?_.workspaceSwitchingEnabled:Oe.workspaceSwitchingEnabled,[E,c]=r.useState(!1),[Y,ye]=r.useState(!1),[Ie,He]=r.useState(te),[Ve,Ne]=r.useState(te?D:"anonymous"),[Vt,qt]=r.useState(""),[Et,Tt]=r.useState(""),[Wt,Ht]=r.useState(""),[sa,Kt]=r.useState([]),[Ka,Fa]=r.useState(""),[Xa,wa]=r.useState(!0),[he,it]=r.useState(null),[xe,jt]=r.useState(()=>{if(T==="local")return"default";const f=Dp(ae);return f&&f.toLowerCase()!=="default"?f:"default"}),tt=r.useMemo(()=>Kv({projectRoot:Ue,runtimeMode:b,workspaceId:xe}),[Ue,b,xe]),[Gt,ga]=r.useState([]),[Na,ua]=r.useState(()=>si()),[ca,Dt]=r.useState(!1),[aa,Za]=r.useState(te),[$t,Qn]=r.useState("idle"),[ba,Qt]=r.useState(null),[Lr,Ia]=r.useState(null),en=r.useRef(null),Ca=r.useRef(0),Jt=r.useRef(0),Ta=r.useRef(te),la=r.useRef(xe),vn=r.useRef(null),pn=r.useRef(0),Xn=r.useRef((typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`).replace(/[^A-Za-z0-9_-]+/g,"").slice(0,12)||"session"),[ma,_r]=r.useState(0),Br=r.useRef(null),Sn=r.useRef(null),Ba=r.useRef(null),Cr=r.useRef(null),wn=r.useRef(null),Pn=r.useRef(null),tn=r.useRef(null),Aa=r.useCallback((f,W)=>{const F=String(f||"").trim();if(!F)return;const Z=String(la.current||"").trim();Z&&Z!==F&&(pn.current+=1,_r(pn.current)),la.current=F,W?.clearExplicitSelection!==!1&&(vn.current=null),jt(F)},[]);r.useEffect(()=>{la.current=xe},[xe]);const Wr=r.useCallback(f=>{const W=String(f||"").trim();W&&jt(()=>{const F=String(vn.current||"").trim();let Z=W;return F&&F!==W&&(Z=F),la.current=Z,Z})},[]),_t=r.useCallback(()=>({workspaceId:String(la.current||"default").trim()||"default",epoch:pn.current}),[]),bn=r.useCallback(f=>(String(la.current||"default").trim()||"default")!==f.workspaceId||pn.current!==f.epoch,[]),fn=r.useCallback(f=>pn.current!==f.epoch,[]),_n=r.useCallback(f=>Hu(f)||Hp(f),[]),Oa=r.useCallback(()=>{[Br,Sn,Ba,Cr,wn,Pn].forEach(f=>{f.current?.abort("workspace-transition"),f.current=null}),tn.current!==null&&typeof window<"u"&&(window.clearTimeout(tn.current),tn.current=null),jc.current=null},[]),Mn=r.useMemo(()=>Tb({shouldGateProtectedApiCalls:Ee,runtimeMode:b,authSessionResolved:aa,authRequiredForApi:E,isAuthenticated:Ie}),[Ee,b,aa,E,Ie]),ya=Mn.shouldDeferProtectedApiCalls,$a=Mn.shouldBlockProtectedApiCalls,[Cn,da]=r.useState(null),[En,Xt]=r.useState(null),[Ua,_a]=r.useState(!1),[er,tr]=r.useState("unknown"),[Pa,na]=r.useState(null),[pa,hn]=r.useState(o.shortcut||"Alt+T"),[an,fr]=r.useState(o.priorities||[]),[hr]=r.useState(xg()),[ea,Ss]=r.useState(""),[za,ar]=r.useState(!1),[Xr,gn]=r.useState(!1),[zn,Fr]=r.useState(!0),[An,Ha]=r.useState(()=>Hv()),Ar=r.useMemo(()=>zv(),[]),[Ra,ws]=r.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[nn,xr]=r.useState(!1),[gr,Or]=r.useState(!0),[yn,yr]=r.useState(!0),[xn,Dn]=r.useState(""),[nr,es]=r.useState(null);Cb({currentWorkspaceIdRef:la,resolveApiUrl:P,runtimeMode:b});const{availableWorkflows:$r,initiativeTemplates:Je,fetchWorkflows:Ut,fetchInitiativeTemplates:Ma,fetchWorkflowTemplate:oa,fetchWorkflowOverrideNames:cn,saveWorkflowTemplateDraft:rn,resetWorkflowTemplateDraft:bs}=Yw({shouldDeferProtectedApiCalls:ya,shouldBlockProtectedApiCalls:$a}),{zenMode:_s,setZenModeState:ts,toggleZenMode:Ya}=Jw(),{exportEnvironment:Wa,setExportEnvironment:Rt,availableEnvironments:kr,loadAvailableEnvironments:Hn,exportWorkflowsPath:Ln,setExportWorkflowsPath:rr,exportingResource:Cs,exportResult:Ir,handleExportWorkflows:Ur}=Vw({storagePath:Ct,shouldDeferProtectedApiCalls:ya,shouldBlockProtectedApiCalls:$a}),[Fs,Bn]=r.useState(!1),[Wn,G]=r.useState(null),{uiNotice:qe,pushNotice:At,clearNotice:Nt}=Gw(),[Ea,In]=r.useState([]),Tn=r.useRef(null),[Mo,Eo]=r.useState(0),ao=r.useCallback(f=>!f||!Ue?f:f.startsWith(Ue)?f.slice(Ue.length).replace(/^[/\\]+/,""):f,[Ue]),[Ga,vr]=r.useState([]),[Da,R]=r.useState([]),[C,Ze]=r.useState([]),[ht,De]=r.useState([]),[oe,sr]=r.useState([]),[as,sn]=r.useState([]),[oi,or]=r.useState(!1),[ir,ns]=r.useState(null),[nl,rl]=r.useState(!1),[no,ii]=r.useState([]),[Rn,ro]=r.useState(!1),[ci,li]=r.useState({}),di=r.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});r.useEffect(()=>{di.current={authSessionResolved:aa,configLoaded:Rn,workspaceBootstrapPending:ca}},[aa,Rn,ca]);const Tr=r.useCallback(f=>{Qn(f),f!=="ready"&&(Qt(null),Ia(Date.now()))},[]),Do=r.useCallback(f=>{const W=di.current;W.authSessionResolved&&W.configLoaded&&!W.workspaceBootstrapPending||(Qn("stalled"),Qt(f),Ia(F=>F??Date.now()))},[]),rs=r.useCallback(async(f,W,F=cd,Z)=>{const We=new AbortController,Le=Z?.signal,Ge=Number(F)>0?Number(F):cd,ha=_t(),va=f.startsWith("/api/taskforce/")?pp(W,th({workspaceId:ha.workspaceId,epoch:ha.epoch,seed:Xn.current})):W,La=typeof window<"u"?window.setTimeout(()=>We.abort("bootstrap-timeout"),Ge):null,un=()=>{We.abort(Le?.reason||"external-abort")};Le&&(Le.aborted?un():Le.addEventListener("abort",un,{once:!0}));try{return await fetch(f,{...va||{},signal:We.signal})}catch(Va){throw Le?.aborted&&vp(Va,Le)?Le.reason||Va:Hu(Va)||Va==="bootstrap-timeout"?Ch(Ge):Va}finally{Le&&Le.removeEventListener("abort",un),La!==null&&typeof window<"u"&&window.clearTimeout(La)}},[_t]),nc=r.useMemo(()=>{const f=!aa,W=$t==="stalled",F=aa&&(!Rn||ca||W);let Z="Checking account, workspace access, and setup status...";return $t==="auth"?Z="Verifying session...":$t==="workspace"?Z="Resolving workspace access...":$t==="config"&&(Z="Loading configuration..."),{phase:$t,auth:{resolved:aa,pending:f},config:{loaded:Rn},workspace:{pending:ca},pending:f||F,authPending:f,appPending:F,ready:aa&&Rn&&!ca&&$t==="ready",stalled:W,subtitle:Z,error:ba,startedAt:Lr}},[aa,ba,$t,Lr,Rn,ca]),zr=r.useCallback(f=>String(f?.name||"")==="BootstrapTimeoutError",[]),[so,As]=r.useState([]),[xs,oo]=r.useState({}),[ss,ui]=r.useState(o.taxonomies||[]),ka=r.useMemo(()=>(no.length>0?no:l||[]).map(W=>typeof W=="string"?{value:W.toLowerCase().replace(/\s+/g,"-"),label:W}:W).sort((W,F)=>W.label.localeCompare(F.label)),[no,l]),rc=r.useMemo(()=>({categories:ka,types:so,priorities:an,taxonomies:ss,displayLabels:xs}),[ka,so,an,ss,xs]);r.useMemo(()=>ka.filter(f=>!f.disabled),[ka]);const Gn=r.useCallback(f=>f.find(F=>F.value==="default"||F.value==="general"||F.label==="General"||F.value==="Taskforce"||F.label==="Taskforce")?.value||f[0]?.value||"default",[]),ra=so.length>0?so:i,[io,Hr]=r.useState(!1),[co,Rr]=r.useState(""),sc="Authentication required. Sign in to continue.",[Is,cr]=r.useState(!1),[Os,ln]=r.useState(!1),os=r.useCallback(()=>{ye(b==="cloud"),He(!1),Tt(""),Ht(""),Fa(""),Rr(sc)},[sc,b]),{recentlyChangedTaskIds:$s,fetchTasks:lo,fetchArchive:Us,refreshTaskCollections:Lo,refreshTaskCollectionsFromInvalidation:zs,mergeTaskFromServer:uo}=Xw({tasks:Ga,archivedTasks:Da,setTasks:vr,setArchivedTasks:R,setLoadingTasks:or,getCurrentWorkspaceId:()=>la.current,workspaceResetKey:`${xe}:${ma}`,shouldDeferProtectedApiCalls:ya,shouldBlockProtectedApiCalls:$a,handleUnauthorized:os,authRequiredForApi:E});r.useEffect(()=>{ma!==0&&(jc.current=null,Ri.current="",Vo.current="",ji.current="",Tc.current="",js.current="",Ni.current="",Ns(!1),cr(!1),ua(si()),ln(!1),sn([]),vr([]),R([]),or(!1),jn.current!==null&&typeof window<"u"&&(window.clearTimeout(jn.current),jn.current=null),us.current!==null&&typeof window<"u"&&(window.clearTimeout(us.current),us.current=null))},[R,or,vr,ma]);const lr=r.useCallback(async(f=!1,W)=>{if(!(W?.ignoreAuthGuard===!0)&&(ya||$a))return;f||or(!0);const Z=_t(),We=new AbortController;wn.current=We;try{let Le=await fetch("/api/taskforce/deleted",{signal:We.signal});if(Le.status===404&&(Le=await fetch("/api/taskforce/trash",{signal:We.signal})),Le.status===401){os(),sn([]);return}if(Le.status===404){sn([]);return}if(Le.ok){const Ge=await Le.json();if(bn(Z))return;const ha=Array.isArray(Ge?.deleted)?Ge.deleted.map(va=>{const La=va?.taskSnapshot&&typeof va.taskSnapshot=="object"?Po(va.taskSnapshot):null;return La?{...va,taskSnapshot:La}:null}).filter(va=>!!va):[];sn(ha)}}catch(Le){if(vp(Le,We.signal)||_n(Le))return;console.error("[Taskforce] Failed to fetch deleted tasks:",Le)}finally{wn.current===We&&(wn.current=null),f||or(!1)}},[_t,os,_n,bn,ya,$a]),fa=r.useCallback(async f=>{if(!(f?.ignoreAuthGuard===!0)&&(ya||$a))return;const F=_t();Pn.current?.abort("superseded"),tn.current!==null&&typeof window<"u"&&(window.clearTimeout(tn.current),tn.current=null);const Z=new AbortController;Pn.current=Z;try{const We=th({workspaceId:F.workspaceId,epoch:F.epoch,seed:Xn.current}),Le=async va=>{if(typeof window>"u")return fetch(va,pp({signal:Z.signal},We));const La=new AbortController,un=window.setTimeout(()=>La.abort("planning-timeout"),Eu),Va=()=>La.abort(Z.signal.reason||"external-abort");Z.signal.aborted?Va():Z.signal.addEventListener("abort",Va,{once:!0});try{return await fetch(va,pp({signal:La.signal},We))}catch(Zn){if(Z.signal.aborted)throw Z.signal.reason||Zn;if(Hu(Zn)||Zn==="planning-timeout")return null;throw Zn}finally{window.clearTimeout(un),Z.signal.removeEventListener("abort",Va)}};let Ge=null;const ha=await Le("/api/taskforce/planning/bootstrap");if(ha?.status===401){os(),Ze([]),De([]),sr([]);return}if(ha===null)throw Ch(Eu);if(ha.ok)Ge=Ah(await ha.json().catch(()=>({})));else{const[va,La]=await Promise.all([Le("/api/taskforce/initiatives"),Le("/api/taskforce/workstreams")]);if(!va||!La)throw new Error("Planning endpoints timed out during startup.");if(va.status===401||La.status===401){os(),Ze([]),De([]),sr([]);return}const[un,Va]=await Promise.all([va.ok?va.json().catch(()=>[]):[],La.ok?La.json().catch(()=>[]):[]]);Ge=Ah({initiatives:un,workstreams:Va,workstreamTaskSummaries:[]})}if(bn(F))return;Ze(Ge.initiatives),De(Ge.workstreams),sr(Ge.workstreamTaskSummaries)}catch(We){if(vp(We,Z.signal)||_n(We))return;zr(We)?(zt("planning_bootstrap_timeout",{workspaceId:F.workspaceId,epoch:F.epoch,timeoutMs:Eu}),console.warn("[Taskforce] Planning bootstrap timed out during startup; retrying in background.")):console.error("[Taskforce] Failed to fetch planning entities:",We),typeof window<"u"&&!bn(F)&&C.length===0&&ht.length===0&&(tn.current=window.setTimeout(()=>{tn.current=null,fa(f)},3e3))}finally{Pn.current===Z&&(Pn.current=null)}},[cd,Eu,C.length,_t,os,_n,bn,ya,$a,ht.length]),on=r.useCallback(async(f=!1,W)=>{await lo(f,W)},[lo]),Vn=r.useCallback(async(f=!1,W)=>{await Us(f,W)},[Us]),Gr=r.useCallback(async f=>{const W=f?.isSilent!==!1,F=f?.ignoreAuthGuard===!0;await Promise.all([Lo({isSilent:W,ignoreAuthGuard:F}),lr(W,{ignoreAuthGuard:F}),fa({ignoreAuthGuard:F})])},[lr,fa,Lo]),mi=r.useCallback(async()=>{await zs(),await lr(!0),await fa()},[lr,fa,zs]),Hs=r.useRef(()=>{}),oc=r.useRef(()=>{}),sl=r.useRef(async()=>!1),dn=r.useCallback(f=>sl.current(f),[]),{userGlobalSyncStatus:mo,setUserGlobalSyncStatus:Bo,userGlobalSyncError:po,setUserGlobalSyncError:Wo,workspaceLastPullAt:Cm,workspaceLastPushAt:ol,workspaceLastErrorAt:Am,workspaceLastErrorMessage:il,workspaceLastSuccessfulSyncAt:qn,workspaceCloudSyncEnabled:is,workspaceSyncPhase:fo,workspaceSyncSetupIntent:pi,workspaceSyncStatus:xm,workspaceSyncSummary:Id,workspaceSyncRecommendedAction:Fo,workspaceSyncBusy:Im,workspaceSyncPendingChanges:Td,workspacePendingSignatureRef:Rd,workspaceDeletedTaskIdsRef:Gs,workspaceDeletedTaskWatermarksRef:jd,loadWorkspaceSyncState:cl,applyWorkspaceSyncStateSnapshot:Nd,syncUserGlobalSettings:ic,buildWorkspaceSyncSignature:ll,pushWorkspaceChangesToCloud:Oo,saveWorkspaceCloudSyncSettings:ho,retryUserGlobalSettingsSync:cc,retryWorkspaceCloudSync:cs,resetWorkspaceSyncCursorAndPull:fi,getWorkspaceSyncDiagnostics:$o}=zw({currentWorkspaceId:xe,cloudAuthConfigured:U,runtimeMode:b,authSessionResolved:aa,isAuthenticated:Ie,authUserId:Ve,projectName:yt,resolveCloudAuthUrl:H,resolveWebSocketUrl:be,realtimeSyncEnabled:Ua,tasks:Ga,archivedTasks:Da,deletedTasks:as,initiatives:C,workstreams:ht,taxonomies:ss,taxonomyState:Is?rc:void 0,setupState:Cn,globalTheme:gt,locale:An,globalWeekStartsOn:Ra,themeUseGlobalDefault:St,setTasks:vr,setArchivedTasks:R,setAuthBlocked:ye,setIsAuthenticated:He,checkAuthSession:dn,setGlobalTheme:lt,setCurrentTheme:nt,setSetupState:da,setLocale:Ha,setGlobalWeekStartsOn:ws,fetchPlanningEntities:fa}),hi=r.useCallback((f=ra)=>f.find(W=>String(W.value||"").trim().length>0)?.value||Dr,[ra]),[Vs,Sr]=r.useState(()=>Gn(ka)),[go,Ts]=r.useState(()=>hi(ra)),[ia,Uo]=r.useState(2),[lc,dl]=r.useState(3),[ul,yo]=r.useState("task"),[ml,pl]=r.useState("default"),[fl,gi]=r.useState("unassigned"),[Fn,Rs]=r.useState(""),[Pd,Md]=r.useState(""),[On,yi]=r.useState(""),[ki,vi]=r.useState(""),[dc,hl]=r.useState(""),[qs,uc]=r.useState([]),[gl,Si]=r.useState([]),[wi,mc]=r.useState(""),[pc,wt]=r.useState({}),Ed=r.useRef(null),[fc,ls]=r.useState(!1),[zo,hc]=r.useState("");r.useEffect(()=>{if(ir)return;const f=String(go||"").trim();ra.some(F=>String(F.value||"").trim()===f)||Ts(hi(ra))},[ra,ir,hi,go]);const{searchQuery:gc,setSearchQuery:Dd,filterCategories:yc,setFilterCategories:wr,filterPriorities:Ja,setFilterPriorities:bi,filterTypes:yl,setFilterTypes:Ld,filterStatus:ko,setFilterStatus:Bd,filterAssignees:kl,setFilterAssignees:Vr,filterAssigneesAllSelected:Wd,setFilterAssigneesAllSelected:Fd,filterTaxonomies:kc,setFilterTaxonomies:_i,hasInitedFilters:vo,setHasInitedFilters:Ci,sortBy:vc,setSortBy:Sc,sortOrder:vl,setSortOrder:Od,toggleSortOrder:Ho,groupBy:ds,setGroupBy:Kn,emptyColumnMode:So,setEmptyColumnMode:wo,collapsedCategories:Sl,setCollapsedCategories:wl,clearFilters:Tm,filteredTasks:wc,searchAgnosticTasks:bc,filteredArchive:$d,groupedTasks:Ud}=kb({tasks:Ga,archivedTasks:Da,activeCategories:ka,activeTypes:ra,priorities:an,taxonomies:ss,configLoaded:Rn,referenceDataLoaded:Is,assigneeOptionsLoaded:Os,assigneeOptions:Na});Hs.current=Bo,oc.current=Wo;const{checkAuthSession:bl}=Ib({runtimeConfigReady:B,shouldProbeCloudAuth:Ce,authSessionResolved:aa,resolveCloudAuthUrl:H,authOnlyCloudMode:Pe,authRequiredError:sc,runtimeMode:b,workspaceSelectionScope:ae,markBootstrapPhase:Tr,markBootstrapStalled:Do,setRuntimeMode:j,setAuthRequiredForApi:c,setIsAuthenticated:He,setAuthUserId:Ne,setAuthWorkspaceId:qt,setAuthUserEmail:Tt,setAuthUserDisplayName:Ht,setAuthUserAvatarUrl:Fa,setUserGlobalSyncStatus:f=>Hs.current(f),setUserGlobalSyncError:f=>oc.current(f),setHasBetaAccess:wa,setAvailableWorkspaces:ga,setHydratedWorkspaceRole:it,setAssigneeOptions:ua,setAuthBlocked:ye,setAuthSessionResolved:Za,setError:Rr,applyResolvedWorkspaceId:Wr,readPersistedWorkspaceId:Dp,authSessionRequestRef:en,authSessionEpochRef:Ca,authSessionLastCheckedAtRef:Jt,authSessionLastResultRef:Ta,isLoopbackHost:v,setAuthStateReadyRefs:(f,W,F)=>{xc.current=W,Ic.current=F,Go.current=f}});sl.current=bl;const[_l,Ai]=r.useState("tasks"),[Rm,zd]=r.useState(!1),[jm,xi]=r.useState(!1),[_c,Cc]=r.useState(!1),[Ac,Ii]=r.useState([]),[Hd,Ti]=r.useState(!1),Nm=r.useRef(null),jn=r.useRef(null),us=r.useRef(null),br=r.useRef(!1),xc=r.useRef(aa),Ic=r.useRef(E),Go=r.useRef(Ie),Cl=r.useRef(!1),Ri=r.useRef(""),Vo=r.useRef(""),ji=r.useRef(""),Tc=r.useRef(""),js=r.useRef(""),Ni=r.useRef(""),Pi=r.useRef(!1),Rc=r.useRef(!1),jc=r.useRef(null),Al=r.useRef(!1),Gd=r.useRef(!1),[qo,Ns]=r.useState(!1),Pm=r.useCallback(f=>{qo||(Rc.current=!0),Ai(f)},[qo]),{handleSaveSettings:Vd,handleSaveTheme:qd,handleSaveGlobalTheme:Mm,handleJsonBackupEnabledChange:Em,handleSaveGlobalJsonBackupEnabled:Dm,handleSaveGlobalWeekStartsOn:Lm,handleSaveLocale:Kd,handleManualComplexityEnabledChange:Bm,handleChecklistDropdownEnabledChange:kn,handleShowTaskCardStatusLabelChange:xl,handleResetProjectToGlobal:Zd}=Kw({keyShortcut:pa,themeUseGlobalDefault:St,runtimeMode:b,jsonBackupUseGlobalDefault:zn,globalTheme:gt,globalJsonBackupEnabled:Xr,setCurrentTheme:nt,setThemeUseGlobalDefault:Ke,setGlobalTheme:lt,setJsonBackupEnabled:ar,setJsonBackupUseGlobalDefault:Fr,setGlobalJsonBackupEnabled:gn,setGlobalWeekStartsOn:ws,setLocale:Ha,setManualComplexityEnabled:xr,setChecklistDropdownEnabled:Or,setShowTaskCardStatusLabel:yr,setShowChecklist:ls});r.useEffect(()=>{b==="cloud"&&ae!==Xi&&fS(xe,ae)},[b,xe,ae]),r.useEffect(()=>{xc.current=aa,Ic.current=E,Go.current=Ie},[aa,E,Ie]);const Nc=r.useCallback((f,W)=>{if(!f)return;const F=Array.isArray(f.filterCategories)||Array.isArray(f.filterPriorities)||Array.isArray(f.filterTypes)||Array.isArray(f.filterStatus)||Array.isArray(f.filterAssignees)||typeof f.filterAssigneesAllSelected=="boolean"||f.filterTaxonomies&&typeof f.filterTaxonomies=="object";W?.skipActiveWorkspaceModule||(typeof f.activeWorkspaceModule=="string"?Ai(f.activeWorkspaceModule):f.groupBy==="docs"&&Ai("docs")),f.groupBy&&f.groupBy!=="docs"&&Kn(f.groupBy),(f.emptyColumnMode==="show"||f.emptyColumnMode==="collapse"||f.emptyColumnMode==="hide")&&wo(f.emptyColumnMode),typeof f.zenMode=="boolean"&&ts(f.zenMode),typeof f.searchQuery=="string"&&Dd(f.searchQuery),Array.isArray(f.filterCategories)&&wr(f.filterCategories),Array.isArray(f.filterPriorities)&&bi(f.filterPriorities),Array.isArray(f.filterTypes)&&Ld(f.filterTypes),Array.isArray(f.filterStatus)&&Bd(f.filterStatus),Array.isArray(f.filterAssignees)&&Vr(f.filterAssignees),typeof f.filterAssigneesAllSelected=="boolean"&&Fd(f.filterAssigneesAllSelected),f.filterTaxonomies&&typeof f.filterTaxonomies=="object"&&_i(f.filterTaxonomies),(f.sortBy==="created"||f.sortBy==="priority"||f.sortBy==="updated"||f.sortBy==="complexity")&&Sc(f.sortBy),(f.sortOrder==="asc"||f.sortOrder==="desc")&&Od(f.sortOrder),typeof f.hasInitedFilters=="boolean"?Ci(f.hasInitedFilters):F&&Ci(!0),typeof f.showChecklist=="boolean"&&ls(f.showChecklist),typeof f.lastCategory=="string"&&hc(f.lastCategory),typeof f.exportEnvironment=="string"&&f.exportEnvironment.trim().length>0&&Rt(f.exportEnvironment.trim())},[]),Pc=r.useCallback(async f=>{const W=String(f||la.current||xe||"default").trim()||"default",F=`${b}:${tt}:${W}`;try{const Z=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(W)}`,{method:"GET",credentials:"include"}),We=Z.ok?await Z.json().catch(()=>({})):{},Le=We?.state&&typeof We.state=="object"?We.state:null,Ge=rh(tt),ha=Le||Ge?{...Ge||{},...Le||{}}:null;if(la.current!==W)return;Nc(ha,{skipActiveWorkspaceModule:Rc.current}),Ri.current=F}catch{const Z=rh(tt);la.current===W&&(Nc(Z,{skipActiveWorkspaceModule:Rc.current}),Ri.current=F)}finally{if(la.current!==W)return;Rc.current=!1,Pi.current=!0,Ns(!0)}},[Nc,xe,b,tt]);r.useEffect(()=>{const f=`${b}:${tt}:${xe}`;Cl.current&&Ri.current!==f&&(Ns(!1),Pc(xe))},[xe,Pc,b,tt]),r.useEffect(()=>{if(!qo)return;if(Pi.current){Pi.current=!1;return}const f={groupBy:ds,activeWorkspaceModule:_l,emptyColumnMode:So,zenMode:_s,searchQuery:gc,filterCategories:yc,filterPriorities:Ja,filterTypes:yl,filterStatus:ko,filterAssignees:kl,filterAssigneesAllSelected:Wd,filterTaxonomies:kc,sortBy:vc,sortOrder:vl,hasInitedFilters:vo,showChecklist:fc,lastCategory:zo||"",exportEnvironment:Wa};hS(f,tt);const W=window.setTimeout(async()=>{try{await df({stateKey:"app",workspaceId:la.current,patch:f})}catch{}},250);return()=>window.clearTimeout(W)},[qo,ds,_l,So,_s,gc,yc,Ja,yl,ko,kl,Wd,kc,vc,vl,vo,fc,zo,Wa,tt]);const Il=r.useCallback(f=>{const W=f.runtimeMode==="cloud"?"cloud":"local",F=!!f.authRequiredForApi,Z=typeof f.userId=="string"&&f.userId.trim().length>0?f.userId.trim():"anonymous",We=W==="cloud"&&Z!=="anonymous",Le=We||Go.current,Ge=xc.current;if(j(W),c(F),We&&(He(!0),Ne(Z),ye(!1),Ge||Za(!0)),typeof f.workspaceId=="string"&&f.workspaceId.trim().length>0){const ed=f.workspaceId.trim();W==="local"?Aa(ed):Wr(ed)}ye(W==="cloud"&&F?!Le:!1),f.setupState&&typeof f.setupState=="object"?da(f.setupState):da(null),f.runtimeCapabilities&&typeof f.runtimeCapabilities=="object"?Xt(f.runtimeCapabilities):Xt(null),_a(!!f.realtimeSyncEnabled);const ha=String(f.realtimeSyncFlagSource||"").trim().toLowerCase();tr(ha==="env"||ha==="settings"||ha==="default"?ha:"unknown"),typeof f.shortcut=="string"&&f.shortcut.trim().length>0&&hn(f.shortcut);const va=Vc(f.theme);va&&nt(va);const La=Vc(f.globalTheme);La&<(La),typeof f.themeUseGlobalDefault=="boolean"&&Ke(f.themeUseGlobalDefault);const un=f.runtimeMode==="cloud"?"cloud":"local";typeof f.projectRoot=="string"?Qe(f.projectRoot):un==="cloud"&&Qe(""),typeof f.tenantId=="string"?Bt(f.tenantId.trim()):un==="cloud"&&Bt("");const Va=un==="cloud"?String(f.projectName||"").trim():f.projectName||f.paths?.projectName||"";(String(Va||"").trim().length>0||un==="cloud")&&ot(Va),typeof f.mcpScript=="string"?bt(f.mcpScript):un==="cloud"&&bt(""),typeof f.hostRoot=="string"?Dn(f.hostRoot):un==="cloud"&&Dn(""),typeof f.jsonBackupEnabled=="boolean"&&ar(f.jsonBackupEnabled),typeof f.globalJsonBackupEnabled=="boolean"&&gn(f.globalJsonBackupEnabled),typeof f.jsonBackupUseGlobalDefault=="boolean"&&Fr(f.jsonBackupUseGlobalDefault);const Zn=f?.schedulePreferences?.weekStartsOn;(Zn==="sunday"||Zn==="monday")&&ws(Zn),typeof f.manualComplexityEnabled=="boolean"&&xr(f.manualComplexityEnabled),typeof f.checklistDropdownEnabled=="boolean"?Or(f.checklistDropdownEnabled):Or(!0),typeof f.showTaskCardStatusLabel=="boolean"?yr(f.showTaskCardStatusLabel):yr(!0)},[Wr,Aa]),Yd=r.useCallback(async()=>{const f=typeof performance<"u"?performance.now():Date.now();try{const W=await rs("/api/taskforce/version",void 0,cd);if(!W.ok)return;const F=await W.json().catch(()=>({}));F?.build&&typeof F.build=="object"&&na({version:String(F.build.version||""),gitSha:F.build.gitSha?String(F.build.gitSha):null,buildTime:F.build.buildTime?String(F.build.buildTime):null,deployId:F.build.deployId?String(F.build.deployId):null}),zt("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-f)})}catch(W){zr(W)&&zt("build_info_timeout",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-f)})}},[rs,zr]),{fetchReferenceData:Mi,fetchConfig:jr,fetchWorkspaces:Nr,fetchAssigneeOptions:Ko,switchWorkspace:Pr,resolveWorkspaceAfterAuth:Jd,retryBootstrapChecks:Tl,runCloudBootstrap:Ks}=Mb({shouldDeferProtectedApiCalls:ya,shouldBlockProtectedApiCalls:$a,getWorkspaceRequestState:_t,isWorkspaceRequestStale:bn,isWorkspaceEpochStale:fn,isAbortError:_n,isBootstrapTimeoutError:zr,fetchWithTimeout:rs,handleUnauthorized:os,applyBootstrapConfig:Il,loadPersistedUiState:Pc,fetchBuildInfo:Yd,markBootstrapPhase:Tr,markBootstrapStalled:Do,fetchWorkflows:Ut,fetchInitiativeTemplates:Ma,loadAvailableEnvironments:Hn,setReferenceDataLoaded:cr,setCustomCategories:ii,setCustomTypes:As,setPriorities:fr,setTaxonomies:ui,setTaxonomyDisplayLabels:oo,setConfigLoaded:ro,hasLoadedUiStateRef:Cl,currentWorkspaceIdRef:la,referenceDataRequestRef:jc,referenceDataAbortRef:Sn,bootstrapConfigAbortRef:Br,workspaceListAbortRef:Ba,assigneeOptionsAbortRef:Cr,workspaceListHydratedRef:Al,setAvailableWorkspaces:ga,runtimeMode:b,applyResolvedWorkspaceId:Wr,workspaceSwitchingEnabled:vt,authSessionResolved:aa,isAuthenticated:Ie,authUserId:Ve,authUserAvatarUrl:Ka,setHydratedWorkspaceRole:it,setAssigneeOptions:ua,setAssigneeOptionsLoaded:ln,commitCurrentWorkspaceId:(f,W)=>{vn.current=f,Aa(f,W),W?.clearExplicitSelection!==!1&&(vn.current=null)},currentWorkspaceId:xe,workspaceSelectionScope:ae,abortWorkspaceScopedRequests:Oa,setWorkspaceBootstrapPending:Dt,checkAuthSession:dn,lastConfigRefreshKeyRef:ji,lastAssigneeOptionsLoadKeyRef:Vo,lastWorkspaceSyncStateLoadKeyRef:Tc,lastTaskSurfaceLoadKeyRef:js,lastSettingsSurfaceLoadKeyRef:Ni,isOpen:ee,activeTab:z,showArchive:q,taskScope:we,settingsSection:Be,workspaceBootstrapPending:ca,fetchTasks:on,fetchArchive:Vn,fetchPlanningEntities:fa,refreshTaskCollections:Gr,loadWorkspaceSyncState:cl,archiveBootstrapTimerRef:us,hasBootstrappedDataRef:Gd}),Ei=r.useCallback(async()=>{await dn(),await jr()},[dn,jr]);r.useEffect(()=>{if(!Rn||ca)return;const f=`${b}:${Ie?"auth":"guest"}:${xe}:${Ka||"no-avatar"}`;Os&&Vo.current===f||(Vo.current=f,Ko())},[Os,Ka,Rn,xe,Ko,Ie,b,ca]),r.useEffect(()=>{if(!aa||!Ie)return;const f=String(Ve||"").trim();if(!f||f==="anonymous")return;const W=String(Ka||"").trim()||null;ua(F=>{let Z=!1;const We=F.map(Le=>Le.kind!=="member"||String(Le.value||"").trim()!==f||(typeof Le.avatarUrl=="string"&&Le.avatarUrl.trim().length>0?Le.avatarUrl.trim():null)===W?Le:(Z=!0,{...Le,avatarUrl:W}));return Z?We:F})},[aa,Ka,Ve,Ie]);const Rl=r.useMemo(()=>vt?Gt.find(W=>W.id===xe)?.role??null:he,[Gt,xe,he,vt]);r.useEffect(()=>{Ie||it(null)},[Ie]);const Qd=r.useCallback(async()=>{Qt(null);const f=await Ks({reason:"post-plans",ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return f.authenticated?f.success?f.workspaceSetupRequired?{success:!0,destination:"setup"}:{success:!0,destination:"app"}:{success:!1,destination:"app",error:f.error||"Unable to resolve workspace after plan selection.",code:f.code}:{success:!1,destination:"login",error:f.error||"Sign in required.",code:f.code||"AUTH_REQUIRED"}},[Ks]),ms=r.useCallback(async f=>{const W=f?.reason||"retry",F=typeof f?.preferredWorkspaceId=="string"?f.preferredWorkspaceId.trim():"",Z=f?.allowCommercialGate===!0;if(F&&vt){if(!await dn({force:!0}))return await jr({ignoreAuthGuard:!0}),{success:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};const Ge=await Jd({preferredWorkspaceId:F});if(!Ge.success)return await jr({ignoreAuthGuard:!0}),{success:!1,error:Ge.error||"Unable to resolve workspace access.",code:Ge.code};if(Ge.workspaceSetupRequired)return await jr({ignoreAuthGuard:!0}),{success:!0,workspaceSetupRequired:!0}}const We=await Ks({reason:W,ignoreAuthGuard:!0,tasksSilent:!0,includeDeferredArchive:!1});return We.authenticated?We.success?We.workspaceSetupRequired?Z?{success:!0,workspaceSetupRequired:!1}:{success:!0,workspaceSetupRequired:!0}:(Z||ic({preferCloudOnFirstSync:!0}),{success:!0,workspaceSetupRequired:!1}):{success:!1,error:We.error||"Unable to resolve workspace access.",code:We.code}:{success:!1,error:We.error||"Sign in required.",code:We.code||"AUTH_REQUIRED"}},[dn,jr,Jd,Ks,ic,vt]),Zo=r.useCallback(async(f,W)=>{if(!vt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const F=String(f||"").trim();if(!F)return{success:!1,error:"Workspace name is required."};try{const Z=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:F,description:typeof W=="string"?W:void 0})}),We=await Z.json().catch(()=>({}));if(!Z.ok||We?.success===!1)return{success:!1,error:We?.error||`Failed to create workspace (${Z.status})`,code:We?.code};const Le=We?.workspace;if(await Nr(),Le?.id){const Ge=await Pr(Le.id);if(!Ge.success)return{success:!1,error:Ge.error||"Workspace created but failed to activate.",code:Ge.code}}return{success:!0,workspace:Le}}catch{return{success:!1,error:"Failed to create workspace."}}},[Nr,Pr,vt]),dr=r.useCallback(async f=>{if(!vt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const W=String(f||"").trim();if(!W)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const F=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(W)}`,{method:"DELETE",credentials:"include"}),Z=await F.json().catch(()=>({}));if(!F.ok||Z?.success===!1)return{success:!1,error:Z?.error||`Failed to delete workspace (${F.status})`,code:Z?.code};await dn({force:!0}),await Promise.all([jr(),Nr()]);const We=typeof Z?.nextWorkspaceId=="string"?Z.nextWorkspaceId.trim():"";return We&&Aa(We),{success:!0,nextWorkspaceId:We||void 0,workspaceSetupRequired:Z?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(Z?.cleanupWarnings)?Z.cleanupWarnings.map(Le=>String(Le||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[dn,Aa,jr,Nr,vt]),Yo=r.useCallback(async f=>{const W=f==="operations"?"operations":"core";try{const F=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:W}})}),Z=await F.json().catch(()=>({}));return!F.ok||Z?.success===!1?!1:(await Ei(),!0)}catch{return!1}},[Ei]),jl=r.useCallback(async f=>{const W=String(f?.name||"").trim(),F=typeof f?.workspaceId=="string"?f.workspaceId.trim():"";if(!W)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const Z=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":b},credentials:"include",body:JSON.stringify({workspaceId:F&&F!=="default"?F:void 0,name:W,description:typeof f.description=="string"?f.description:void 0,allowCreate:!0})}),We=await Z.json().catch(()=>({}));if(!Z.ok||We?.success===!1)return{success:!1,error:We?.error||`Failed to save workspace (${Z.status})`,code:We?.code};const Le=String(We?.workspace?.id||"").trim();if(Le&&(Aa(Le),await new Promise(Ge=>window.setTimeout(Ge,0)),b==="cloud"&&Ie&&Le!==xe)){const Ge=await Pr(Le);if(!Ge.success)return{success:!1,error:Ge.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await Ei(),{success:!0,workspaceId:Le||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[Aa,Ei,b,Ie,xe,Pr]),Xd=r.useCallback(async(f,W)=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const F=f.trim().toLowerCase(),Z=W;if(!F||!Z)return{success:!1,error:"Email and password are required."};try{const We=await fetch(H("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:F,password:Z})}),Le=await We.json().catch(()=>({}));if(!We.ok||!Le?.success)return{success:!1,error:Le?.error||"Sign in failed.",code:Le?.code};Rr("");const Ge=await ms();return Ge.success?{success:!0,workspaceSetupRequired:Ge.workspaceSetupRequired===!0}:{success:!1,error:Ge.error||"Unable to resolve workspace after sign in.",code:Ge.code}}catch{return{success:!1,error:"Sign in failed."}}},[H,U,ms]),Wm=r.useCallback((f,W,F)=>{const Z=W&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(W)?W:"/";let We=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?return_to=${encodeURIComponent(Z)}`;F&&(We+=`&invite_token=${encodeURIComponent(F)}`),window.location.href=H(We)},[H]),Nl=r.useCallback(async(f,W,F)=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const Z=f.trim().toLowerCase(),We=W;if(!Z||!We)return{success:!1,error:"Email and password are required."};try{const Le=await fetch(H("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:Z,password:We,...typeof F?.displayName=="string"&&F.displayName.trim()?{displayName:F.displayName.trim()}:{},...typeof F?.planId=="string"&&F.planId.trim()?{planId:F.planId.trim()}:{},...typeof F?.planVersionId=="string"&&F.planVersionId.trim()?{planVersionId:F.planVersionId.trim()}:{},...typeof F?.interval=="string"&&F.interval.trim()?{interval:F.interval.trim()}:{}})}),Ge=await Le.json().catch(()=>({}));if(!Le.ok||!Ge?.success)return{success:!1,error:Ge?.error||"Create account failed.",code:Ge?.code,verificationRequired:!!Ge?.verificationRequired,verificationToken:typeof Ge?.verificationToken=="string"?Ge.verificationToken:void 0,emailSent:Ge?.emailSent!==!1,emailError:typeof Ge?.emailError=="string"?Ge.emailError:void 0};const ha=Ge?.planSelectionRequired===!0,va=Ge?.checkoutPending===!0,La=typeof Ge?.commercialState=="string"?Ge.commercialState:null,un=!!Ge?.verificationRequired;if(!un){if(Rr(""),!!(ha||va||La==="pending_plan_selection"||La==="checkout_pending"))return await dn({force:!0})?{success:!0,workspaceSetupRequired:!1,planSelectionRequired:ha,checkoutPending:va,commercialState:La,verificationRequired:un,verificationToken:typeof Ge?.verificationToken=="string"?Ge.verificationToken:void 0,emailSent:Ge?.emailSent!==!1,emailError:typeof Ge?.emailError=="string"?Ge.emailError:void 0}:{success:!1,error:"Unable to resolve workspace after registration.",code:"AUTH_REQUIRED"};const Zn=await ms({allowCommercialGate:!1});return Zn.success?{success:!0,workspaceSetupRequired:Zn.workspaceSetupRequired===!0,planSelectionRequired:ha,checkoutPending:va,commercialState:La,verificationRequired:un,verificationToken:typeof Ge?.verificationToken=="string"?Ge.verificationToken:void 0,emailSent:Ge?.emailSent!==!1,emailError:typeof Ge?.emailError=="string"?Ge.emailError:void 0}:{success:!1,error:Zn.error||"Unable to resolve workspace after registration.",code:Zn.code}}return{success:!0,workspaceSetupRequired:!!Ge?.workspaceSetupRequired,planSelectionRequired:ha,checkoutPending:va,commercialState:La,verificationRequired:un,verificationToken:typeof Ge?.verificationToken=="string"?Ge.verificationToken:void 0,emailSent:Ge?.emailSent!==!1,emailError:typeof Ge?.emailError=="string"?Ge.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[dn,H,U,ms]),eu=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=String(f.displayName||"").trim(),F=typeof f.avatarDraftId=="string"?f.avatarDraftId.trim():"",Z=f.clearAvatar===!0;if(!W)return{success:!1,error:"Display name is required."};try{const We=await fetch(H("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:W,...F?{avatarDraftId:F}:{},...Z?{clearAvatar:!0}:{}})}),Le=await We.json().catch(()=>({}));if(!We.ok||!Le?.success)return{success:!1,error:Le?.error||"Failed to update profile.",code:Le?.code};const Ge={userId:typeof Le?.profile?.userId=="string"?Le.profile.userId:Ve,email:typeof Le?.profile?.email=="string"?Le.profile.email:Et,displayName:typeof Le?.profile?.displayName=="string"?Le.profile.displayName:null,avatarUrl:typeof Le?.profile?.avatarUrl=="string"?Le.profile.avatarUrl:null};return Ht(Ge.displayName||""),Fa(Ge.avatarUrl||""),{success:!0,profile:Ge}}catch{return{success:!1,error:"Failed to update profile."}}},[H,U,Et,Ve]),qr=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=f.trim().toLowerCase();if(!W)return{success:!1,error:"Email is required."};try{const F=await fetch(H("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:W})}),Z=await F.json().catch(()=>({}));return!F.ok||!Z?.success?{success:!1,error:Z?.error||"Failed to request verification email.",code:Z?.code}:{success:!0,verificationToken:Z?.verificationToken??null,emailSent:Z?.emailSent!==!1,deliveryAttempted:Z?.deliveryAttempted===!0||typeof Z?.verificationToken=="string"&&Z.verificationToken.trim().length>0,emailError:typeof Z?.emailError=="string"?Z.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[H,U]),tu=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=f.trim();if(!W)return{success:!1,error:"Token is required."};try{const F=await fetch(H("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:W})}),Z=await F.json().catch(()=>({}));return!F.ok||!Z?.success?{success:!1,error:Z?.error||"Verification failed.",code:Z?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[H,U]),Kr=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=f.trim().toLowerCase();if(!W)return{success:!1,error:"Email is required."};try{const F=await fetch(H("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:W})}),Z=await F.json().catch(()=>({}));return!F.ok||!Z?.success?{success:!1,error:Z?.error||"Failed to request password reset.",code:Z?.code}:{success:!0,resetToken:Z?.resetToken??null,emailSent:Z?.emailSent!==!1,deliveryAttempted:Z?.deliveryAttempted===!0||typeof Z?.resetToken=="string"&&Z.resetToken.trim().length>0,emailError:typeof Z?.emailError=="string"?Z.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[H,U]),au=r.useCallback(async(f,W)=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const F=f.trim(),Z=W;if(!F||!Z)return{success:!1,error:"Token and password are required."};try{const We=await fetch(H("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:F,password:Z})}),Le=await We.json().catch(()=>({}));return!We.ok||!Le?.success?{success:!1,error:Le?.error||"Failed to reset password.",code:Le?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[H,U]),nu=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=f.trim();if(!W)return{success:!1,error:"Token is required."};try{const F=await fetch(H("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:W})}),Z=await F.json().catch(()=>({}));return!F.ok||!Z?.success?{success:!1,error:Z?.error||"Invite inspection failed.",code:Z?.code,state:Z?.state}:{success:!0,state:Z?.state,email:typeof Z?.email=="string"?Z.email:void 0,workspaceId:typeof Z?.workspaceId=="string"?Z.workspaceId:void 0,inviteeKind:Z?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:Z?.passwordRequired===!0,inviteeState:Z?.inviteeState==="existing_account"?"existing_account":"pending_setup",availableMethods:Array.isArray(Z?.availableMethods)?Z.availableMethods:[]}}catch{return{success:!1,error:"Invite inspection failed."}}},[H,U]),Di=r.useCallback(async(f,W)=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const F=f.trim(),Z=W;if(!F||!Z)return{success:!1,error:"Token and password are required."};try{const We=await fetch(H("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:F,password:Z})}),Le=await We.json().catch(()=>({}));if(!We.ok||!Le?.success)return{success:!1,error:Le?.error||"Invite acceptance failed.",code:Le?.code};Rr("");const Ge=typeof Le?.workspaceId=="string"?Le.workspaceId:null;if(Ge&&vt){const va=await Pr(Ge,{hydrate:!1});if(!va.success)return{success:!1,error:va.error||"Unable to resolve workspace after invite acceptance.",code:va.code}}const ha=await ms({preferredWorkspaceId:Ge});return ha.success?(Ge&&la.current!==Ge&&Aa(Ge,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:ha.workspaceSetupRequired===!0}):{success:!1,error:ha.error||"Unable to resolve workspace after invite acceptance.",code:ha.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[Aa,H,U,la,ms,Pr,vt]),Pl=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth endpoint is not configured."};const W=f.trim();if(!W)return{success:!1,error:"Token is required."};try{const F=await fetch(H("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:W})}),Z=await F.json().catch(()=>({}));if(!F.ok||!Z?.success)return{success:!1,error:Z?.error||"Invite join failed.",code:Z?.code};Rr("");const We=typeof Z?.workspaceId=="string"?Z.workspaceId:null;if(We&&vt){const Ge=await Pr(We,{hydrate:!1});if(!Ge.success)return{success:!1,error:Ge.error||"Unable to resolve workspace after invite join.",code:Ge.code}}const Le=await ms({preferredWorkspaceId:We});return Le.success?(We&&la.current!==We&&Aa(We,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:Le.workspaceSetupRequired===!0}):{success:!1,error:Le.error||"Unable to resolve workspace after invite join.",code:Le.code}}catch{return{success:!1,error:"Invite join failed."}}},[Aa,H,U,la,ms,Pr,vt]),Li=r.useCallback(async()=>{if(!U)return{success:!1,error:"Cloud auth not configured."};try{const f=await fetch(H("/api/taskforce/account/login-methods"),{credentials:"include"}),W=await f.json().catch(()=>({}));return!f.ok||!W?.success?{success:!1,error:W?.error||"Failed to fetch login methods."}:{success:!0,methods:Array.isArray(W?.methods)?W.methods:[]}}catch{return{success:!1,error:"Failed to fetch login methods."}}},[H,U]),Fm=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth not configured."};try{const W=await fetch(H(`/api/taskforce/account/login-methods/${encodeURIComponent(f)}`),{method:"DELETE",credentials:"include"}),F=await W.json().catch(()=>({}));return!W.ok||!F?.success?{success:!1,error:F?.error||"Unlink failed.",code:F?.code}:{success:!0}}catch{return{success:!1,error:"Unlink failed."}}},[H,U]),Jo=r.useCallback(async f=>{if(!U)return{success:!1,error:"Cloud auth not configured."};try{const W=await fetch(H("/api/taskforce/account/login-methods/password"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:f})}),F=await W.json().catch(()=>({}));return!W.ok||!F?.success?{success:!1,error:F?.error||"Failed to add password.",code:F?.code}:{success:!0}}catch{return{success:!1,error:"Failed to add password."}}},[H,U]),Ml=r.useCallback((f,W)=>{const F=W&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(W)?W:"/",Z=`/api/taskforce/auth/oauth/${encodeURIComponent(f)}/start?flow=link&return_to=${encodeURIComponent(F)}`;window.location.href=H(Z)},[H]),El=r.useCallback(()=>{Oa(),jc.current=null,Ri.current="",Vo.current="",ji.current="",Tc.current="",js.current="",Ni.current="",Ns(!1),cr(!1),ua(si()),ln(!1),sn([]),vr([]),R([]),Ze([]),De([]),sr([]),or(!1),jn.current!==null&&typeof window<"u"&&(window.clearTimeout(jn.current),jn.current=null),us.current!==null&&typeof window<"u"&&(window.clearTimeout(us.current),us.current=null)},[Oa,R,vr]),Om=r.useCallback(async()=>{try{U&&await fetch(H("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(Oa(),Ca.current+=1,en.current=null,Ta.current=!1,Jt.current=Date.now(),He(!1),Za(!0),Ne("anonymous"),qt(""),od(null),Tt(""),Ht(""),Fa(""),Bo("disconnected"),Wo(null),wa(!0),ot(""),ro(!1),cr(!1),da(null),Qn("idle"),Qt(null),Cl.current=!1,b!=="local"&&nh(ae),ye(b==="cloud"&&E),Aa("default"),ga([]),Al.current=!1,it(null),b==="local"){await Promise.allSettled([jr({ignoreAuthGuard:!0}),on(!0,{ignoreAuthGuard:!0}),fa({ignoreAuthGuard:!0}),Mi({ignoreAuthGuard:!0,force:!0})]);return}Gd.current=!1,El()}},[Oa,E,nh,Aa,H,U,ae,b,jr,fa,Mi,on,El]),Dl=r.useCallback(async f=>{try{const W=await fetch("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}),F=await W.json().catch(()=>({}));return!W.ok||!F?.success?{success:!1,error:F?.error||`Create failed (${W.status})`}:(await on(!0),{success:!0,result:F?.results})}catch(W){return{success:!1,error:W.message}}},[on]),ru=r.useCallback(async f=>{const W=await fetch("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to create initiative (${W.status})`);return await fa(),Ze(Z=>ti(Z,F)),F},[fa]),$m=r.useCallback(async(f,W)=>{const F=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(W||{})}),Z=await F.json().catch(()=>({}));if(!F.ok)throw new Error(Z?.error||`Failed to update initiative (${F.status})`);return await fa(),Ze(We=>ti(We,Z)),Z},[fa]),Ll=r.useCallback(async f=>{const W=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/archive`,{method:"POST"}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to archive initiative (${W.status})`);return await fa(),Ze(Z=>ti(Z,F)),F},[fa]),su=r.useCallback(async f=>{const W=await fetch(`/api/taskforce/initiative/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to unarchive initiative (${W.status})`);return await fa(),Ze(Z=>ti(Z,F)),F},[fa]),Um=r.useCallback(async f=>{const W=await fetch("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f||{})}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to create workstream (${W.status})`);return await fa(),De(Z=>ti(Z,F)),F},[fa]),zm=r.useCallback(async(f,W)=>{const F=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(W||{})}),Z=await F.json().catch(()=>({}));if(!F.ok)throw new Error(Z?.error||`Failed to update workstream (${F.status})`);return await fa(),De(We=>ti(We,Z)),Z},[fa]),Bl=r.useCallback(async f=>{const W=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/archive`,{method:"POST"}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to archive workstream (${W.status})`);return await fa(),De(Z=>ti(Z,F)),F},[fa]),Mc=r.useCallback(async f=>{const W=await fetch(`/api/taskforce/workstream/${encodeURIComponent(f)}/unarchive`,{method:"POST"}),F=await W.json().catch(()=>({}));if(!W.ok)throw new Error(F?.error||`Failed to unarchive workstream (${W.status})`);return await fa(),De(Z=>ti(Z,F)),F},[fa]),bo=r.useRef(!1);r.useEffect(()=>{Q(!0),!bo.current&&(bo.current=!0,dn())},[dn]),r.useEffect(()=>{B&&dn()},[B,dn]),r.useEffect(()=>{if(!U)return;let f=!1;const W=new AbortController,F=typeof window<"u"?window.setTimeout(()=>W.abort(),5e3):null;return fetch(H("/api/taskforce/auth/providers"),{credentials:"include",signal:W.signal}).then(Z=>Z.ok?Z.json():null).then(Z=>{!f&&Array.isArray(Z?.providers)&&Kt(Z.providers)}).catch(()=>{}).finally(()=>{F!==null&&typeof window<"u"&&window.clearTimeout(F)}),()=>{f=!0,W.abort()}},[U,H]),r.useEffect(()=>{if(b!=="local"||!Ce||typeof window>"u")return;const f=()=>{dn()},W=()=>{document.visibilityState==="visible"&&f()};window.addEventListener("focus",f),window.addEventListener("online",f),document.addEventListener("visibilitychange",W);const F=window.setInterval(f,3e4);return()=>{window.removeEventListener("focus",f),window.removeEventListener("online",f),document.removeEventListener("visibilitychange",W),window.clearInterval(F)}},[b,Ce,dn]),r.useEffect(()=>{n&&n(Ga.length)},[Ga.length,n]),r.useEffect(()=>{if(t&&Ga.length>0){const f=Ga.find(W=>W.id.endsWith(t)||W.id===t);f&&(mu(f),Ds("add"))}},[t,Ga]);const Bi=r.useRef(!1);r.useEffect(()=>{if(!Rn)return;if(!Bi.current&&ka.length>0){Bi.current=!0;const W=zo,F=ka.some(Z=>Z.label===W||Z.value===W);if(W&&F){const Z=ka.find(We=>We.label===W||We.value===W);Sr(Z?.value||W)}else Sr(Gn(ka));return}const f=ka.some(W=>W.value===Vs);ka.length>0&&!f&&Sr(Gn(ka))},[Rn,ka,Vs,Gn,zo]),r.useEffect(()=>{if(!Rn||ka.length===0)return;const f=Z=>!ka.some(We=>We.value===Z.category),W=Ga.some(f),F=Da.some(f);if(W||F){const Z=Gn(ka);W&&vr(We=>We.map(Le=>f(Le)?{...Le,category:Z}:Le)),F&&R(We=>We.map(Le=>f(Le)?{...Le,category:Z}:Le))}},[Rn,ka,Ga,Da,Gn]),r.useEffect(()=>()=>{us.current!==null&&typeof window<"u"&&(window.clearTimeout(us.current),us.current=null),jn.current!==null&&typeof window<"u"&&(window.clearTimeout(jn.current),jn.current=null)},[]),r.useEffect(()=>{},[Gr]);const Mr=r.useCallback(async()=>{await mi()},[mi]),Ps=String(xe||"").trim(),Zs=String(Ve||"").trim(),Wl=be("/taskforce-ws"),Hm=!!(U&&b==="cloud"&&aa&&Ie&&Zs&&Zs!=="anonymous"&&Ps&&!of(Ps)&&Wl),Gm=r.useCallback(()=>{b==="cloud"&&(mi(),!(typeof window>"u")&&(jn.current!==null&&window.clearTimeout(jn.current),jn.current=window.setTimeout(()=>{jn.current=null,mi()},250)))},[b,mi]);Yg({enabled:Hm,workspaceId:Ps,websocketUrl:Wl,onSignal:Gm,userId:Zs||void 0}),Eb({isOpen:ee,authBlocked:Y,authRequiredForApi:E,isAuthenticated:Ie,canCallProtectedApi:Mn.canCallProtectedApi,shouldGateProtectedApiCalls:Ee,authSessionResolvedRef:xc,authRequiredForApiRef:Ic,isAuthenticatedRef:Go,dataVersionRef:Nm,refreshTaskCollectionsForDataVersion:Mr});const Wi=r.useMemo(()=>{const f=new Map;for(const W of Da)f.set(W.id,W);for(const W of Ga)f.set(W.id,W);return Array.from(f.values())},[Ga,Da]),Af=r.useMemo(()=>as.map(f=>({...f.taskSnapshot,isDeleted:!0,deletedRecordId:f.id})),[as]);r.useEffect(()=>{if(!(ya||$a)&&ee&&!ca){if(z==="tasks"){const f=`${xe}:${z}:${q?"archive":"active"}:${we}`;if(!br.current){br.current=!0,js.current=f;return}if(js.current===f)return;js.current=f,on(),fa(),(q||we==="archived")&&Vn(!0),we==="deleted"&&lr();return}if(z==="settings"){const f=`${xe}:${z}:${Be}`;if(Ni.current===f)return;Ni.current=f,jr(),(Be==="commands"||Be==="resources")&&Ut()}}},[xe,ee,z,Be,q,we,on,fa,Vn,lr,jr,Ut,ya,$a,ca]);const Fi=r.useCallback(async(f="")=>{try{const W=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(f)}`);if(W.ok){const F=await W.json();st(F.folders||[]),Pt(F.files||[]),It(f)}}catch(W){console.error("[Taskforce] Failed to fetch folders:",W)}},[]),Fl=r.useCallback(f=>{const W=[];if(f.path&&W.push(f.path),f.paths&&f.paths.length>0)for(const F of f.paths)W.includes(F)||W.push(F);return W},[]),{validatePaths:Vm,handleUpdateCategory:Ec,handleSaveCategory:Dc,handleAddPath:ou,handleUpdateCategoryIcon:Ms,handleUpdateCategoryColor:iu,handleRemovePath:Ol,handleSelectPath:qm,handleRemoveCategory:$l,handleSaveType:Es,handleRemoveType:cu,handleUpdateType:lu,handleUpdateTaxonomies:du,handleUpdatePriorities:uu,analyzeSystemTaxonomyPack:Km,handleApplySystemTaxonomyPack:Zr}=Zw({activeCategories:ka,activeTab:z,activeTypes:ra,archivedTasks:Da,browserTarget:Ft,category:Vs,configLoaded:Rn,customCategories:no,refreshTaskCollections:Gr,fetchTasks:on,filterCategories:yc,getCategoryPaths:Fl,normalizePath:ao,pathValidation:ci,setBrowserTarget:Mt,setCategory:Sr,setCustomCategories:ii,setCustomTypes:As,setFilterCategories:wr,setPathValidation:li,setPriorities:fr,setShowFolderBrowser:ct,setTaxonomies:ui,tasks:Ga}),Lc=r.useCallback(async f=>{const W=xs,F={...W,...f};oo(F);try{const Z=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:f})});if(!Z.ok)throw new Error(`Failed to save taxonomy display labels (${Z.status})`);const We=await Z.json().catch(()=>({}));We?.displayLabels&&typeof We.displayLabels=="object"&&oo({...F,...We.displayLabels})}catch(Z){console.error("[Taskforce] Failed to update taxonomy display labels",Z),oo(W)}},[xs]),Ds=r.useCallback(f=>{z==="tasks"&&Tn.current&&Eo(Tn.current.scrollTop),ie(f)},[z]),ps=r.useRef(async()=>{}),{handleNavigation:Zm,handleClose:Ul,resetForm:zl,resolveWorkstreamIdInput:Hl,handleEdit:mu,handleOpenTaskById:Oi,returnToPreviousTask:_o,clearReturnToParentTask:Bc}=rb({activeCategories:ka,activeTypes:ra,activeTab:z,attachments:Ac,checklistItems:qs,comments:gl,description:dc,editingTaskId:ir,flushPendingAutoSave:()=>ps.current(),getPreferredCategoryValue:Gn,lastUsedCategory:zo,newCommentText:wi,relationshipTasks:Wi,workstreams:ht,showArchive:q,taxonomies:ss,setActiveTab:Ds,setApproach:pl,setAssignee:gi,setAttachments:Ii,setAttachmentsDirty:Ti,setCategory:Sr,setChecklistItems:uc,setComments:Si,setComplexity:dl,setDescription:hl,setDueDate:Md,setEditingTaskId:ns,setError:Rr,setFormTaxonomies:wt,setIsOpen:Q,setNewCommentText:mc,setPendingNavigation:G,setWorkstreamInput:yi,setPriority:Uo,setScheduledDate:Rs,setShowArchive:Se,setStatus:yo,setTaskReturnTrail:In,setTitle:vi,setType:Ts,setUnsavedModalOpen:Bn,taskReturnTrail:Ea,title:ki}),{copiedId:Wc,handleDelete:Co,handleUpdateTask:Qo,handleToggleComplete:Gl,handleToggleCancel:Vl,handleToggleInProgress:Fc,handleToggleReview:Ao,handleArchiveTask:ql,handleBulkArchive:Kl,handleUnarchive:Ym,handleRestoreDeletedTask:Zl,handlePermanentlyDeleteDeletedTask:pu,handleEmptyDeletedTasks:fu,handleCopyId:Ys,queueWorkspaceSyncFromAuthoritativeTaskState:Yl}=bb({tasks:Ga,archivedTasks:Da,editingTaskId:ir,setTasks:vr,setArchivedTasks:R,setDeletedTasks:sn,setError:Rr,resetForm:zl,setActiveTab:Ds,fetchTasks:on,fetchArchive:Vn,fetchDeletedTasks:lr,mergeTaskFromServer:uo,pushNotice:At,cloudAuthConfigured:U,runtimeMode:b,isAuthenticated:Ie,workspaceCloudSyncEnabled:is,buildWorkspaceSyncSignature:ll,pushWorkspaceChangesToCloud:Oo,workspacePendingSignatureRef:Rd,workspaceDeletedTaskIdsRef:Gs,workspaceDeletedTaskWatermarksRef:jd}),{autoSaveState:hu,flushAutoSave:Jl,scheduleWarningPrompt:Jm,handleSubmit:Ql,confirmScheduleWarning:Qm,cancelScheduleWarning:Xm,handleAddComment:Xo}=vb({activeCategories:ka,activeTab:z,apiEndpoint:d,approach:ml,assignee:fl,attachments:Ac,attachmentsDirty:Hd,category:Vs,checklistItems:qs,comments:gl,complexity:lc,description:dc,dueDate:Pd,editingTaskId:ir,fetchTasks:on,formTaxonomies:pc,getPreferredCategoryValue:Gn,mergeTaskFromServer:uo,workstreamInput:On,priority:ia,pushNotice:At,queueWorkspaceSyncFromAuthoritativeTaskState:Yl,relationshipTasks:Wi,resetForm:zl,resolveWorkstreamIdInput:Hl,scheduledDate:Fn,setActiveTab:Ds,setAttachmentsDirty:Ti,setComments:Si,setError:Rr,setLastUsedCategory:hc,setLoading:Hr,setNewCommentText:mc,status:ul,title:ki,taxonomies:ss,type:go});r.useEffect(()=>{ps.current=Jl},[Jl]);const{handleSetWorkstreamForCurrentTask:Xl}=Sb({editingTaskId:ir,mergeTaskFromServer:uo,workstreamInput:On,pushNotice:At,queueWorkspaceSyncFromAuthoritativeTaskState:Yl,relationshipTasks:Wi,resolveWorkstreamIdInput:Hl,setError:Rr,fetchTasks:on}),{currentTask:gu,currentTaskWorkstream:yu,currentTaskInitiative:ku}=eb({editingTaskId:ir,relationshipTasks:Wi,initiatives:C,workstreams:ht,supplementalTasks:Af,setComments:Si}),fs=qw({resolveCloudAuthUrl:H,currentWorkspaceId:xe,normalizedCloudAuthBaseUrl:se,normalizedCloudMcpBaseUrl:Re,mergedConfig:o,availableWorkspaces:Gt,currentTheme:Me,configLoaded:Rn,globalTheme:gt,themeUseGlobalDefault:St,keyShortcut:pa,jsonBackupEnabled:za,globalJsonBackupEnabled:Xr,globalWeekStartsOn:Ra,locale:An,supportedLocales:Ar,jsonBackupUseGlobalDefault:zn,manualComplexityEnabled:nn,checklistDropdownEnabled:gr,showTaskCardStatusLabel:yn,exportWorkflowsPath:Ln,exportingResource:Cs,exportResult:Ir,pathSaved:dt,settingsSection:Be,exportEnvironment:Wa,setupState:Cn,buildInfo:Pa,saveSetupMode:Yo,saveWorkspaceProfile:jl,setCurrentTheme:nt,handleSaveTheme:qd,handleSaveGlobalTheme:Mm,setKeyShortcut:hn,handleJsonBackupEnabledChange:Em,handleSaveGlobalJsonBackupEnabled:Dm,handleSaveGlobalWeekStartsOn:Lm,handleSaveLocale:Kd,handleManualComplexityEnabledChange:Bm,handleChecklistDropdownEnabledChange:kn,handleShowTaskCardStatusLabelChange:xl,handleResetProjectToGlobal:Zd,handleSaveSettings:Vd,setExportWorkflowsPath:rr,setExportEnvironment:Rt,availableWorkflows:$r,initiativeTemplates:Je,availableEnvironments:kr,fetchWorkflows:Ut,fetchInitiativeTemplates:Ma,createInitiativeFromTemplate:Dl,fetchWorkflowTemplate:oa,fetchWorkflowOverrideNames:cn,saveWorkflowTemplateDraft:rn,resetWorkflowTemplateDraft:bs,handleExportWorkflows:Ur,setShowFolderBrowser:ct,setBrowserTarget:Mt,fetchFolders:Fi,activeCategories:ka,pathValidation:ci,taxonomyDisplayLabels:xs,handleUpdateCategory:Ec,handleRemoveCategory:$l,handleSaveCategory:Dc,handleAddPath:ou,handleRemovePath:Ol,handleUpdateCategoryIcon:Ms,handleUpdateCategoryColor:iu,activeTypes:ra,handleSaveType:Es,handleRemoveType:cu,handleUpdateType:lu,taxonomies:ss,handleUpdateTaxonomies:du,priorities:an,handleUpdatePriorities:uu,analyzeSystemTaxonomyPack:Km,handleApplySystemTaxonomyPack:Zr,handleUpdateTaxonomyDisplayLabels:Lc,projectRoot:Ue,projectName:yt,mcpHostRoot:ea,serverHostRoot:xn,mcpScriptPath:ze,tenantId:Ot,runtimeMode:b,workspaceSwitchingEnabled:vt,deleteWorkspace:dr,setMcpHostRoot:Ss,isAuthenticated:Ie});r.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:Ga,archivedTasks:Da,runtimeMode:b,currentWorkspaceId:xe,isAuthenticated:Ie,workspaceCloudSyncEnabled:is,realtimeSyncEnabled:Ua,fetchTasks:on,fetchArchive:Vn,retryWorkspaceCloudSync:cs,resetWorkspaceSyncCursorAndPull:fi,getSyncDiagnostics:$o,__dispatch:{handleUpdateTask:Qo,handleToggleComplete:Gl,handleArchiveTask:ql,handleToggleCancel:Vl,handleToggleInProgress:Fc,handleToggleReview:Ao,handleSubmit:Ql,handleDelete:Co}})},[Ga,Da,b,xe,Ie,is,Ua,on,Vn,cs,fi,$o,Qo,Gl,ql,Vl,Fc,Ao,Ql,Co]);const hs=qe&&qe.tone!=="error"?{message:qe.message,type:"info"}:null,vu=String(S||_.wsBaseUrl||ge||"").trim().replace(/\/+$/,"");return{config:{...o,cloudEnvironment:_.cloudEnvironment||o.cloudEnvironment||"",apiBaseUrl:ge||o.apiBaseUrl,cloudAuthBaseUrl:se||o.cloudAuthBaseUrl,wsBaseUrl:vu||o.wsBaseUrl},isOpen:ee,setIsOpen:Q,activeTab:z,setActiveTab:Ds,currentTheme:Me,setCurrentTheme:nt,configLoaded:Rn,storagePath:Ct,saveSettings:Vd,pathSaved:dt,keyShortcut:pa,setKeyShortcut:hn,globalWeekStartsOn:Ra,locale:An,supportedLocales:Ar,saveLocale:Kd,jsonBackupEnabled:za,setJsonBackupEnabled:ar,manualComplexityEnabled:nn,checklistDropdownEnabled:gr,showTaskCardStatusLabel:yn,setManualComplexityEnabled:xr,mcpHostRoot:ea,setMcpHostRoot:Ss,settingsSection:Be,setSettingsSection:et,runtimeMode:b,workspaceMode:Lt,workspaceSwitchingEnabled:vt,cloudAuthConfigured:U,authRequiredForApi:E,authBlocked:Y,isAuthenticated:Ie,authUserId:Ve,authUserEmail:Et,authUserDisplayName:Wt,authUserAvatarUrl:Ka,authWorkspaceId:Vt,userGlobalSyncStatus:mo,workspaceLastPullAt:Cm,workspaceLastPushAt:ol,workspaceLastErrorAt:Am,userGlobalSyncError:po,workspaceLastErrorMessage:il,workspaceLastSuccessfulSyncAt:qn,workspaceSyncPhase:fo,workspaceSyncSetupIntent:pi,workspaceSyncStatus:xm,workspaceSyncSummary:Id,workspaceSyncRecommendedAction:Fo,workspaceSyncBusy:Im,workspaceSyncPendingChanges:Td,retryUserGlobalSettingsSync:cc,retryWorkspaceCloudSync:cs,resetWorkspaceSyncCursorAndPull:fi,getWorkspaceSyncDiagnostics:$o,hasBetaAccess:Xa,realtimeSyncEnabled:Ua,realtimeSyncFlagSource:er,currentWorkspaceId:xe,currentWorkspaceRole:Rl,availableWorkspaces:Gt,assigneeOptions:Na,workspaceCloudSyncEnabled:is,saveWorkspaceCloudSyncSettings:ho,applyWorkspaceSyncStateSnapshot:Nd,bootstrapState:nc,authSessionResolved:aa,workspaceBootstrapPending:ca,bootstrapPhase:$t,bootstrapError:ba,bootstrapStartedAt:Lr,setupState:Cn,runtimeCapabilities:En,refreshSetupContext:Ei,retryBootstrapChecks:Tl,continueAfterCommercialOnboarding:Qd,saveWorkspaceProfile:jl,fetchWorkspaces:Nr,createWorkspace:Zo,deleteWorkspace:dr,switchWorkspace:Pr,loginWithCredentials:Xd,beginOAuthLogin:Wm,availableAuthProviders:sa,fetchLoginMethods:Li,unlinkLoginMethod:Fm,addPasswordToAccount:Jo,beginOAuthLink:Ml,registerWithCredentials:Nl,updateCurrentUserProfile:eu,requestEmailVerification:qr,confirmEmailVerification:tu,requestPasswordReset:Kr,confirmPasswordReset:au,inspectInviteAcceptance:nu,acceptInviteWithToken:Di,joinInviteWithToken:Pl,logout:Om,showFolderBrowser:Xe,setShowFolderBrowser:ct,folders:ne,files:Ye,currentBrowsePath:kt,fetchFolders:Fi,browserTarget:Ft,setBrowserTarget:Mt,groupBy:ds,setGroupBy:Kn,activeWorkspaceModule:_l,setActiveWorkspaceModule:Pm,emptyColumnMode:So,setEmptyColumnMode:wo,zenMode:_s,setZenMode:Ya,handleSelectPath:qm,handleAddPath:ou,handleRemovePath:Ol,tasks:Ga,loadingTasks:oi,archivedTasks:Da,initiatives:C,workstreams:ht,planningBootstrapTaskSummaries:oe,deletedTasks:as,activeCategories:ka,activeTypes:ra,priorities:an,taxonomyDisplayLabels:xs,approaches:hr,taxonomies:ss,searchQuery:gc,setSearchQuery:Dd,filterCategories:yc,setFilterCategories:wr,filterTypes:yl,setFilterTypes:Ld,filterPriorities:Ja,setFilterPriorities:bi,filterStatus:ko,setFilterStatus:Bd,filterAssignees:kl,setFilterAssignees:Vr,filterTaxonomies:kc,setFilterTaxonomies:_i,hasInitedFilters:vo,sortBy:vc,setSortBy:Sc,sortOrder:vl,setSortOrder:Od,toggleSortOrder:Ho,showArchive:q,setShowArchive:Se,taskScope:we,setTaskScope:Te,clearFilters:Tm,filteredTasks:wc,searchAgnosticTasks:bc,filteredArchive:$d,groupedTasks:Ud,collapsedCategories:Sl,setCollapsedCategories:wl,fetchTasks:on,fetchArchive:Vn,fetchDeletedTasks:lr,fetchPlanningEntities:fa,fetchAssigneeOptions:Ko,createInitiative:ru,updateInitiative:$m,archiveInitiative:Ll,unarchiveInitiative:su,createWorkstream:Um,updateWorkstream:zm,archiveWorkstream:Bl,unarchiveWorkstream:Mc,handleEdit:mu,handleDelete:Co,handleCopyId:Ys,handleToggleComplete:Gl,handleToggleCancel:Vl,handleToggleInProgress:Fc,handleToggleReview:Ao,handleArchiveTask:ql,handleBulkArchive:Kl,handleUnarchive:Ym,handleRestoreDeletedTask:Zl,handlePermanentlyDeleteDeletedTask:pu,handleEmptyDeletedTasks:fu,handleUpdateTask:Qo,editingTaskId:ir,loading:io,error:co,title:ki,setTitle:vi,description:dc,setDescription:hl,checklistItems:qs,setChecklistItems:uc,category:Vs,setCategory:Sr,type:go,setType:Ts,priority:ia,setPriority:Uo,complexity:lc,setComplexity:dl,status:ul,setStatus:yo,approach:ml,setApproach:pl,assignee:fl,setAssignee:gi,scheduledDate:Fn,setScheduledDate:Rs,dueDate:Pd,setDueDate:Md,workstreamInput:On,setWorkstreamInput:yi,formTaxonomies:pc,setFormTaxonomies:wt,comments:gl,newCommentText:wi,setNewCommentText:mc,attachments:Ac,setAttachments:Ii,attachmentsDirty:Hd,setAttachmentsDirty:Ti,descriptionFocused:jm,setDescriptionFocused:xi,showMarkdownHelp:nl,setShowMarkdownHelp:rl,showChecklist:fc,setShowChecklist:ls,showComments:Rm,setShowComments:zd,isCapturingScreenshot:_c,setIsCapturingScreenshot:Cc,handleSubmit:Ql,resetForm:zl,handleAddComment:Xo,handleSetWorkstreamForCurrentTask:Xl,handleOpenTaskById:Oi,returnToPreviousTask:_o,autoSaveState:hu,unsavedModalOpen:Fs,setUnsavedModalOpen:Bn,pendingNavigation:Wn,handleNavigation:Zm,handleClose:Ul,uiNotice:qe,pushNotice:At,clearNotice:Nt,successBanner:hs,taskReturnTrail:Ea,clearReturnToParentTask:Bc,copiedId:Wc,recentlyChangedTaskIds:$s,scheduleWarningPrompt:Jm,confirmScheduleWarning:Qm,cancelScheduleWarning:Xm,tasksScrollRef:Tn,setTasksScrollPos:Eo,exportEnvironment:Wa,setExportEnvironment:Rt,exportWorkflowsPath:Ln,setExportWorkflowsPath:rr,exportResult:Ir,exportingResource:Cs,handleUpdateCategory:Ec,handleRemoveCategory:$l,handleSaveCategory:Dc,handleUpdateCategoryIcon:Ms,handleUpdateCategoryColor:iu,handleSaveType:Es,handleRemoveType:cu,handleUpdateType:lu,handleUpdateTaxonomies:du,handleUpdatePriorities:uu,handleUpdateTaxonomyDisplayLabels:Lc,pathValidation:ci,validatePaths:Vm,getCategoryPaths:Fl,customCategories:no,setCustomCategories:ii,projectRoot:Ue,projectName:yt,mcpScriptPath:ze,serverHostRoot:xn,commentsEndRef:Ed,currentTask:gu,currentTaskWorkstream:yu,currentTaskInitiative:ku,availableWorkflows:$r,initiativeTemplates:Je,availableEnvironments:kr,fetchWorkflows:Ut,fetchInitiativeTemplates:Ma,createInitiativeFromTemplate:Dl,fetchWorkflowTemplate:oa,fetchWorkflowOverrideNames:cn,saveWorkflowTemplateDraft:rn,resetWorkflowTemplateDraft:bs,onExportWorkflows:Ur,settingsModel:fs}}const Wb="modulepreload",Fb=function(e){return"/taskforce/"+e},xh={},vs=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){let m=function(y){return Promise.all(y.map(k=>Promise.resolve(k).then(S=>({status:"fulfilled",value:S}),S=>({status:"rejected",reason:S}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),d=i?.nonce||i?.getAttribute("nonce");o=m(n.map(y=>{if(y=Fb(y),y in xh)return;xh[y]=!0;const k=y.endsWith(".css"),S=k?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${y}"]${S}`))return;const h=document.createElement("link");if(h.rel=k?"stylesheet":Wb,k||(h.as="script"),h.crossOrigin="",h.href=y,d&&h.setAttribute("nonce",d),document.head.appendChild(h),k)return new Promise((g,v)=>{h.addEventListener("load",g),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${y}`)))})}))}function l(i){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=i,window.dispatchEvent(d),!d.defaultPrevented)throw i}return o.then(i=>{for(const d of i||[])d.status==="rejected"&&l(d.reason);return t().catch(l)})},Ob="_filterGlow_1a4uy_8",$b="_floatingButton_1a4uy_18",Ub="_badge_1a4uy_49",zb="_configBadge_1a4uy_66",Hb="_configBadgeActive_1a4uy_76",Gb="_configBadgeRevoked_1a4uy_82",Vb="_configBadgeExpired_1a4uy_88",qb="_header_1a4uy_98",Kb="_headerTitle_1a4uy_113",Zb="_brandIcon_1a4uy_130",Yb="_brandHomeButton_1a4uy_136",Jb="_brandHomeStatic_1a4uy_137",Qb="_brandCloudSuffix_1a4uy_162",Xb="_projectSlash_1a4uy_167",e_="_projectName_1a4uy_174",t_="_taskCountBadge_1a4uy_193",a_="_taskCountBadgeIcon_1a4uy_210",n_="_taskCountBadgeAlert_1a4uy_214",r_="_headerActions_1a4uy_220",s_="_sortDirectionBtn_1a4uy_227",o_="_sortDirectionBtnWidget_1a4uy_234",i_="_form_1a4uy_242",c_="_topRow_1a4uy_254",l_="_field_1a4uy_260",d_="_labelRow_1a4uy_266",u_="_label_1a4uy_266",m_="_manageLink_1a4uy_280",p_="_input_1a4uy_299",f_="_select_1a4uy_300",h_="_textarea_1a4uy_301",g_="_taskIdInlineLink_1a4uy_335",y_="_readOnly_1a4uy_354",k_="_selectWithConfig_1a4uy_362",v_="_configBtn_1a4uy_372",S_="_configBtnActive_1a4uy_402",w_="_hasPath_1a4uy_410",b_="_pathIndicator_1a4uy_415",__="_formActions_1a4uy_421",C_="_hasCancel_1a4uy_428",A_="_submitBtn_1a4uy_432",x_="_cancelBtn_1a4uy_448",I_="_successMessage_1a4uy_480",T_="_errorMessage_1a4uy_486",R_="_successIcon_1a4uy_498",j_="_spinner_1a4uy_518",N_="_spin_1a4uy_518",P_="_boardRefreshIndicator_1a4uy_522",M_="_destructiveBtn_1a4uy_552",E_="_warningBtn_1a4uy_575",D_="_viewTab_1a4uy_598",L_="_deleteBtn_1a4uy_609",B_="_loading_1a4uy_619",W_="_emptyState_1a4uy_625",F_="_taskList_1a4uy_635",O_="_taskIdBadge_1a4uy_641",$_="_taskIdBadgeLabel_1a4uy_663",U_="_copiedId_1a4uy_682",z_="_highlight_1a4uy_688",H_="_modal_1a4uy_700",G_="_priorityEmoji_1a4uy_708",V_="_metaItem_1a4uy_712",q_="_taskFormDateInput_1a4uy_726",K_="_metaBadge_1a4uy_736",Z_="_complexityPill_1a4uy_751",Y_="_complexityDots_1a4uy_755",J_="_dot_1a4uy_761",Q_="_dotFilled_1a4uy_769",X_="_typePill_1a4uy_775",eC="_type_bug_1a4uy_779",tC="_type_feature_1a4uy_783",aC="_type_chore_1a4uy_787",nC="_type_refactor_1a4uy_791",rC="_type_documentation_1a4uy_795",sC="_type_research_1a4uy_799",oC="_type_security_1a4uy_807",iC="_approachPill_1a4uy_812",cC="_approach_evaluate_1a4uy_817",lC="_approach_collaborate_1a4uy_823",dC="_approach_plan_1a4uy_829",uC="_approachActive_1a4uy_835",mC="_statusActionsGroup_1a4uy_840",pC="_statusActionsGroupCompact_1a4uy_846",fC="_statusSelectWrap_1a4uy_850",hC="_statusTaxonomyDropdownWrap_1a4uy_856",gC="_statusTaxonomyDropdown_1a4uy_856",yC="_statusTaxonomyDropdownCompact_1a4uy_864",kC="_statusTaxonomyDropdownIconOnly_1a4uy_868",vC="_taxonomyDropdownButton_1a4uy_873",SC="_taxonomyDropdownButtonContent_1a4uy_890",wC="_statusTaxonomyDropdownIconOnlyPanel_1a4uy_894",bC="_actionBtn_1a4uy_900",_C="_startWorkBtn_1a4uy_924",CC="_workingBtn_1a4uy_933",AC="_pulse_1a4uy_1",xC="_reviewBtn_1a4uy_939",IC="_reviewActiveBtn_1a4uy_949",TC="_reviewPill_1a4uy_955",RC="_archiveTaskBtn_1a4uy_962",jC="_bulkArchiveBtn_1a4uy_971",NC="_bulkDeleteBtn_1a4uy_993",PC="_completeBtn_1a4uy_1034",MC="_completeActiveBtn_1a4uy_1044",EC="_deleteActiveBtn_1a4uy_1050",DC="_disabledBtn_1a4uy_1056",LC="_archiveList_1a4uy_1063",BC="_archiveHeader_1a4uy_1071",WC="_settingsTab_1a4uy_1082",FC="_settingsTabMcpOnly_1a4uy_1091",OC="_settingsTabs_1a4uy_1100",$C="_settingsLayout_1a4uy_1114",UC="_settingsLayoutMcpOnly_1a4uy_1121",zC="_settingsSidebar_1a4uy_1127",HC="_settingsSidebarHeader_1a4uy_1137",GC="_settingsSidebarNav_1a4uy_1146",VC="_settingsSidebarBtn_1a4uy_1155",qC="_settingsSidebarBtnActive_1a4uy_1179",KC="_settingsSidebarGroup_1a4uy_1186",ZC="_settingsSidebarGroupBtn_1a4uy_1192",YC="_settingsSidebarGroupLabel_1a4uy_1196",JC="_settingsSidebarGroupChevron_1a4uy_1200",QC="_settingsSidebarSubnav_1a4uy_1206",XC="_settingsSidebarSubBtn_1a4uy_1213",eA="_appScrollbar_1a4uy_1236",tA="_settingsTabBtn_1a4uy_1240",aA="_settingsTabBtnActive_1a4uy_1266",nA="_settingsContent_1a4uy_1272",rA="_mcpRegistrationHint_1a4uy_1298",sA="_mcpRegistrationPrompt_1a4uy_1309",oA="_mcpAuthRequiredCard_1a4uy_1328",iA="_mcpAuthRequiredIcon_1a4uy_1340",cA="_mcpAuthRequiredBody_1a4uy_1353",lA="_mcpAuthRequiredActions_1a4uy_1360",dA="_settingsToast_1a4uy_1404",uA="_settingsToastSuccess_1a4uy_1421",mA="_settingsToastError_1a4uy_1427",pA="_inputWithPrefix_1a4uy_1433",fA="_pathHint_1a4uy_1440",hA="_settingGroup_1a4uy_1453",gA="_settingTitle_1a4uy_1459",yA="_settingTitleRow_1a4uy_1468",kA="_settingTitleActionBtn_1a4uy_1475",vA="_themeOptions_1a4uy_1495",SA="_buttonGrid_1a4uy_1500",wA="_themeBtn_1a4uy_1512",bA="_activeTheme_1a4uy_1536",_A="_pathInputGroup_1a4uy_1544",CA="_saveSettingsBtn_1a4uy_1553",AA="_shortcutInputWrapper_1a4uy_1574",xA="_inputIcon_1a4uy_1579",IA="_settingHelper_1a4uy_1588",TA="_browseBtn_1a4uy_1595",RA="_inlineCategoryManager_1a4uy_1614",jA="_categoryManager_1a4uy_1625",NA="_categoryList_1a4uy_1631",PA="_categoryChip_1a4uy_1643",MA="_categoryChipLabel_1a4uy_1656",EA="_chipActionBtn_1a4uy_1664",DA="_removeCategoryBtn_1a4uy_1684",LA="_addCategoryForm_1a4uy_1704",BA="_addCategoryBtn_1a4uy_1709",WA="_filesList_1a4uy_1734",FA="_helpLink_1a4uy_1761",OA="_inlineCode_1a4uy_1782",$A="_codeBlock_1a4uy_1793",UA="_taskChildrenSummaryBadges_1a4uy_1817",zA="_taskChildrenProgressBar_1a4uy_1825",HA="_taskChildrenProgressBarSegmentDone_1a4uy_1836",GA="_taskChildrenProgressBarSegmentReview_1a4uy_1842",VA="_taskChildrenProgressBarSegmentInProgress_1a4uy_1848",qA="_taskChildrenProgressBarSegmentBlocked_1a4uy_1854",KA="_taskChildrenProgressText_1a4uy_1860",ZA="_taskChildUnlinkBtn_1a4uy_1869",YA="_aboutText_1a4uy_1887",JA="_versionInfo_1a4uy_1894",QA="_filterBar_1a4uy_1902",XA="_kanbanHintText_1a4uy_1916",ex="_searchContainer_1a4uy_1922",tx="_searchIcon_1a4uy_1929",ax="_searchInput_1a4uy_1937",nx="_searchActive_1a4uy_1963",rx="_searchCount_1a4uy_1968",sx="_clearSearchBtn_1a4uy_1984",ox="_filterRow_1a4uy_2006",ix="_sortLabel_1a4uy_2012",cx="_archiveToggle_1a4uy_2020",lx="_filterContainer_1a4uy_2057",dx="_filterButton_1a4uy_2062",ux="_filterActive_1a4uy_2087",mx="_filterDropdown_1a4uy_2093",px="_filterOption_1a4uy_2108",fx="_filterDivider_1a4uy_2138",hx="_filterSelect_1a4uy_2144",gx="_filterToggleBtn_1a4uy_2185",yx="_inProgressToggle_1a4uy_2207",kx="_activeInProgress_1a4uy_2225",vx="_activeFilter_1a4uy_2234",Sx="_resetFiltersBtn_1a4uy_2244",wx="_categoryChip_disabled_1a4uy_2277",bx="_categoryVisibilityToggle_1a4uy_2287",_x="_editCategoryInput_1a4uy_2300",Cx="_categoryChipActionBtn_1a4uy_2311",Ax="_categoryChipActionBtn_active_1a4uy_2329",xx="_categoryGroup_1a4uy_2334",Ix="_categoryHeader_1a4uy_2342",Tx="_categoryTitle_1a4uy_2356",Rx="_categoryCount_1a4uy_2366",jx="_categoryItems_1a4uy_2372",Nx="_priorityItem_low_1a4uy_2381",Px="_priorityItem_medium_1a4uy_2385",Mx="_priorityItem_high_1a4uy_2389",Ex="_priorityItem_critical_1a4uy_2393",Dx="_priorityPill_low_1a4uy_2397",Lx="_priorityPill_medium_1a4uy_2403",Bx="_priorityPill_high_1a4uy_2409",Wx="_priorityPill_critical_1a4uy_2415",Fx="_selectPriority_low_1a4uy_2430",Ox="_selectPriority_medium_1a4uy_2435",$x="_selectPriority_high_1a4uy_2440",Ux="_selectPriority_critical_1a4uy_2445",zx="_levelSelect_1a4uy_2454",Hx="_levelOption_1a4uy_2467",Gx="_levelOptionFilled_1a4uy_2484",Vx="_levelOption_priority_low_1a4uy_2491",qx="_levelOption_priority_medium_1a4uy_2496",Kx="_levelOption_priority_high_1a4uy_2501",Zx="_levelOption_priority_critical_1a4uy_2506",Yx="_levelOption_complexity_tiny_1a4uy_2513",Jx="_levelOption_complexity_low_1a4uy_2518",Qx="_levelOption_complexity_medium_1a4uy_2523",Xx="_levelOption_complexity_high_1a4uy_2528",eI="_levelOption_complexity_epic_1a4uy_2533",tI="_levelOptionActive_1a4uy_2540",aI="_levelOptionSelected_1a4uy_2545",nI="_levelLabel_1a4uy_2553",rI="_fadeIn_1a4uy_1",sI="_closeConfigBtn_1a4uy_2578",oI="_configItem_1a4uy_2600",iI="_settingsLabel_1a4uy_2606",cI="_settingsHint_1a4uy_2615",lI="_pathList_1a4uy_2622",dI="_pathChip_1a4uy_2629",uI="_pathValid_1a4uy_2642",mI="_pathInvalid_1a4uy_2647",pI="_pathValidIcon_1a4uy_2652",fI="_pathInvalidIcon_1a4uy_2657",hI="_pathText_1a4uy_2662",gI="_removePathBtn_1a4uy_2669",yI="_pathCount_1a4uy_2691",kI="_specialistSection_1a4uy_2714",vI="_toggleHeading_1a4uy_2722",SI="_dropdownList_1a4uy_2762",wI="_specialistBadge_1a4uy_2771",bI="_iconGrid_1a4uy_2801",_I="_iconPickerBtn_1a4uy_2812",CI="_iconPickerBtnActive_1a4uy_2831",AI="_categorySubConfig_1a4uy_2838",xI="_colorPickerRow_1a4uy_2846",II="_colorPickerGrid_1a4uy_2852",TI="_colorSwatch_1a4uy_2859",RI="_colorSwatchActive_1a4uy_2878",jI="_categoryChipIcon_1a4uy_2884",NI="_fieldIconWrapper_1a4uy_2889",PI="_fieldIcon_1a4uy_2889",MI="_field_dynamic_1a4uy_2911",EI="_fieldIcon_dynamic_1a4uy_2917",DI="_categoryTitleIcon_1a4uy_2921",LI="_editActionsHeader_1a4uy_2927",BI="_editActionsGroup_1a4uy_2936",WI="_urlInputGroup_1a4uy_2943",FI="_iconBtn_1a4uy_2956",OI="_stickyActionHeader_1a4uy_2977",$I="_taskHierarchyHeader_1a4uy_2994",UI="_taskHierarchyBadgeRow_1a4uy_3001",zI="_taskHierarchyDivider_1a4uy_3009",HI="_taskHierarchySegment_1a4uy_3015",GI="_taskHierarchyMeta_1a4uy_3022",VI="_taskHierarchyActionBtn_1a4uy_3035",qI="_taskHierarchyEditor_1a4uy_3041",KI="_taskHierarchyInput_1a4uy_3048",ZI="_taskSaveStatus_1a4uy_3057",YI="_taskSaveStatusCenter_1a4uy_3068",JI="_taskSaveStatusError_1a4uy_3076",QI="_headerSuccessFeedback_1a4uy_3080",XI="_slideInUp_1a4uy_1",eT="_successCheck_1a4uy_3092",tT="_scaleIn_1a4uy_1",aT="_primaryUpdateBtn_1a4uy_3128",nT="_secondaryHeaderBtn_1a4uy_3156",rT="_secondaryHeaderBtnDestructive_1a4uy_3177",sT="_commentSection_1a4uy_3190",oT="_attachmentCaptureContainer_1a4uy_3226",iT="_capturePrompt_1a4uy_3234",cT="_previewContainer_1a4uy_3248",lT="_previewHeader_1a4uy_3254",dT="_attachmentCapturePreview_1a4uy_3264",uT="_actions_1a4uy_3271",mT="_primaryButton_1a4uy_3277",pT="_secondaryButton_1a4uy_3292",fT="_iconButton_1a4uy_3307",hT="_attachmentGrid_1a4uy_3329",gT="_attachmentCard_1a4uy_3336",yT="_attachmentPreviewContainer_1a4uy_3350",kT="_contextFileLink_1a4uy_3371",vT="_attachmentActions_1a4uy_3397",ST="_attachmentActionBtn_1a4uy_3411",wT="_attachmentCaptionInput_1a4uy_3433",bT="_hiddenInput_1a4uy_3451",_T="_contextUploadPanel_1a4uy_3455",CT="_contextUploadActions_1a4uy_3463",AT="_contextDropzone_1a4uy_3471",xT="_contextDropzoneActive_1a4uy_3487",IT="_contextDropzonePulse_1a4uy_1",TT="_contextLinkRow_1a4uy_3495",RT="_contextNotice_1a4uy_3501",jT="_documentAttachmentList_1a4uy_3507",NT="_documentAttachmentItem_1a4uy_3514",PT="_documentAttachmentRow_1a4uy_3521",MT="_documentAttachmentLink_1a4uy_3529",ET="_documentAttachmentMain_1a4uy_3543",DT="_documentAttachmentText_1a4uy_3550",LT="_documentAttachmentIcon_1a4uy_3558",BT="_documentAttachmentName_1a4uy_3569",WT="_documentAttachmentType_1a4uy_3578",FT="_documentAttachmentActions_1a4uy_3591",OT="_documentAttachmentActionBtn_1a4uy_3597",$T="_documentAttachmentCaptionInput_1a4uy_3618",UT="_brokenImage_1a4uy_3646",zT="_brokenImagePlaceholder_1a4uy_3654",HT="_regionOverlay_1a4uy_3668",GT="_selectionBox_1a4uy_3679",VT="_exportRow_1a4uy_3687",qT="_exportItem_1a4uy_3692",KT="_taxonomyDrillDown_1a4uy_3701",ZT="_drillDownList_1a4uy_3711",YT="_drillDownSection_1a4uy_3719",JT="_drillDownSectionHeader_1a4uy_3725",QT="_drillDownSectionTitle_1a4uy_3732",XT="_drillDownItem_1a4uy_3741",eR="_drillDownItemDimmed_1a4uy_3763",tR="_drillDownItemActive_1a4uy_3771",aR="_drillDownItemInfo_1a4uy_3776",nR="_drillDownItemText_1a4uy_3782",rR="_drillDownItemLabel_1a4uy_3787",sR="_drillDownItemSubtext_1a4uy_3792",oR="_addTaxonomyBtnSmall_1a4uy_3797",iR="_taxonomyDetailView_1a4uy_3819",cR="_slideIn_1a4uy_1",lR="_detailHeader_1a4uy_3839",dR="_detailTitle_1a4uy_3848",uR="_detailContent_1a4uy_3855",mR="_createOverlay_1a4uy_3862",pR="_createDialog_1a4uy_3874",fR="_zoomIn_1a4uy_1",hR="_dialogActions_1a4uy_3902",gR="_settingsGroup_1a4uy_3920",yR="_settingsItem_1a4uy_3926",kR="_settingLabelGroup_1a4uy_3932",vR="_settingLabel_1a4uy_3932",SR="_settingDescription_1a4uy_3944",wR="_settingInput_1a4uy_3951",bR="_codeBlockWrapper_1a4uy_3974",_R="_codeHeader_1a4uy_3983",CR="_codeHeaderActions_1a4uy_3994",AR="_codeLabel_1a4uy_4001",xR="_codeHeaderDescription_1a4uy_4009",IR="_mcpTokenCardBody_1a4uy_4017",TR="_mcpTokenFormGrid_1a4uy_4025",RR="_mcpTokenOutputWrap_1a4uy_4032",jR="_mcpTokenValueField_1a4uy_4039",NR="_mcpTokenValueText_1a4uy_4049",PR="_mcpTokenValueInput_1a4uy_4062",MR="_mcpTokenActionRow_1a4uy_4067",ER="_copyBtn_1a4uy_4090",DR="_copyBtnActive_1a4uy_4111",LR="_copyBtnNeutralActive_1a4uy_4117",BR="_headerDivider_1a4uy_4135",WR="_groupByContainer_1a4uy_4141",FR="_groupByLabel_1a4uy_4149",OR="_groupBySelect_1a4uy_4154",$R="_viewSwitcher_1a4uy_4176",UR="_selectWithIcon_1a4uy_4184",zR="_marginBottom16_1a4uy_4188",HR="_headerDraggable_1a4uy_4193",GR="_headerDragging_1a4uy_4197",VR="_filterSelectSort_1a4uy_4205",qR="_archiveRow_1a4uy_4209",KR="_taskScopeToggle_1a4uy_4215",ZR="_taskScopeTabs_1a4uy_4223",YR="_taskScopeTab_1a4uy_4223",JR="_taskScopeTabActive_1a4uy_4256",QR="_taskToolbarAction_1a4uy_4268",XR="_overlayHighZ_1a4uy_4284",ej="_savedText_1a4uy_4294",tj="_shortcutInput_1a4uy_1574",aj="_saveSettingsBtnWrapper_1a4uy_4302",nj="_marginBottom12_1a4uy_4306",rj="_exportRowGrid_1a4uy_4310",sj="_settingSubtitleCustom_1a4uy_4315",oj="_capitalize_1a4uy_4321",ij="_marginTop12_1a4uy_4325",cj="_marginTop16_1a4uy_4329",lj="_labelGroupFlex_1a4uy_4333",dj="_codeBlockWrapperCustom_1a4uy_4339",uj="_kanbanWrapper_1a4uy_4345",mj="_kanbanContainer_1a4uy_4353",pj="_kanbanTopScroll_1a4uy_4375",fj="_kanbanTopScrollSpacer_1a4uy_4384",hj="_kanbanColumn_1a4uy_4388",gj="_kanbanColumnSticky_1a4uy_4404",yj="_kanbanColumnCollapsed_1a4uy_4410",kj="_kanbanColumnPast_1a4uy_4415",vj="_kanbanColumnSelectedDay_1a4uy_4420",Sj="_kanbanHeader_1a4uy_4427",wj="_kanbanCount_1a4uy_4437",bj="_kanbanHeaderDraggable_1a4uy_4457",_j="_kanbanHeaderPanning_1a4uy_4461",Cj="_kanbanQuickAdd_1a4uy_4465",Aj="_kanbanColorDot_1a4uy_4486",xj="_kanbanDroppable_1a4uy_4498",Ij="_kanbanDroppableScroll_1a4uy_4507",Tj="_kanbanEmpty_1a4uy_4517",Rj="_kanbanCard_1a4uy_4527",jj="_kanbanCardWrapper_1a4uy_4537",Nj="_taxonomyDropdownActive_1a4uy_4545",Pj="_kanbanCardWrapperRaised_1a4uy_4549",Mj="_kanbanCardTitle_1a4uy_4553",Ej="_kanbanBadges_1a4uy_4557",Dj="_kanbanBadge_1a4uy_4557",Lj="_headerFlex_1a4uy_4573",Bj="_marginBottom8_1a4uy_4580",Wj="_marginBottom20_1a4uy_4584",Fj="_configPanel_1a4uy_4588",Oj="_configPanelLarge_1a4uy_4597",$j="_subLabelBlock_1a4uy_4601",Uj="_subLabelBlock12_1a4uy_4608",zj="_flexBetween_1a4uy_4612",Hj="_flexBetweenCenter_1a4uy_4619",Gj="_deleteBtnSmall_1a4uy_4624",Vj="_deleteBtnMedium_1a4uy_4630",qj="_trashIcon_1a4uy_4637",Kj="_gridConfig_1a4uy_4641",Zj="_flexColGap4_1a4uy_4648",Yj="_flexColGap4Center_1a4uy_4654",Jj="_flex1_1a4uy_4661",Qj="_flexCol_1a4uy_4648",Xj="_flexGrow1_1a4uy_4671",eN="_inputLabel_1a4uy_4675",tN="_inputLabelBlock_1a4uy_4679",aN="_checkboxInput_1a4uy_4685",nN="_configDividerMargin_1a4uy_4691",rN="_configDividerMargin24_1a4uy_4696",sN="_pathListMargin_1a4uy_4701",oN="_cancelBtnRed_1a4uy_4705",iN="_code_1a4uy_1793",cN="_workflowList_1a4uy_4732",lN="_workflowActions_1a4uy_4740",dN="_textBtn_1a4uy_4749",uN="_workflowGrid_1a4uy_4763",mN="_checkboxLabel_1a4uy_4771",pN="_checkboxSmall_1a4uy_4785",fN="_docWorkspace_1a4uy_4804",hN="_docIndexPanel_1a4uy_4815",gN="_docWorkspaceTrayMode_1a4uy_4827",yN="_docViewerPanel_1a4uy_4827",kN="_docWorkspaceTrayOpen_1a4uy_4832",vN="_docTrayPanel_1a4uy_4836",SN="_docTrayPanelOpen_1a4uy_4860",wN="_docSpinning_1a4uy_4868",bN="_docSpin_1a4uy_4868",_N="_docViewerEmpty_1a4uy_4887",CN="_agentsModuleRoot_1a4uy_4902",AN="_agentsModuleWithTray_1a4uy_4914",xN="_agentsModuleTrayOpen_1a4uy_4918",IN="_agentTrayPanel_1a4uy_4922",TN="_agentTrayPanelOpen_1a4uy_4945",RN="_agentTrayHeader_1a4uy_4953",jN="_agentTrayTitle_1a4uy_4968",NN="_agentTrayContent_1a4uy_4980",PN="_agentTrayContentInner_1a4uy_4988",MN="_agentsModuleContent_1a4uy_4992",EN="_agentsModuleGroup_1a4uy_4997",DN="_marginTop24_1a4uy_5001",LN="_settingSubTitle_1a4uy_5005",BN="_dangerBtn_1a4uy_5014",WN="_aiProfilesExplorer_1a4uy_5030",FN="_aiProfilesListPane_1a4uy_5041",ON="_aiProfilesList_1a4uy_5041",$N="_aiProfilesSection_1a4uy_5060",UN="_aiProfilesSectionHeader_1a4uy_5066",zN="_aiProfileGroup_1a4uy_5074",HN="_aiProfileGroupSelected_1a4uy_5097",GN="_aiProfileGroupDuplicate_1a4uy_5106",VN="_aiProfileGroupHeader_1a4uy_5111",qN="_aiProfileGroupAvatar_1a4uy_5119",KN="_aiProfileGroupIdentity_1a4uy_5141",ZN="_aiProfileName_1a4uy_5150",YN="_aiProfileHandle_1a4uy_5158",JN="_aiProfileRole_1a4uy_5159",QN="_aiProfileSeatSummary_1a4uy_5170",XN="_aiProfileSeatScopeIcon_1a4uy_5179",eP="_aiProfileSeatScopeIconDetail_1a4uy_5190",tP="_aiProfileSeatScopeIconCloud_1a4uy_5195",aP="_aiProfileSeatScopeIconLocal_1a4uy_5199",nP="_aiProfileDuplicateBadge_1a4uy_5203",rP="_aiProfileMergeSection_1a4uy_5215",sP="_aiProfileMergeRow_1a4uy_5222",oP="_aiProfileIdChip_1a4uy_5229",iP="_aiProfileKeepBadge_1a4uy_5241",cP="_aiProfileMergeActions_1a4uy_5255",lP="_aiProfileDetailPane_1a4uy_5262",dP="_aiProfileDetailCard_1a4uy_5268",uP="_aiProfileDetailHero_1a4uy_5280",mP="_aiProfileDetailIcon_1a4uy_5286",pP="_aiProfileDetailAvatar_1a4uy_5300",fP="_aiProfileDetailHeading_1a4uy_5304",hP="_aiProfileDetailTitleRow_1a4uy_5309",gP="_aiProfileDetailTitle_1a4uy_5309",yP="_aiProfileDetailMetaRow_1a4uy_5324",kP="_aiProfileDetailHandle_1a4uy_5332",vP="_aiProfileDetailRole_1a4uy_5337",SP="_aiProfileDetailLinkedCount_1a4uy_5344",wP="_aiProfileDetailDescription_1a4uy_5349",bP="_aiProfileSignatureColor_1a4uy_5356",_P="_aiProfileSignatureSwatch_1a4uy_5366",CP="_aiProfileDetailDataList_1a4uy_5376",AP="_aiProfileDetailDataGroup_1a4uy_5385",xP="_aiProfileDetailDateGroup_1a4uy_5392",IP="_aiProfileDetailDataRow_1a4uy_5397",TP="_aiProfileDetailDataLabel_1a4uy_5406",RP="_aiProfileDetailDataValue_1a4uy_5413",jP="_aiProfileStatusSelect_1a4uy_5419",NP="_aiProfileInstanceSection_1a4uy_5461",PP="_aiProfileInstanceSectionHeader_1a4uy_5467",MP="_aiProfileInstanceList_1a4uy_5477",EP="_aiProfileInstanceCard_1a4uy_5483",DP="_aiProfileIdFooter_1a4uy_5496",LP="_aiProfileIdFooterValue_1a4uy_5506",BP="_aiProfileDangerTextButton_1a4uy_5516",WP="_aiProfileInstanceTopRow_1a4uy_5548",FP="_aiProfileInstanceName_1a4uy_5555",OP="_aiProfileInstanceMeta_1a4uy_5562",$P="_aiProfileInlineError_1a4uy_5570",p={filterGlow:Ob,floatingButton:$b,badge:Ub,configBadge:zb,configBadgeActive:Hb,configBadgeRevoked:Gb,configBadgeExpired:Vb,header:qb,headerTitle:Kb,brandIcon:Zb,brandHomeButton:Yb,brandHomeStatic:Jb,brandCloudSuffix:Qb,projectSlash:Xb,projectName:e_,taskCountBadge:t_,taskCountBadgeIcon:a_,taskCountBadgeAlert:n_,headerActions:r_,sortDirectionBtn:s_,sortDirectionBtnWidget:o_,form:i_,topRow:c_,field:l_,labelRow:d_,label:u_,manageLink:m_,input:p_,select:f_,textarea:h_,taskIdInlineLink:g_,readOnly:y_,selectWithConfig:k_,configBtn:v_,configBtnActive:S_,hasPath:w_,pathIndicator:b_,formActions:__,hasCancel:C_,submitBtn:A_,cancelBtn:x_,successMessage:I_,errorMessage:T_,successIcon:R_,spinner:j_,spin:N_,boardRefreshIndicator:P_,destructiveBtn:M_,warningBtn:E_,viewTab:D_,deleteBtn:L_,loading:B_,emptyState:W_,taskList:F_,taskIdBadge:O_,taskIdBadgeLabel:$_,copiedId:U_,highlight:z_,modal:H_,priorityEmoji:G_,metaItem:V_,taskFormDateInput:q_,metaBadge:K_,complexityPill:Z_,complexityDots:Y_,dot:J_,dotFilled:Q_,typePill:X_,type_bug:eC,type_feature:tC,type_chore:aC,type_refactor:nC,type_documentation:rC,type_research:sC,"type_ui-ux":"_type_ui-ux_1a4uy_803",type_security:oC,approachPill:iC,approach_evaluate:cC,approach_collaborate:lC,approach_plan:dC,approachActive:uC,statusActionsGroup:mC,statusActionsGroupCompact:pC,statusSelectWrap:fC,statusTaxonomyDropdownWrap:hC,statusTaxonomyDropdown:gC,statusTaxonomyDropdownCompact:yC,statusTaxonomyDropdownIconOnly:kC,taxonomyDropdownButton:vC,taxonomyDropdownButtonContent:SC,statusTaxonomyDropdownIconOnlyPanel:wC,actionBtn:bC,startWorkBtn:_C,workingBtn:CC,pulse:AC,reviewBtn:xC,reviewActiveBtn:IC,reviewPill:TC,archiveTaskBtn:RC,bulkArchiveBtn:jC,bulkDeleteBtn:NC,completeBtn:PC,completeActiveBtn:MC,deleteActiveBtn:EC,disabledBtn:DC,archiveList:LC,archiveHeader:BC,settingsTab:WC,settingsTabMcpOnly:FC,settingsTabs:OC,settingsLayout:$C,settingsLayoutMcpOnly:UC,settingsSidebar:zC,settingsSidebarHeader:HC,settingsSidebarNav:GC,settingsSidebarBtn:VC,settingsSidebarBtnActive:qC,settingsSidebarGroup:KC,settingsSidebarGroupBtn:ZC,settingsSidebarGroupLabel:YC,settingsSidebarGroupChevron:JC,settingsSidebarSubnav:QC,settingsSidebarSubBtn:XC,appScrollbar:eA,settingsTabBtn:tA,settingsTabBtnActive:aA,settingsContent:nA,mcpRegistrationHint:rA,mcpRegistrationPrompt:sA,mcpAuthRequiredCard:oA,mcpAuthRequiredIcon:iA,mcpAuthRequiredBody:cA,mcpAuthRequiredActions:lA,settingsToast:dA,settingsToastSuccess:uA,settingsToastError:mA,inputWithPrefix:pA,pathHint:fA,settingGroup:hA,settingTitle:gA,settingTitleRow:yA,settingTitleActionBtn:kA,themeOptions:vA,buttonGrid:SA,themeBtn:wA,activeTheme:bA,pathInputGroup:_A,saveSettingsBtn:CA,shortcutInputWrapper:AA,inputIcon:xA,settingHelper:IA,browseBtn:TA,inlineCategoryManager:RA,categoryManager:jA,categoryList:NA,categoryChip:PA,categoryChipLabel:MA,chipActionBtn:EA,removeCategoryBtn:DA,addCategoryForm:LA,addCategoryBtn:BA,filesList:WA,helpLink:FA,inlineCode:OA,codeBlock:$A,taskChildrenSummaryBadges:UA,taskChildrenProgressBar:zA,taskChildrenProgressBarSegmentDone:HA,taskChildrenProgressBarSegmentReview:GA,taskChildrenProgressBarSegmentInProgress:VA,taskChildrenProgressBarSegmentBlocked:qA,taskChildrenProgressText:KA,taskChildUnlinkBtn:ZA,aboutText:YA,versionInfo:JA,filterBar:QA,kanbanHintText:XA,searchContainer:ex,searchIcon:tx,searchInput:ax,searchActive:nx,searchCount:rx,clearSearchBtn:sx,filterRow:ox,sortLabel:ix,archiveToggle:cx,filterContainer:lx,filterButton:dx,filterActive:ux,filterDropdown:mx,filterOption:px,filterDivider:fx,filterSelect:hx,filterToggleBtn:gx,inProgressToggle:yx,activeInProgress:kx,activeFilter:vx,resetFiltersBtn:Sx,categoryChip_disabled:wx,categoryVisibilityToggle:bx,editCategoryInput:_x,categoryChipActionBtn:Cx,categoryChipActionBtn_active:Ax,categoryGroup:xx,categoryHeader:Ix,categoryTitle:Tx,categoryCount:Rx,categoryItems:jx,priorityItem_low:Nx,priorityItem_medium:Px,priorityItem_high:Mx,priorityItem_critical:Ex,priorityPill_low:Dx,priorityPill_medium:Lx,priorityPill_high:Bx,priorityPill_critical:Wx,selectPriority_low:Fx,selectPriority_medium:Ox,selectPriority_high:$x,selectPriority_critical:Ux,"critical-glow":"_critical-glow_1a4uy_1",levelSelect:zx,levelOption:Hx,levelOptionFilled:Gx,levelOption_priority_low:Vx,levelOption_priority_medium:qx,levelOption_priority_high:Kx,levelOption_priority_critical:Zx,levelOption_complexity_tiny:Yx,levelOption_complexity_low:Jx,levelOption_complexity_medium:Qx,levelOption_complexity_high:Xx,levelOption_complexity_epic:eI,levelOptionActive:tI,levelOptionSelected:aI,levelLabel:nI,fadeIn:rI,closeConfigBtn:sI,configItem:oI,settingsLabel:iI,settingsHint:cI,pathList:lI,pathChip:dI,pathValid:uI,pathInvalid:mI,pathValidIcon:pI,pathInvalidIcon:fI,pathText:hI,removePathBtn:gI,pathCount:yI,specialistSection:kI,toggleHeading:vI,dropdownList:SI,specialistBadge:wI,iconGrid:bI,iconPickerBtn:_I,iconPickerBtnActive:CI,categorySubConfig:AI,colorPickerRow:xI,colorPickerGrid:II,colorSwatch:TI,colorSwatchActive:RI,categoryChipIcon:jI,fieldIconWrapper:NI,fieldIcon:PI,field_dynamic:MI,fieldIcon_dynamic:EI,categoryTitleIcon:DI,editActionsHeader:LI,editActionsGroup:BI,urlInputGroup:WI,iconBtn:FI,stickyActionHeader:OI,taskHierarchyHeader:$I,taskHierarchyBadgeRow:UI,taskHierarchyDivider:zI,taskHierarchySegment:HI,taskHierarchyMeta:GI,taskHierarchyActionBtn:VI,taskHierarchyEditor:qI,taskHierarchyInput:KI,taskSaveStatus:ZI,taskSaveStatusCenter:YI,taskSaveStatusError:JI,headerSuccessFeedback:QI,slideInUp:XI,successCheck:eT,scaleIn:tT,primaryUpdateBtn:aT,secondaryHeaderBtn:nT,secondaryHeaderBtnDestructive:rT,commentSection:sT,attachmentCaptureContainer:oT,capturePrompt:iT,previewContainer:cT,previewHeader:lT,attachmentCapturePreview:dT,actions:uT,primaryButton:mT,secondaryButton:pT,iconButton:fT,attachmentGrid:hT,attachmentCard:gT,attachmentPreviewContainer:yT,contextFileLink:kT,attachmentActions:vT,attachmentActionBtn:ST,attachmentCaptionInput:wT,hiddenInput:bT,contextUploadPanel:_T,contextUploadActions:CT,contextDropzone:AT,contextDropzoneActive:xT,contextDropzonePulse:IT,contextLinkRow:TT,contextNotice:RT,documentAttachmentList:jT,documentAttachmentItem:NT,documentAttachmentRow:PT,documentAttachmentLink:MT,documentAttachmentMain:ET,documentAttachmentText:DT,documentAttachmentIcon:LT,documentAttachmentName:BT,documentAttachmentType:WT,documentAttachmentActions:FT,documentAttachmentActionBtn:OT,documentAttachmentCaptionInput:$T,brokenImage:UT,brokenImagePlaceholder:zT,regionOverlay:HT,selectionBox:GT,exportRow:VT,exportItem:qT,taxonomyDrillDown:KT,drillDownList:ZT,drillDownSection:YT,drillDownSectionHeader:JT,drillDownSectionTitle:QT,drillDownItem:XT,drillDownItemDimmed:eR,drillDownItemActive:tR,drillDownItemInfo:aR,drillDownItemText:nR,drillDownItemLabel:rR,drillDownItemSubtext:sR,addTaxonomyBtnSmall:oR,taxonomyDetailView:iR,slideIn:cR,detailHeader:lR,detailTitle:dR,detailContent:uR,createOverlay:mR,createDialog:pR,zoomIn:fR,dialogActions:hR,settingsGroup:gR,settingsItem:yR,settingLabelGroup:kR,settingLabel:vR,settingDescription:SR,settingInput:wR,codeBlockWrapper:bR,codeHeader:_R,codeHeaderActions:CR,codeLabel:AR,codeHeaderDescription:xR,mcpTokenCardBody:IR,mcpTokenFormGrid:TR,mcpTokenOutputWrap:RR,mcpTokenValueField:jR,mcpTokenValueText:NR,mcpTokenValueInput:PR,mcpTokenActionRow:MR,copyBtn:ER,copyBtnActive:DR,copyBtnNeutralActive:LR,headerDivider:BR,groupByContainer:WR,groupByLabel:FR,groupBySelect:OR,viewSwitcher:$R,selectWithIcon:UR,marginBottom16:zR,headerDraggable:HR,headerDragging:GR,filterSelectSort:VR,archiveRow:qR,taskScopeToggle:KR,taskScopeTabs:ZR,taskScopeTab:YR,taskScopeTabActive:JR,taskToolbarAction:QR,overlayHighZ:XR,savedText:ej,shortcutInput:tj,saveSettingsBtnWrapper:aj,marginBottom12:nj,exportRowGrid:rj,settingSubtitleCustom:sj,capitalize:oj,marginTop12:ij,marginTop16:cj,labelGroupFlex:lj,codeBlockWrapperCustom:dj,kanbanWrapper:uj,kanbanContainer:mj,kanbanTopScroll:pj,kanbanTopScrollSpacer:fj,kanbanColumn:hj,kanbanColumnSticky:gj,kanbanColumnCollapsed:yj,kanbanColumnPast:kj,kanbanColumnSelectedDay:vj,kanbanHeader:Sj,kanbanCount:wj,kanbanHeaderDraggable:bj,kanbanHeaderPanning:_j,kanbanQuickAdd:Cj,kanbanColorDot:Aj,kanbanDroppable:xj,kanbanDroppableScroll:Ij,kanbanEmpty:Tj,kanbanCard:Rj,kanbanCardWrapper:jj,taxonomyDropdownActive:Nj,kanbanCardWrapperRaised:Pj,kanbanCardTitle:Mj,kanbanBadges:Ej,kanbanBadge:Dj,headerFlex:Lj,marginBottom8:Bj,marginBottom20:Wj,configPanel:Fj,configPanelLarge:Oj,subLabelBlock:$j,subLabelBlock12:Uj,flexBetween:zj,flexBetweenCenter:Hj,deleteBtnSmall:Gj,deleteBtnMedium:Vj,trashIcon:qj,gridConfig:Kj,flexColGap4:Zj,flexColGap4Center:Yj,flex1:Jj,flexCol:Qj,flexGrow1:Xj,inputLabel:eN,inputLabelBlock:tN,checkboxInput:aN,configDividerMargin:nN,configDividerMargin24:rN,pathListMargin:sN,cancelBtnRed:oN,code:iN,workflowList:cN,workflowActions:lN,textBtn:dN,workflowGrid:uN,checkboxLabel:mN,checkboxSmall:pN,docWorkspace:fN,docIndexPanel:hN,docWorkspaceTrayMode:gN,docViewerPanel:yN,docWorkspaceTrayOpen:kN,docTrayPanel:vN,docTrayPanelOpen:SN,docSpinning:wN,docSpin:bN,docViewerEmpty:_N,agentsModuleRoot:CN,agentsModuleWithTray:AN,agentsModuleTrayOpen:xN,agentTrayPanel:IN,agentTrayPanelOpen:TN,agentTrayHeader:RN,agentTrayTitle:jN,agentTrayContent:NN,agentTrayContentInner:PN,agentsModuleContent:MN,agentsModuleGroup:EN,marginTop24:DN,settingSubTitle:LN,dangerBtn:BN,aiProfilesExplorer:WN,aiProfilesListPane:FN,aiProfilesList:ON,aiProfilesSection:$N,aiProfilesSectionHeader:UN,aiProfileGroup:zN,aiProfileGroupSelected:HN,aiProfileGroupDuplicate:GN,aiProfileGroupHeader:VN,aiProfileGroupAvatar:qN,aiProfileGroupIdentity:KN,aiProfileName:ZN,aiProfileHandle:YN,aiProfileRole:JN,aiProfileSeatSummary:QN,aiProfileSeatScopeIcon:XN,aiProfileSeatScopeIconDetail:eP,aiProfileSeatScopeIconCloud:tP,aiProfileSeatScopeIconLocal:aP,aiProfileDuplicateBadge:nP,aiProfileMergeSection:rP,aiProfileMergeRow:sP,aiProfileIdChip:oP,aiProfileKeepBadge:iP,aiProfileMergeActions:cP,aiProfileDetailPane:lP,aiProfileDetailCard:dP,aiProfileDetailHero:uP,aiProfileDetailIcon:mP,aiProfileDetailAvatar:pP,aiProfileDetailHeading:fP,aiProfileDetailTitleRow:hP,aiProfileDetailTitle:gP,aiProfileDetailMetaRow:yP,aiProfileDetailHandle:kP,aiProfileDetailRole:vP,aiProfileDetailLinkedCount:SP,aiProfileDetailDescription:wP,aiProfileSignatureColor:bP,aiProfileSignatureSwatch:_P,aiProfileDetailDataList:CP,aiProfileDetailDataGroup:AP,aiProfileDetailDateGroup:xP,aiProfileDetailDataRow:IP,aiProfileDetailDataLabel:TP,aiProfileDetailDataValue:RP,aiProfileStatusSelect:jP,aiProfileInstanceSection:NP,aiProfileInstanceSectionHeader:PP,aiProfileInstanceList:MP,aiProfileInstanceCard:EP,aiProfileIdFooter:DP,aiProfileIdFooterValue:LP,aiProfileDangerTextButton:BP,aiProfileInstanceTopRow:WP,aiProfileInstanceName:FP,aiProfileInstanceMeta:OP,aiProfileInlineError:$P},UP="_standaloneWrapper_1r0om_1",zP="_standalonePage_1r0om_11",HP="_standaloneHeader_1r0om_21",GP="_standaloneTitle_1r0om_27",VP="_standaloneContent_1r0om_31",qP="_workspaceToolRail_1r0om_37",KP="_workspaceToolRailMain_1r0om_54",ZP="_workspaceToolRailBottom_1r0om_62",YP="_workspaceToolRailDivider_1r0om_72",JP="_workspaceToolButton_1r0om_79",QP="_workspaceToolButtonActive_1r0om_99",XP="_workspaceToolButtonDisabled_1r0om_106",e0="_headerTitleWidget_1r0om_137",ta={standaloneWrapper:UP,standalonePage:zP,standaloneHeader:HP,standaloneTitle:GP,standaloneContent:VP,workspaceToolRail:qP,workspaceToolRailMain:KP,workspaceToolRailBottom:ZP,workspaceToolRailDivider:YP,workspaceToolButton:JP,workspaceToolButtonActive:QP,workspaceToolButtonDisabled:XP,headerTitleWidget:e0},t0="_overlay_11v7l_1",a0="_browser_11v7l_16",n0="_header_11v7l_27",r0="_pathInfo_11v7l_36",s0="_actions_11v7l_52",o0="_list_11v7l_57",i0="_item_11v7l_63",c0="_itemCurrent_11v7l_80",l0="_itemFile_11v7l_86",d0="_empty_11v7l_90",ja={overlay:t0,browser:a0,header:n0,pathInfo:r0,actions:s0,list:o0,item:i0,itemCurrent:c0,itemFile:l0,empty:d0},u0="_overlay_1hk7m_2",m0="_overlayHighZ_1hk7m_15",p0="_modal_1hk7m_20",f0="_draggableModal_1hk7m_46",h0="_draggableHeader_1hk7m_53",g0="_headerActions_1hk7m_61",y0="_modalContent_1hk7m_69",k0="_form_1hk7m_80",v0="_formActions_1hk7m_91",S0="_modalFooter_1hk7m_98",w0="_modalSizeSm_1hk7m_104",b0="_modalSizeMd_1hk7m_108",_0="_modalSizeMdWide_1hk7m_112",C0="_modalSizeLg_1hk7m_116",A0="_modalSizeXl_1hk7m_120",x0="_modalSizeFull_1hk7m_124",I0="_settingsViewModal_1hk7m_129",T0="_unsavedOverlay_1hk7m_148",R0="_unsavedModal_1hk7m_153",j0="_unsavedHeader_1hk7m_159",N0="_unsavedTitle_1hk7m_164",P0="_unsavedContent_1hk7m_168",M0="_unsavedText_1hk7m_172",E0="_unsavedActions_1hk7m_177",xt={overlay:u0,overlayHighZ:m0,modal:p0,draggableModal:f0,draggableHeader:h0,headerActions:g0,modalContent:y0,form:k0,formActions:v0,modalFooter:S0,modalSizeSm:w0,modalSizeMd:b0,modalSizeMdWide:_0,modalSizeLg:C0,modalSizeXl:A0,modalSizeFull:x0,settingsViewModal:I0,unsavedOverlay:T0,unsavedModal:R0,unsavedHeader:j0,unsavedTitle:N0,unsavedContent:P0,unsavedText:M0,unsavedActions:E0};function D0(e){const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),n={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return n[t]?n[t]:`${e}s`}function Vi({label:e,options:t,selected:n,onChange:s,variant:o="label",containerStyle:l}){const[i,d]=r.useState(!1),m=r.useRef(null);r.useEffect(()=>{const _=I=>{m.current&&!m.current.contains(I.target)&&d(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const y=_=>{n.includes(_)?s(n.filter(I=>I!==_)):s([...n,_])},k=t.length>0&&t.every(_=>{const I=o==="label"?_.label:_.value;return n.includes(I)}),S=!t.some(_=>{const I=o==="label"?_.label:_.value;return n.includes(I)}),h=()=>{s(k?[]:t.map(_=>o==="label"?_.label:_.value))},g=t.filter(_=>{const I=o==="label"?_.label:_.value;return n.includes(I)}).length,v=D0(e),A=k?`All ${v}`:S?`No ${v}`:g===1?`1 ${e}`:`${g} ${v}`;return a.jsxs("div",{className:p.filterContainer,ref:m,style:l,children:[a.jsxs("button",{className:`${p.filterButton} ${k?"":p.filterActive}`,onClick:()=>d(!i),title:`Filter by ${e}`,children:[a.jsx("span",{children:A}),a.jsx(tl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&a.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,children:[a.jsxs("div",{className:p.filterOption,onClick:h,children:[a.jsx("input",{type:"checkbox",checked:k,onChange:()=>{}}),a.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),a.jsx("div",{className:p.filterDivider}),t.map(_=>{const I=o==="label"?_.label:_.value,B=n.includes(I);return a.jsxs("div",{className:p.filterOption,onClick:()=>y(I),children:[a.jsx("input",{type:"checkbox",checked:B,onChange:()=>{}}),a.jsx("span",{children:_.label})]},_.value)})]})]})}const L0="_taskItem_zvr7q_1",B0="_compressed_zvr7q_20",W0="_taskHeader_zvr7q_25",F0="_taskReferenceCluster_zvr7q_30",O0="_taskMeta_zvr7q_34",$0="_taskTitle_zvr7q_40",U0="_taskItemRecentlyChanged_zvr7q_67",z0="_assigneeAvatarImage_zvr7q_107",H0="_assigneeAvatarIndicator_zvr7q_115",G0="_assigneeAvatarEmpty_zvr7q_137",V0="_inProgress_zvr7q_164",q0="_onHold_zvr7q_175",K0="_readyForReview_zvr7q_186",Z0="_completed_zvr7q_197",Y0="_cancelled_zvr7q_208",J0="_archived_zvr7q_219",Q0="_taskContent_zvr7q_229",X0="_kanbanCardOverlay_zvr7q_238",e1="_taskReferenceText_zvr7q_277",t1="_taskReferenceDivider_zvr7q_286",a1="_taskActions_zvr7q_293",n1="_taskMetaCompact_zvr7q_318",r1="_taskMetaRow_zvr7q_325",s1="_taskMetaBadgeGroup_zvr7q_333",o1="_taskDescription_zvr7q_339",i1="_taskLatestComment_zvr7q_398",c1="_taskCancellationReason_zvr7q_419",l1="_archiveBadge_zvr7q_573",d1="_attachmentThumbnails_zvr7q_578",u1="_attachmentImageRow_zvr7q_585",m1="_attachmentDocumentList_zvr7q_592",p1="_attachmentThumbnail_zvr7q_578",f1="_contextDocThumb_zvr7q_625",h1="_contextDocMain_zvr7q_651",g1="_contextDocText_zvr7q_658",y1="_contextDocIcon_zvr7q_666",k1="_contextDocName_zvr7q_677",v1="_contextDocType_zvr7q_687",S1="_taskSpecialists_zvr7q_699",w1="_taxonomiesList_zvr7q_708",Yt={taskItem:L0,compressed:B0,taskHeader:W0,taskReferenceCluster:F0,taskMeta:O0,taskTitle:$0,taskItemRecentlyChanged:U0,assigneeAvatarImage:z0,assigneeAvatarIndicator:H0,assigneeAvatarEmpty:G0,inProgress:V0,onHold:q0,readyForReview:K0,completed:Z0,cancelled:Y0,archived:J0,taskContent:Q0,kanbanCardOverlay:X0,taskReferenceText:e1,taskReferenceDivider:t1,taskActions:a1,taskMetaCompact:n1,taskMetaRow:r1,taskMetaBadgeGroup:s1,taskDescription:o1,taskLatestComment:i1,taskCancellationReason:c1,archiveBadge:l1,attachmentThumbnails:d1,attachmentImageRow:u1,attachmentDocumentList:m1,attachmentThumbnail:p1,contextDocThumb:f1,contextDocMain:h1,contextDocText:g1,contextDocIcon:y1,contextDocName:k1,contextDocType:v1,taskSpecialists:S1,taxonomiesList:w1},iy=({children:e,className:t,onTaskIdClick:n})=>{if(!e)return null;const s=i=>Fe.Children.toArray(i).some(m=>Fe.isValidElement(m)?String(m.props?.className||"").includes("task-list-item"):!1),o=/\b(task-\d{10,}-[a-z0-9]+)\b/gi,l=i=>{if(!n)return i;if(typeof i=="string"){const y=Array.from(i.matchAll(o));if(!y.length)return i;const k=[];let S=0;for(let h=0;h<y.length;h+=1){const g=y[h],v=g[1],A=g.index??-1;A<S||(A>S&&k.push(i.slice(S,A)),k.push(a.jsx("button",{type:"button",className:p.taskIdInlineLink,onClick:_=>{_.preventDefault(),_.stopPropagation(),n(v)},children:v},`${v}-${A}-${h}`)),S=A+v.length)}return S<i.length&&k.push(i.slice(S)),k}if(Array.isArray(i))return i.map(l);if(!Fe.isValidElement(i))return i;const d=typeof i.type=="string"?i.type:"";if(d==="code"||d==="pre"||d==="a")return i;const m=i.props?.children;return m===void 0?i:Fe.cloneElement(i,{},Fe.Children.map(m,l))};return a.jsx("div",{className:t,children:a.jsx(av,{remarkPlugins:[nv,rv],components:{p:({children:i})=>a.jsx("p",{children:l(i)}),ul:({children:i})=>a.jsx("ul",{style:s(i)?{paddingLeft:0}:void 0,children:i}),li:({children:i,className:d})=>{const m=String(d||"").includes("task-list-item");return a.jsx("li",{className:d,style:m?{listStyle:"none"}:void 0,children:l(i)})},input:({type:i,checked:d})=>i!=="checkbox"?a.jsx("input",{type:i,checked:d,readOnly:!0}):a.jsx("input",{type:"checkbox",checked:!!d,readOnly:!0,style:{cursor:"default",marginRight:8}}),code:({children:i,className:d,...m})=>{const y=String(i||"").replace(/\n$/,"");return/language-(\w+)/.test(d||"")||y.includes(`
|
|
3
|
+
`)?a.jsx("pre",{className:p.codeBlock,children:a.jsx("code",{className:d,...m,children:y})}):a.jsx("code",{className:p.inlineCode,...m,children:y})}},children:e})})};function cy({label:e,title:t,ariaLabel:n,copied:s=!1,disabled:o=!1,className:l="",onClick:i,children:d}){return a.jsxs("button",{type:"button",className:`${p.taskIdBadge} ${s?p.copiedId:""} ${l}`.trim(),onClick:i,disabled:o,title:t,"aria-label":n,children:[s?a.jsx(eo,{size:13}):a.jsx(Qp,{size:13}),a.jsx("span",{className:p.taskIdBadgeLabel,children:d??e})]})}function Gu({copied:e,disabled:t=!1,label:n,onClick:s,title:o="Copy task reference",ariaLabel:l,className:i=""}){return a.jsx(cy,{copied:e,disabled:t,label:"",onClick:s,title:o,ariaLabel:l,className:i,children:n})}const b1=(e,t=10)=>{const n=sm[e?.toLowerCase()]||{icon:"FileCode"},s=ks[n.icon]||Rk;return a.jsx(s,{size:t})},Du=(e,t)=>{if(!e)return null;const n=t.trim();if(!n)return e;const o=wm(n)?.match(/^(lt|t)-(\d+)$/),l=o?`${o[1]==="lt"?"l\\s*t":"t"}\\s*(?:-|\\s)?\\s*${o[2]}`:n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^${l}$`,"i"),d=e.split(new RegExp(`(${l})`,"gi"));return a.jsx(a.Fragment,{children:d.map((m,y)=>i.test(m)?a.jsx("mark",{className:p.highlight,children:m},y):m)})};function _d(e){return e.trim().replace(/\\/g,"/")}function ly(e){return e.split("?")[0].split("#")[0]}function _m(e){return typeof e=="string"?e:String(e.path||"").trim()}function dy(e){const n=ly(_d(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!n?.[1])return null;try{return decodeURIComponent(n[1]).trim()||null}catch{return n[1].trim()||null}}function uy(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const n=new URL(e,window.location.origin).searchParams.get("path");return n?_d(n):null}catch{return null}}function _1(e,t){const n=(t||(typeof e=="string"?"":e.fsPath||"")).trim();if(n)return _d(n);const s=_m(e),o=uy(s);return o?_d(o):null}function C1(e,t){const n=String(typeof e=="string"?"":e.assetId||"").trim();if(n)return n;const s=_m(e);return dy(s)}function A1(e,t){const n=_m(e);return dy(n)?!0:[(t||(typeof e=="string"?"":e.fsPath||"")).trim(),typeof e=="string"?"":String(e.originalFilename||"").trim(),typeof e=="string"?"":String(e.displayName||"").trim(),typeof e=="string"?"":String(e.caption||"").trim(),uy(n)||"",n].some(o=>{if(!o)return!1;const l=ly(_d(o)).toLowerCase();return l.endsWith(".md")||l.endsWith(".markdown")})}function x1(e,t){const n=_m(e),s=_1(e,t);if(!s||!A1(e,s))return!1;const o=C1(e),l=new CustomEvent("taskforce:open-markdown-document",{detail:{path:n,fsPath:s,...o?{assetId:o}:{},...typeof e!="string"&&e.taskId?{taskId:e.taskId}:{}},cancelable:!0});return!window.dispatchEvent(l)}const I1="I-";function my(e){return km(I1,e)}function T1(e){return e.trim().replace(/\\/g,"/")}function py(e){return typeof e=="string"?e:String(e.path||"").trim()}function R1(e){return/\.(png|jpe?g|webp)(\?|#|$)/i.test(e)}function j1(e){return typeof e=="string"?T1(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function N1(e,t){if(typeof e=="string")return!1;const n=String(e.assetId||"").trim(),s=py(e);return!!(n&&s&&R1(s))}function P1(e,t){if(!N1(e))return!1;const n=e,s=String(t?.taskId||n.taskId||"").trim(),o=String(t?.taskReferenceLabel||"").trim(),l=String(n.assetId||"").trim(),i=my(n),d=py(e),m=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...s?{taskId:s}:{},...o?{taskReferenceLabel:o}:{},assetId:l,...i?{imageReferenceLabel:i}:{},path:d,displayName:j1(e)},cancelable:!0});return!window.dispatchEvent(m)}function Ih(e,t){if(!e)return null;const n=String(e.taskId||"").trim(),s=String(e.assetId||"").trim(),o=String(e.path||"").trim(),l=String(e.displayName||"").trim()||"Image attachment";if(!s||!o)return null;const i=String(e.taskReferenceLabel||"").trim(),d=n?t.find(y=>y.id===n):void 0,m=n?i||Qi(d)||n:void 0;return{...n?{taskId:n}:{},...m?{taskReferenceLabel:m}:{},assetId:s,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,path:o,displayName:l}}function cm(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return"";const n=t.split("/").filter(Boolean);return n[n.length-1]||""}function Sf(e){const t=String(e||"").trim(),n=t.lastIndexOf(".");return n<=0?{stem:t,ext:""}:{stem:t.slice(0,n),ext:t.slice(n)}}function fy(e,t){const n=String(e||"").trim(),s=String(t||"").trim();return n?s&&n.startsWith(`${s}-`)?n.slice(s.length+1):n.replace(/^asset-[a-z0-9-]+-/i,""):""}function M1(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Th(e,t){const{stem:n,ext:s}=Sf(cm(e)),o=fy(n,t),l=M1(o||n);return l?`${l}${s}`:cm(e)||"Untitled document"}function Sp(e,t){const n=String(e||"").trim();if(!n)return!0;const s=cm(n),{stem:o}=Sf(s),l=String(t||"").trim();if(l&&o.toLowerCase()===l.toLowerCase())return!0;const i=fy(o,t);return i?i!==o:!0}function E1(e){const t=String(e.logicalName||"").trim();if(t&&!Sp(t,e.assetId))return t;const n=String(e.displayName||"").trim();if(n&&!Sp(n,e.assetId))return n;const s=String(e.title||"").trim();if(s&&!Sp(s,e.assetId))return s;const o=String(e.originalFilename||"").trim();if(o)return Th(o,e.assetId);const l=String(e.fsPath||"").trim();return l?Th(l,e.assetId):"Untitled document"}function D1(e){return E1(e)}function L1(e){const t=D1(e),n=String(e.originalFilename||e.fsPath||"").trim(),s=Sf(cm(n)).ext;return s?t.toLowerCase().endsWith(s.toLowerCase())?t:`${t}${s}`:t}const B1="_taxonomyDropdown_tt12a_1",W1="_taxonomyDropdownActive_tt12a_6",F1="_taxonomyDropdownButton_tt12a_11",O1="_taxonomyDropdownOpen_tt12a_50",$1="_taxonomyDropdownButtonContent_tt12a_56",U1="_taxonomyDropdownIcon_tt12a_64",z1="_taxonomyDropdownLabel_tt12a_72",H1="_taxonomyDropdownChevron_tt12a_81",G1="_taxonomyDropdownChevronOpen_tt12a_87",V1="_taxonomyDropdownPanel_tt12a_91",q1="_taxonomyDropdownPanelPortal_tt12a_110",K1="_taxonomyDropdownOption_tt12a_129",Z1="_taxonomyDropdownOptionHighlighted_tt12a_157",Y1="_taxonomyDropdownOptionSelected_tt12a_163",mr={taxonomyDropdown:B1,taxonomyDropdownActive:W1,taxonomyDropdownButton:F1,taxonomyDropdownOpen:O1,taxonomyDropdownButtonContent:$1,taxonomyDropdownIcon:U1,taxonomyDropdownLabel:z1,taxonomyDropdownChevron:H1,taxonomyDropdownChevronOpen:G1,taxonomyDropdownPanel:V1,taxonomyDropdownPanelPortal:q1,taxonomyDropdownOption:K1,taxonomyDropdownOptionHighlighted:Z1,taxonomyDropdownOptionSelected:Y1};function ld({value:e,options:t,onChange:n,placeholder:s="Select...",required:o=!1,disabled:l=!1,className:i="",ariaLabelledBy:d,ariaLabel:m,hideSelectedLabel:y=!1,hideChevron:k=!1,panelClassName:S="",portalPanel:h=!1,panelMinWidth:g}){const[v,A]=r.useState(!1),[_,I]=r.useState(-1),[B,V]=r.useState({}),L=r.useRef(null),J=r.useRef(null),me=r.useRef(null),ve=t.find(X=>String(X.value)===String(e));r.useEffect(()=>{if(!v)return;const X=M=>{const O=M.target,de=!!L.current?.contains(O),ge=!!me.current?.contains(O);!de&&!ge&&(A(!1),I(-1))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[v]),r.useEffect(()=>{if(!v)I(-1);else{const X=t.findIndex(M=>String(M.value)===String(e));I(X>=0?X:0)}},[v,t,e]),r.useEffect(()=>{if(!v||!h)return;const X=()=>{const M=J.current;if(!M)return;const O=M.getBoundingClientRect(),de=Math.max(g||0,O.width),ge=Math.max(8,O.right-de),$=O.bottom;V({position:"fixed",top:$,left:ge,minWidth:de,zIndex:2e3})};return X(),window.addEventListener("resize",X),window.addEventListener("scroll",X,!0),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0)}},[v,h,g]);const re=()=>{l||A(!v)},x=X=>{n(X.value),A(!1),J.current?.focus()},K=X=>{if(!l)switch(X.key){case"Enter":case" ":X.preventDefault(),v?_>=0&&x(t[_]):A(!0);break;case"Escape":X.preventDefault(),A(!1),J.current?.focus();break;case"ArrowDown":X.preventDefault(),v?I(M=>M<t.length-1?M+1:0):A(!0);break;case"ArrowUp":X.preventDefault(),v?I(M=>M>0?M-1:t.length-1):A(!0);break;case"Home":X.preventDefault(),v&&I(0);break;case"End":X.preventDefault(),v&&I(t.length-1);break;case"Tab":A(!1);break}},ue=(X,M)=>{const O=X.icon&&ks[X.icon]?ks[X.icon]:Yi,de=X.color?Nn(X.color):"var(--text-secondary)",ge=M?.hideLabel===!0;return a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${mr.taxonomyDropdownIcon}`,style:{color:de},children:a.jsx(O,{size:16})}),!ge&&a.jsx("span",{className:`taxonomyDropdownLabel ${mr.taxonomyDropdownLabel}`,children:X.label})]})},pe=v?a.jsx("div",{ref:me,id:`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,className:`taxonomyDropdownPanel ${mr.taxonomyDropdownPanel} ${h?mr.taxonomyDropdownPanelPortal:""} ${S}`,role:"listbox","aria-labelledby":d,"aria-label":m,style:h?B:void 0,children:t.map((X,M)=>{const O=String(X.value)===String(e),de=M===_;return a.jsx("div",{className:`taxonomyDropdownOption ${mr.taxonomyDropdownOption} ${O?`taxonomyDropdownOptionSelected ${mr.taxonomyDropdownOptionSelected}`:""} ${de?`taxonomyDropdownOptionHighlighted ${mr.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":O,onClick:()=>x(X),onMouseEnter:()=>I(M),style:(()=>{const ge=X.color,$=Nn(ge),_e=!$||$.startsWith("var("),je=_e?"#8b5cf6":$,se=_e?"20":"30",ce=_e?"05":"10";return{"--option-color":$||"var(--text-primary)","--option-border":`${je}${se}`,"--option-bg":`${je}${ce}`}})(),children:ue(X)},String(X.value))})}):null;return a.jsxs("div",{ref:L,className:`taxonomyDropdown ${mr.taxonomyDropdown} ${v?`taxonomyDropdownActive ${mr.taxonomyDropdownActive}`:""} ${i}`,children:[a.jsxs("button",{ref:J,type:"button",className:`taxonomyDropdownButton ${mr.taxonomyDropdownButton} ${v?`taxonomyDropdownOpen ${mr.taxonomyDropdownOpen}`:""}`,onClick:re,onKeyDown:K,disabled:l,role:"combobox","aria-haspopup":"listbox","aria-expanded":v,"aria-controls":`taxonomy-listbox-${s.replace(/\s+/g,"-")}`,"aria-labelledby":d,"aria-label":m,style:(()=>{if(!ve)return{};const X=ve.color,M=Nn(X),O=!M||M.startsWith("var("),de=O?"#8b5cf6":M,ge=O?"30":"50",$=O?"05":"10";return{"--field-color":M||"var(--text-primary)","--field-border":`${de}${ge}`,"--field-bg":`${de}${$}`}})(),children:[a.jsx("span",{className:`taxonomyDropdownButtonContent ${mr.taxonomyDropdownButtonContent}`,children:ve?ue(ve,{hideLabel:y}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${mr.taxonomyDropdownIcon}`,children:a.jsx(Yi,{size:16})}),a.jsx("span",{className:`taxonomyDropdownLabel ${mr.taxonomyDropdownLabel}`,children:s})]})}),!k&&a.jsx(tl,{size:16,className:`taxonomyDropdownChevron ${mr.taxonomyDropdownChevron} ${v?`taxonomyDropdownChevronOpen ${mr.taxonomyDropdownChevronOpen}`:""}`})]}),h?pe?Zi.createPortal(pe,document.body):null:pe]})}function hy({task:e,disabled:t=!1,actionDisabled:n,statusDisabled:s,compressed:o=!1,shortLabels:l=!1,showLabel:i=!0,onSetStatus:d,onArchiveTask:m,onUnarchiveTask:y,archiveActionMode:k="auto"}){const S=e?.status||"task",g=k==="auto"?!!e&&(S==="done"||S==="cancelled")?"archive":"none":k,v=n??t,A=s??t,_=Kc.map(I=>({...I,label:(o||l)&&I.shortLabel||I.label}));return a.jsxs("div",{className:`${p.statusActionsGroup} ${o?p.statusActionsGroupCompact:""}`,children:[g==="archive"&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!v&&m?.(e),disabled:v,title:"Archive Now","aria-label":"Archive task",children:a.jsx(jk,{size:o?12:16})}),g==="unarchive"&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.archiveTaskBtn}`,onClick:()=>e&&!v&&y?.(e),disabled:v,title:"Unarchive task","aria-label":"Unarchive task",children:a.jsx(kd,{size:o?12:16})}),a.jsx("div",{className:`${p.statusSelectWrap} ${p.statusTaxonomyDropdownWrap}`,children:a.jsx(ld,{value:S,options:_,disabled:A||!e,ariaLabel:"Status",hideSelectedLabel:!i,hideChevron:!i,className:`${p.statusTaxonomyDropdown} ${o?p.statusTaxonomyDropdownCompact:""} ${i?"":p.statusTaxonomyDropdownIconOnly}`,panelClassName:i?"":p.statusTaxonomyDropdownIconOnlyPanel,portalPanel:!i,panelMinWidth:i?void 0:144,onChange:I=>{e&&d?.(e,I)}})})]})}function J1(e,t,n){const s=typeof e=="string"?e.trim():"";if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;const o=Number(t),l=Number.isFinite(o)&&o>0?String(Math.floor(o)):typeof n=="string"&&n.trim().length>0?n.trim():"";if(!l)return s;const[i,d=""]=s.split("#"),m=i.includes("?")?"&":"?";return`${i}${m}v=${encodeURIComponent(l)}${d?`#${d}`:""}`}function Q1(e){return e==="taskId"?"Task":e==="title"?"Title":e==="description"?"Description":e==="assignee"?"Assigned to":e==="ownerId"?"Owner":e==="status"?"Status":e==="scheduledDate"?"Scheduled date":e==="dueDate"?"Due date":e==="workstreamId"?"Workstream":e==="initiativeId"?"Initiative":e}function X1(e){return e==="task"?"Task":e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Yn(e,t,n){const s=n?.(t,e);if(typeof s=="string")return s;if(e==null||e==="")return"none";if(Array.isArray(e)){const o=e.map(l=>Yn(l,t,n)).filter(Boolean);return o.length>0?o.join(", "):"none"}return typeof e=="object"?"updated":t==="status"?X1(String(e)):String(e)}function Rh(e){return Array.isArray(e)?e.map((t,n)=>{const s=t&&typeof t=="object"?t:{},o=Number(s.order);return{id:String(s.id||"").trim(),title:String(s.title||"").trim(),isCompleted:!!s.isCompleted,order:Number.isFinite(o)?o:n}}):[]}function eM(e){const t=Rh(e?.from),n=Rh(e?.to),s=new Map(t.map(i=>[i.id||i.title,i])),o=new Map(n.map(i=>[i.id||i.title,i]));for(const[i,d]of o.entries()){const m=s.get(i);if(!m)return d.title?`Checklist item added: ${d.title}`:"Checklist item added";if(m.isCompleted!==d.isCompleted)return d.title?d.isCompleted?`Checklist item completed: ${d.title}`:`Checklist item reopened: ${d.title}`:d.isCompleted?"Checklist item completed":"Checklist item reopened"}for(const[i,d]of s.entries())if(!o.has(i))return d.title?`Checklist item removed: ${d.title}`:"Checklist item removed";return t.length===n.length&&t.every(i=>o.has(i.id||i.title))&&t.some((d,m)=>{const y=n[m];return(d.id||d.title)!==(y?.id||y?.title)})?"Checklist reordered":"Checklist updated"}function wf(e){return e.split(/[?#]/,1)[0]||e}function jh(e){const t=wf(e).replace(/\\/g,"/"),n=t.split("/").filter(Boolean);return n[n.length-1]||t}function tM(e){return/\.(png|jpe?g|webp|gif)$/i.test(wf(e))}function aM(e){return e.includes("/api/taskforce/documents/")?!0:/\.(pdf|txt|md|markdown|csv|json|docx?|html?|js|jsx|ts|tsx|css|py|java|go|rs|sh)$/i.test(wf(e))}function Nh(e){return Array.isArray(e)?e.flatMap((t,n)=>{const s=t&&typeof t=="object"?t:null,o=typeof t=="string"?t:String(s?.path||"").trim(),l=String(s?.fsPath||"").trim(),i=String(s?.assetId||"").trim(),d=String(s?.referenceLabel||"").trim(),m=[s?.displayName,s?.originalFilename,s?.caption,d,l?jh(l):"",o?jh(o):""].map(h=>String(h||"").trim()).find(Boolean)||`Attachment ${n+1}`,y=i||l||o||`${m}:${n}`,k=[o,l,String(s?.originalFilename||"").trim(),String(s?.displayName||"").trim(),d].filter(Boolean),S=k.some(h=>tM(h))?"image":d.startsWith("D-")||k.some(h=>aM(h))?"document":"attachment";return[{key:y,label:m,kind:S}]}):[]}function nM(e,t){return t===1?e:e==="image"?"images":e==="document"?"documents":"attachments"}function Lu(e){if(e.length===0)return"attachments";const t=e.reduce((s,o)=>(s[o.kind]+=1,s),{image:0,document:0,attachment:0}),n=Object.entries(t).filter(([,s])=>s>0).map(([s,o])=>o===1?s:`${o} ${nM(s,o)}`);return n.length===1?n[0]:e.length<=3&&n.length<=2?n.join(" and "):`${e.length} attachments`}function Hi(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function rM(e){const t=Nh(e?.from),n=Nh(e?.to),s=new Map(t.map(m=>[m.key,m])),o=new Map(n.map(m=>[m.key,m])),l=n.filter(m=>!s.has(m.key)),i=t.filter(m=>!o.has(m.key));if(l.length===1&&i.length===0)return`${Hi(l[0].kind)} attached: ${l[0].label}`;if(i.length===1&&l.length===0)return`${Hi(i[0].kind)} removed: ${i[0].label}`;if(l.length>0&&i.length===0)return`${Hi(Lu(l))} attached`;if(i.length>0&&l.length===0)return`${Hi(Lu(i))} removed`;if(l.length===1&&i.length===1)return`${Hi(l[0].kind)} replaced: ${i[0].label} -> ${l[0].label}`;if(l.length>0||i.length>0)return`${Hi(Lu(l))} attached, ${Lu(i)} removed`;const d=n.filter(m=>{const y=s.get(m.key);return y&&y.label!==m.label});if(d.length===1&&t.length===1&&n.length===1){const m=s.get(d[0].key);return`${Hi(d[0].kind)} renamed: ${m?.label||"Attachment"} -> ${d[0].label}`}return"Attachment details updated"}function lm(e,t,n){if(e==="checklistItems")return eM(t);if(e==="attachments")return rM(t);const s=Q1(e);if(e==="title")return`${s}: updated`;if(e==="description"){const o=Yn(t?.from,e,n)!=="none",l=Yn(t?.to,e,n)!=="none";return!o&&l?`${s}: added`:o&&!l?`${s}: cleared`:`${s}: updated`}return`${s}: ${Yn(t?.from,e,n)} -> ${Yn(t?.to,e,n)}`}function gy(e,t){const n=e.details?.changes||{},s=Object.keys(n);if(e.action==="task-created")return"Task created";if(e.action==="task-comment-added")return"Comment added";if(e.action==="task-archived")return"Task marked done";if(e.action==="task-cancelled")return"Task cancelled";if(e.action==="task-unarchived")return"Task restored";if(e.action==="task-status-changed"&&n.status)return`Status changed: ${Yn(n.status.from,"status",t)} -> ${Yn(n.status.to,"status",t)}`;if(e.action==="task-schedule-changed")return n.scheduledDate?`Scheduled date changed: ${Yn(n.scheduledDate.from,"scheduledDate",t)} -> ${Yn(n.scheduledDate.to,"scheduledDate",t)}`:n.dueDate?`Due date changed: ${Yn(n.dueDate.from,"dueDate",t)} -> ${Yn(n.dueDate.to,"dueDate",t)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&n.workstreamId)return`Workstream changed: ${Yn(n.workstreamId.from,"workstreamId",t)} -> ${Yn(n.workstreamId.to,"workstreamId",t)}`;if(e.action==="task-relationship-changed"&&n.initiativeId)return`Initiative changed: ${Yn(n.initiativeId.from,"initiativeId",t)} -> ${Yn(n.initiativeId.to,"initiativeId",t)}`;if(e.action==="task-attachments-changed")return n.attachments?lm("attachments",n.attachments,t):"Attachments updated";if(s.length===1){const o=s[0],l=n[o];return lm(o,l,t)}return s.length>1?`${s.length} fields updated`:"Task updated"}function qO(e,t){if(e.taskId||e.entityType==="task")return gy(e,t);const n=e.details?.changes||{},s=Object.keys(n),o=e.entityType==="initiative"?"Initiative":"Workstream",l=typeof e.details?.taskTitle=="string"&&e.details.taskTitle.trim().length>0?e.details.taskTitle.trim():null;return e.action==="initiative-created"?"Initiative created":e.action==="initiative-archived"?"Initiative archived":e.action==="initiative-unarchived"?"Initiative restored":e.action==="workstream-created"?"Workstream created":e.action==="workstream-archived"?"Workstream archived":e.action==="workstream-unarchived"?"Workstream restored":e.action==="workstream-task-added"?l?`Task added: ${l}`:"Task added":e.action==="workstream-task-removed"?l?`Task removed: ${l}`:"Task removed":e.action==="workstream-relationship-changed"&&n.initiativeId?`Initiative changed: ${Yn(n.initiativeId.from,"initiativeId",t)} -> ${Yn(n.initiativeId.to,"initiativeId",t)}`:(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&n.attachments?lm("attachments",n.attachments,t):s.length===1?lm(s[0],n[s[0]],t):s.length>1?`${s.length} fields updated`:e.action==="initiative-updated"||e.action==="workstream-updated"?`${o} updated`:`${o} activity updated`}function dm(e){const t=Date.parse(String(e.timestamp||""));return Number.isFinite(t)?t:null}function sM(e){const t=e.details?.changes||{},n=Object.keys(t);if(e.action==="task-status-changed"&&t.status)return"status";if(e.action==="task-schedule-changed"){if(t.scheduledDate)return"scheduledDate";if(t.dueDate)return"dueDate"}if(e.action==="task-relationship-changed"){if(t.workstreamId)return"workstreamId";if(t.initiativeId)return"initiativeId"}return e.action==="task-attachments-changed"&&t.attachments?"attachments":n.length===1?n[0]:null}function KO(e){if(e.taskId||e.entityType==="task")return sM(e);const t=e.details?.changes||{},n=Object.keys(t);return(e.action==="workstream-task-added"||e.action==="workstream-task-removed")&&e.details?.taskId?"taskId":e.action==="workstream-relationship-changed"&&t.initiativeId?"initiativeId":(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&t.attachments?"attachments":n.length===1?n[0]:null}function yy(e){const t=new Map,n=new Set,s=o=>{if(o.type==="event"&&o.event.action==="task-comment-added")return;const l=o.type==="comment"?`comment:${String(o.comment.id||o.id).replace(/^comment:/,"")}`:`event:${String(o.event.id||o.id).replace(/^event:/,"")}`;t.set(l,{...o,id:l}),o.type==="comment"&&n.add(String(o.comment.id||o.id).replace(/^comment:/,""))};return Array.isArray(e.activity)&&e.activity.forEach(s),Array.isArray(e.comments)&&e.comments.forEach(o=>{const l=String(o.id||"").trim();!l||n.has(l)||s({id:`comment:${l}`,type:"comment",timestamp:o.timestamp,comment:o})}),[...t.values()].sort((o,l)=>{const i=dm(o),d=dm(l);return i!==null&&d!==null&&i!==d?i-d:i!==null&&d===null?-1:i===null&&d!==null?1:String(o.id||"").localeCompare(String(l.id||""))})}function bf(e){return yy(e)}function oM(e){const t=bf(e);return t.length===0?null:[...t].sort((n,s)=>{const o=dm(n),l=dm(s);return o!==null&&l!==null&&o!==l?l-o:o!==null&&l===null?-1:o===null&&l!==null?1:String(s.id||"").localeCompare(String(n.id||""))})[0]||null}function iM(e,t){return e?e.type==="comment"?e.comment.text:gy(e.event,t):""}const{MessageSquare:cM,User:lM,Bot:dM,Gauge:uM,ClipboardList:mM,HelpCircle:pM,File:fM}=ks,hM=({task:e,searchQuery:t="",copiedId:n=null,taxonomies:s=[],types:o=[],priorities:l=[],categories:i=[],assigneeOptions:d=[],taskWorkstream:m=null,taskInitiative:y=null,isOverlay:k=!1,isArchived:S=!1,readOnlyMode:h=null,isRecentlyChanged:g=!1,onClick:v,onCopyId:A,onToggleInProgress:_,onToggleReview:I,onToggleComplete:B,onToggleCancel:V,onSetStatus:L,onArchiveTask:J,onUnarchive:me,onDelete:ve,deleteActionTitle:re,onOpenTaskById:x,compressed:K=!1,showStatusLabel:ue=!0})=>{const pe=jg(e),X=pe.label||(pe.isProvisional?"Pending":""),M=pe.isProvisional,O=!!pe.label,de=rm(m)||m?.id||"",ge=ny(y)||y?.id||"",$=l.find(ne=>String(ne.value)===String(e.priority)),_e=$?$.label.toLowerCase().replace(/\s+/g,"-"):String(e.priority),je=i.find(ne=>ne.value===e.category||ne.label===e.category),se=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),ce=Number.isFinite(se)?Math.max(1,Math.min(5,Math.round(se))):3,Re={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Pe={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},Ce=Re[ce],Ee=`var(--complexity-${Pe[ce]})`,U=Dv(e.priority,_e),T=!!p[`priorityItem_${U}`],b=tm(e.assignee),j=pd(e.assignee,d),D=Fe.useMemo(()=>{const ne=String(e.assignee||"").trim();return d.find(st=>String(st.value||"").trim()===ne)||null},[d,e.assignee]),te=b!=="unassigned"&&typeof D?.avatarUrl=="string"?J1(D.avatarUrl,D.avatarRevision,D.avatarUpdatedAt):"",P=b==="agent"?"var(--color-violet-500, #8b5cf6)":b==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)",H=Fe.useMemo(()=>oM(e),[e]),be=h||(e.isDeleted?"deleted":S?"archived":null),z=be!==null,ie=Fe.useCallback((ne,st)=>{const Ye=String(st||"").trim();if(Ye){if(ne==="assignee")return pd(Ye,d);if(ne==="workstreamId"&&Ye===m?.id)return de||m.id;if(ne==="initiativeId"&&Ye===y?.id)return ge||y.id}},[d,ge,y,m,de]),ee=Fe.useMemo(()=>iM(H,ie),[ie,H]),Q=Fe.useMemo(()=>bf(e).length,[e]),q=[Yt.taskItem,e.status==="on-hold"?Yt.onHold:"",e.status==="in-progress"?Yt.inProgress:"",e.status==="review"?Yt.readyForReview:"",e.status==="done"?Yt.completed:"",e.status==="cancelled"?Yt.cancelled:"",g?Yt.taskItemRecentlyChanged:"",p[`priorityItem_${U}`]||"",k?Yt.kanbanCardOverlay:"",S?Yt.archived:"",K?Yt.compressed:""].filter(Boolean).join(" "),Se=Nn($?.color),we=o.find(ne=>ne.value===e.type),Te=Nn(we?.color)||ub(e.type),Me=ne=>{const st=typeof ne=="string"?ne:ne.path,Ye=typeof ne=="string"?"":(ne.fsPath||"").trim(),Pt=typeof ne=="string"?"":(ne.displayName||"").trim(),kt=typeof ne=="string"?"":(ne.originalFilename||"").trim(),It=typeof ne=="string"?"":(ne.caption||"").trim();return[Ye,kt,Pt,It,st].some(Mt=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(Mt))},nt=ne=>{const st=typeof ne=="string"?ne:ne.path,Ye=st.includes("/api/taskforce/documents/"),Pt=typeof ne=="string"?"":(ne.displayName||"").trim();if(Ye&&typeof ne!="string")return L1({displayName:ne.displayName,originalFilename:ne.originalFilename,fsPath:ne.fsPath,assetId:ne.assetId||null});const kt=typeof ne=="string"?"":(ne.caption||"").trim();if(kt)return kt;if(Pt)return Pt;const It=typeof ne=="string"?"":(ne.originalFilename||"").trim();return It||st.split("?")[0].split("#")[0].split("/").pop()||"Context file"},gt=ne=>{const st=typeof ne=="string"?ne:ne.path,Ye=typeof ne=="string"?"":(ne.fsPath||"").trim(),Pt=typeof ne=="string"?"":(ne.caption||"").trim(),kt=typeof ne=="string"?"":(ne.originalFilename||"").trim(),It=[];if(Ye&&It.push(Ye),kt&&It.push(kt),Pt&&It.push(Pt),st.includes("/api/taskforce/context-link?path="))try{const Mt=new URL(st,"http://localhost").searchParams.get("path");Mt&&It.push(Mt)}catch{}It.push(st);for(const Ft of It){const Be=Ft.split("?")[0].split("#")[0].split("/").pop()||"",et=Be.lastIndexOf(".");if(et<=0||et===Be.length-1)continue;const Ue=Be.slice(et+1);if(Ue)return Ue.slice(0,5).toUpperCase()}return"FILE"},lt={"--task-change-glow-color":Se||`var(--priority-${U})`,...Se?{borderLeftColor:Se,[`--priority-${U}`]:Se}:{},...!T&&Se?{borderLeft:`4px solid ${Se}`}:{}},St=ne=>ne.replace(/\b\w/g,st=>st.toUpperCase()),Ke=xd(s,[e]),Ct=e.checklistItems||[],dt=Ct.length,Xe=dt>0?Ct.filter(ne=>ne.isCompleted).length:0,ct=(ne,st)=>{ne.stopPropagation(),A?.(ne,st)};return a.jsxs("div",{className:q,onClick:()=>v?.(e),style:lt,"data-task-card":"true",children:[a.jsxs("div",{className:Yt.taskHeader,children:[a.jsxs("div",{className:Yt.taskReferenceCluster,children:[y?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:Yt.taskReferenceText,children:ge}),a.jsx("span",{className:Yt.taskReferenceDivider,children:"/"})]}):null,m?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:Yt.taskReferenceText,children:de}),a.jsx("span",{className:Yt.taskReferenceDivider,children:"/"})]}):null,X?a.jsx(Gu,{copied:O&&n===pe.label,onClick:ne=>ct(ne,pe.label),disabled:!O,title:O?"Copy task reference":"Task reference pending sync",className:S?Yt.archiveBadge:"",label:Du(X,t)}):null,M?a.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),a.jsx("div",{className:Yt.taskActions,onClick:ne=>ne.stopPropagation(),children:z?me||ve?a.jsxs(a.Fragment,{children:[me&&a.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>me(e.id),title:be==="deleted"?"Restore deleted task":"Restore archived task",children:a.jsx(kd,{size:16})}),ve&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>ve(e.id),title:re||(be==="deleted"?"Delete Permanently":"Move to Trash"),children:a.jsx(gm,{size:16})})]}):null:a.jsx(hy,{task:e,compressed:K,shortLabels:!0,showLabel:ue,onSetStatus:(ne,st)=>{if(L){L(ne,st);return}if(st==="in-progress"){_?.(ne);return}if(st==="review"){I?.(ne);return}if(st==="done"){B?.(ne);return}st==="cancelled"&&V?.(ne)},onArchiveTask:J})})]}),a.jsxs("div",{className:Yt.taskContent,children:[z&&a.jsx("div",{className:`${Yt.taskMeta} ${Yt.taskMetaCompact}`}),a.jsxs("div",{children:[a.jsxs("div",{className:Yt.taskTitle,style:K?{fontSize:"13px",lineHeight:"1.4"}:{},children:[be==="archived"&&"✓ ",be==="deleted"&&"Deleted: ",Du(e.title,t)]}),e.description&&!z&&!K&&a.jsx("div",{className:Yt.taskDescription,children:a.jsx(iy,{onTaskIdClick:x,children:e.description})})]}),e.attachments&&e.attachments.length>0&&!z&&!K&&a.jsxs("div",{className:Yt.attachmentThumbnails,children:[a.jsx("div",{className:Yt.attachmentImageRow,children:(e.attachments||[]).map((ne,st)=>{const Ye=typeof ne=="string"?ne:ne.path;return Me(ne)?a.jsx("div",{className:Yt.attachmentThumbnail,onClick:Pt=>{Pt.stopPropagation(),!P1(typeof ne=="string"?{path:Ye}:ne,{taskId:e.id,taskReferenceLabel:X})&&window.open(Ye,"_blank")},children:a.jsx("img",{src:Ye,alt:`Attachment ${st}`})},st):null})}),a.jsx("div",{className:Yt.attachmentDocumentList,children:(e.attachments||[]).map((ne,st)=>{const Ye=typeof ne=="string"?ne:ne.path,Pt=typeof ne=="string"?void 0:ne.fsPath,kt=nt(ne);if(Me(ne))return null;const It=gt(ne);return a.jsxs("button",{type:"button",className:Yt.contextDocThumb,onClick:Ft=>{Ft.stopPropagation();const Mt=typeof ne=="string"?{path:ne,taskId:e.id}:{...ne,taskId:e.id};x1(Mt,Pt)||window.open(Ye,"_blank")},title:kt,style:{"--context-doc-accent":mb(It)},children:[a.jsxs("span",{className:Yt.contextDocMain,children:[a.jsx("span",{className:Yt.contextDocIcon,"aria-hidden":"true",children:a.jsx(fM,{size:13})}),a.jsx("span",{className:Yt.contextDocText,children:a.jsx("span",{className:Yt.contextDocName,children:kt})})]}),a.jsx("span",{className:Yt.contextDocType,children:It})]},st)})})]}),e.status==="cancelled"&&e.canceledReason&&!K&&a.jsxs("div",{className:Yt.taskCancellationReason,children:[a.jsx("strong",{children:"Cancellation Reason:"})," ",Du(e.canceledReason,t)]}),ee&&!z&&!K&&a.jsxs("div",{className:Yt.taskLatestComment,children:[a.jsx("strong",{children:"Latest Activity:"})," ",Du(ee.length>120?ee.substring(0,120)+"...":ee,t)]}),!z&&Ke.length>0&&!K&&a.jsx("div",{className:`${Yt.taskSpecialists} ${Yt.taxonomiesList}`,children:Ke.map(ne=>{const st=e.taxonomies?.[ne.id];return st?(Array.isArray(st)?st:[st]).map(Pt=>{const kt=ne.options.find(et=>et.value===Pt);if(!kt)return null;const It=ks[kt.icon||"Layers"]||Np,Ft=Nn(kt.color)||"var(--text-primary)",Mt=ne.status==="retired"?`${ne.label} (Retired)`:ne.label,Be=kt.status==="retired"?`${kt.label} (Retired)`:kt.label;return a.jsx("span",{className:p.specialistBadge,style:{borderColor:`${Ft}50`,backgroundColor:`${Ft}15`,color:Ft},title:`${Mt}: ${St(Be)}`,children:a.jsx(It,{size:10})},`${ne.id}-${Pt}`)}):null})}),a.jsx("div",{className:Yt.taskMeta,children:z?a.jsx("span",{children:e.category}):a.jsx(a.Fragment,{children:a.jsxs("div",{className:Yt.taskMetaRow,style:K?{marginBottom:0}:void 0,children:[a.jsxs("div",{className:Yt.taskMetaBadgeGroup,children:[(()=>{const ne=Nn(je?.color),st=je?.icon||"Folder",Ye=ks[st]||Ro;return a.jsx("span",{className:p.metaBadge,title:St(e.category),style:{color:ne||"var(--text-secondary)",backgroundColor:ne?`${ne}15`:"var(--bg-tertiary)",borderColor:ne?`${ne}40`:"transparent"},children:a.jsx(Ye,{size:14})})})(),a.jsx("span",{className:`${p.metaBadge} ${p[`type_${e.type}`]||""}`,title:St(e.type||Dr),style:{color:`var(--type-color, ${Te})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${Te}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${Te}), transparent 75%)`},children:we?.icon?(()=>{const ne=ks[we.icon]||pM;return a.jsx(ne,{size:14})})():b1(e.type,14)}),$&&a.jsx("span",{className:p.metaBadge,style:{color:Se||"var(--text-secondary)",backgroundColor:Se?`${Se}15`:"var(--bg-tertiary)",borderColor:Se?`${Se}40`:"var(--border-color)"},title:`${$.label}`,children:(()=>{const ne=$.icon||"AlertCircle",st=ks[ne]||Nk;return a.jsx(st,{size:14})})()}),Q>0&&a.jsxs("span",{className:p.metaBadge,title:`${Q} activity items`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[a.jsx(cM,{size:14}),a.jsx("span",{children:Q})]}),dt>0&&a.jsxs("span",{className:p.metaBadge,title:`${Xe}/${dt} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[a.jsx(mM,{size:14}),a.jsx("span",{children:`${Xe}/${dt}`})]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsxs("span",{className:p.metaBadge,title:`AI-estimated complexity: ${Ce} (${ce}/5)`,style:{color:Ee,backgroundColor:`color-mix(in srgb, ${Ee}, transparent 88%)`,borderColor:`color-mix(in srgb, ${Ee}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[a.jsx(uM,{size:14}),!K&&a.jsx("span",{children:Ce})]}),a.jsx("span",{className:`${Yt.assigneeAvatarIndicator} ${b==="unassigned"?Yt.assigneeAvatarEmpty:""}`,title:`Assigned to: ${j}`,"aria-label":b==="unassigned"?"Unassigned":`Assigned to ${j}`,style:{"--assignee-avatar-color":P},children:te?a.jsx("img",{src:te,alt:"",className:Yt.assigneeAvatarImage}):b==="agent"?a.jsx(dM,{size:K?18:20}):b==="member"?a.jsx(lM,{size:K?18:20}):null})]})]})})})]})]})},Cd=Fe.memo(hM),um="168px";function ky(){return a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:$e("standalone.filtersCaps")})}function qi({label:e,options:t,selected:n,onChange:s,variant:o="label"}){return a.jsx(Vi,{label:e,options:t,selected:n,onChange:s,variant:o,containerStyle:{flex:`0 0 ${um}`,maxWidth:um}})}function vy({onClick:e}){return a.jsxs("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-secondary)",cursor:"pointer",fontSize:"12px",display:"flex",alignItems:"center",gap:"4px"},children:[a.jsx(ac,{size:12})," ",$e("standalone.clearFilters")]})}function Ph({label:e,options:t,selected:n,onChange:s,allLabel:o,title:l}){const[i,d]=Fe.useState(!1),m=Fe.useRef(null),y=t.find(h=>h.value===n),k=y?.selectedLabel||y?.label||o;Fe.useEffect(()=>{const h=g=>{m.current&&!m.current.contains(g.target)&&d(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const S=h=>{s(h),d(!1)};return a.jsxs("div",{className:p.filterContainer,ref:m,style:{flex:`0 0 ${um}`,maxWidth:um},children:[a.jsxs("button",{type:"button",className:`${p.filterButton} ${n?p.filterActive:""}`,onClick:()=>d(h=>!h),title:l||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":i,children:[a.jsx("span",{children:k}),a.jsx(tl,{size:14,style:{transform:i?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),i&&a.jsxs("div",{className:`${p.filterDropdown} ${p.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[a.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>S(""),"aria-selected":!n,children:[a.jsx(eo,{size:14,style:{opacity:n?0:1}}),a.jsx("span",{style:{fontWeight:n?500:600},children:o})]}),a.jsx("div",{className:p.filterDivider}),t.map(h=>{const g=h.value===n;return a.jsxs("button",{type:"button",className:p.filterOption,onClick:()=>S(h.value),"aria-selected":g,children:[a.jsx(eo,{size:14,style:{opacity:g?1:0}}),a.jsx("span",{style:{fontWeight:g?600:500},children:h.label})]},h.value)})]})]})}function Sy({scope:e,onScopeChange:t,className:n,labelClassName:s}){return a.jsxs("div",{className:n,children:[a.jsx("span",{className:s,children:"Scope"}),a.jsx("div",{className:p.taskScopeTabs,role:"tablist","aria-label":"Task scope",children:[{value:"open",label:"Open"},{value:"archived",label:"Archived"},{value:"deleted",label:"Deleted"}].map(o=>{const l=e===o.value;return a.jsx("button",{type:"button",className:`${p.taskScopeTab} ${l?p.taskScopeTabActive:""}`,onClick:()=>t(o.value),role:"tab","aria-selected":l,"aria-pressed":l,title:`Show ${o.label.toLowerCase()} tasks`,children:o.label},o.value)})})]})}function wy({onClick:e,disabled:t=!1,className:n,title:s="Permanently delete all deleted tasks",children:o="Delete All Permanently"}){return a.jsxs("button",{type:"button",className:n,onClick:e,disabled:t,title:s,children:[a.jsx(gm,{size:14}),o]})}const{Search:Mh,ClipboardList:gM,ChevronRight:yM,ChevronDown:kM,Folder:vM,Archive:SM,RotateCcw:wM,X:bM,Plus:_M,ArrowUpDown:CM,Trash2:AM}=ks,by=r.forwardRef((e,t)=>{const{tasks:n,archivedTasks:s,categories:o,types:l,priorities:i,taxonomyDisplayLabels:d,assigneeOptions:m=[],workstreams:y=[],initiatives:k=[],searchQuery:S,filterCategories:h,filterTypes:g,filterPriorities:v,filterStatus:A,filterAssignees:_=[],filterTaxonomies:I,sortBy:B,sortOrder:V,showArchive:L,taskScope:J,collapsedCategories:me,loadingTasks:ve,filteredTasks:re,filteredArchive:x,groupedTasks:K,filteredDeletedTasks:ue=[],groupedDeletedTasks:pe={},copiedId:X,recentlyChangedTaskIds:M=[],showTaskCardStatusLabel:O=!0,onSearchChange:de,onFilterCategoriesChange:ge,onFilterTypesChange:$,onFilterPrioritiesChange:_e,onFilterStatusChange:je,onFilterAssigneesChange:se,onTaxonomyFilterChange:ce,onSortByChange:Re,onSortOrderChange:Pe,onShowArchiveChange:Ce,onTaskScopeChange:Ee,onClearFilters:U,onToggleCategory:T,onEditTask:b,onOpenTaskById:j,onCopyId:D,onToggleInProgress:te,onToggleReview:P,onToggleComplete:H,onToggleCancel:be,onSetStatus:z,onArchiveTask:ie,onBulkArchive:ee,onUnarchive:Q,onDelete:q,onDeleteAllDeleted:Se,onFetchArchive:we,onAddTaskToCategory:Te,supplementalTasks:Me=[],taxonomies:nt}=e,gt=new Set(M),lt=Fe.useMemo(()=>new Map(y.map(ae=>[ae.id,ae])),[y]),St=Fe.useMemo(()=>new Map(k.map(ae=>[ae.id,ae])),[k]),Ke=Fe.useCallback(ae=>{const ze=ae.workstreamId&<.get(ae.workstreamId)||null,bt=ze?.initiativeId&&St.get(ze.initiativeId)||null;return{taskWorkstream:ze,taskInitiative:bt}},[St,lt]),Ct=[...n,...s,...Me],dt=!!Ee,Xe=Ee,ct=J??(L?"archived":"open"),ne=dt?ct==="archived"?x:ct==="deleted"?ue:re:re,st=dt?ct==="archived"?{Archived:x}:ct==="deleted"?pe:K:K,Ye=dt?ct==="deleted"?"deleted":ct==="archived"?"archived":null:null,Pt=wm(S),kt=S?Pt?`No task found for ${Pt.toUpperCase()}`:$e("taskList.noMatchingTasks"):ct==="archived"?"No archived tasks found.":ct==="deleted"?"No deleted tasks found.":$e("taskList.noActiveTasks"),It=o.filter(ae=>!ae.disabled),Ft=o.filter(ae=>ae.disabled&&Ct.some(ze=>ze.category===ae.value)),Mt=[...It,...Ft.filter(ae=>!It.some(ze=>ze.value===ae.value))].map(ae=>({value:ae.value,label:ae.disabled?`${ae.label} (Legacy)`:ae.label})),Be=l.filter(ae=>ae.status!=="retired"),et=l.filter(ae=>ae.status==="retired"&&Ct.some(ze=>ze.type===ae.value)),Ue=[...Be,...et.filter(ae=>!Be.some(ze=>ze.value===ae.value))].map(ae=>({value:ae.value,label:ae.status==="retired"?`${ae.label} (Retired)`:ae.label})),yt=xd(nt,Ct).filter(ae=>ae.filterEnabled!==!1).map(ae=>({...ae,options:vf(ae,Ct)})),ot=Fe.useMemo(()=>[{value:"created",label:$e("taskList.sortCreated")},{value:"updated",label:$e("taskList.sortUpdated")},{value:"priority",label:$e("taskList.sortPriority")},...oy(nt,Ct)],[Ct,$e,nt]);return a.jsxs("div",{className:p.viewTab,ref:t,children:[a.jsxs("div",{className:p.filterBar,children:[a.jsxs("div",{className:p.searchContainer,children:[a.jsx(Mh,{size:16,className:p.searchIcon}),a.jsx("input",{type:"text",className:p.searchInput,placeholder:$e("taskList.searchPlaceholder"),value:S,onChange:ae=>de(ae.target.value)}),S&&a.jsx("button",{className:p.clearSearchBtn,onClick:()=>de(""),title:$e("taskList.clearSearchTitle"),children:a.jsx(bM,{size:14})})]}),a.jsxs("div",{className:p.filterRow,children:[a.jsx(Vi,{label:d?.category||$e("taskList.categoryLabel"),options:Mt,selected:h,onChange:ge,variant:"value"}),a.jsx(Vi,{label:d?.type||$e("taskList.typeLabel"),options:Ue,selected:g,onChange:$,variant:"value"})]}),a.jsxs("div",{className:p.filterRow,children:[a.jsx(Vi,{label:d?.priority||$e("taskList.priorityLabel"),options:i,selected:v,onChange:_e,variant:"value"}),a.jsx(Vi,{label:$e("taskList.statusLabel"),options:Xs,selected:A,onChange:je,variant:"value"}),a.jsx(Vi,{label:$e("taskList.assigneeLabel"),options:m,selected:_,onChange:ae=>se?.(ae),variant:"value"})]}),yt.map(ae=>a.jsx(Vi,{label:ae.status==="retired"?`${ae.label} (Retired)`:ae.label,options:ae.options.map(ze=>({...ze,label:ze.status==="retired"?`${ze.label} (Retired)`:ze.label})),selected:I[ae.id]||[],onChange:ze=>ce(ae.id,ze),variant:"value"},ae.id)),a.jsxs("div",{className:p.filterRow,children:[a.jsxs("div",{className:p.sortLabel,children:[a.jsx(CM,{size:14,style:{marginRight:"4px"}})," ",$e("taskList.sortByLabel")]}),a.jsx("select",{value:B,onChange:ae=>Re(ae.target.value),className:`${p.filterSelect} ${p.filterSelectSort} `,children:ot.map(ae=>a.jsx("option",{value:ae.value,children:ae.label},ae.value))}),a.jsx("button",{className:`${p.resetFiltersBtn} ${p.sortDirectionBtnWidget}`,onClick:Pe,title:$e(V==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:V==="desc"?a.jsx(ig,{size:14}):a.jsx(cg,{size:14})}),a.jsx("button",{className:p.resetFiltersBtn,onClick:U,title:$e("taskList.resetFiltersTitle"),children:a.jsx(wM,{size:14})})]}),a.jsxs("div",{className:`${p.filterRow} ${p.archiveRow} `,children:[ct==="open"?a.jsxs("button",{className:`${p.bulkArchiveBtn} ${n.some(ae=>ae.status==="done"||ae.status==="cancelled")?"":p.disabledBtn} `,onClick:()=>n.some(ae=>ae.status==="done"||ae.status==="cancelled")&&ee(),disabled:!n.some(ae=>ae.status==="done"||ae.status==="cancelled"),title:n.some(ae=>ae.status==="done"||ae.status==="cancelled")?$e("taskList.archiveAllTitle"):$e("taskList.noTasksToArchiveTitle"),children:[a.jsx(SM,{size:12}),a.jsx("span",{children:$e("taskList.archiveFinished")})]}):ct==="deleted"&&Se?a.jsx(wy,{className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn} ${ue.length===0?p.disabledBtn:""}`,onClick:()=>ue.length>0&&Se(),disabled:ue.length===0,title:ue.length>0?"Empty trash":"Trash is already empty",children:"Empty Trash"}):a.jsx("div",{}),dt?a.jsx(Sy,{scope:ct,onScopeChange:ae=>{Xe?.(ae),ae==="archived"?(Ce(!0),we()):L&&Ce(!1)},className:`${p.archiveToggle} ${p.taskScopeToggle}`}):a.jsxs("label",{className:p.archiveToggle,children:[a.jsx("input",{type:"checkbox","aria-label":"Archived",checked:L,onChange:ae=>{Ce(ae.target.checked),ae.target.checked&&we()}}),a.jsx("span",{children:"Include Archive"})]})]})]}),ve&&n.length===0?a.jsx("div",{className:p.loading,children:a.jsx(pr,{size:24,className:p.spinner})}):ne.length===0&&!ve?a.jsxs("div",{className:p.emptyState,children:[S?a.jsx(Mh,{size:48}):ct==="deleted"?a.jsx(AM,{size:48}):a.jsx(gM,{size:48}),a.jsx("p",{children:kt})]}):a.jsx("div",{className:p.taskList,style:{opacity:ve?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(st).map(([ae,ze])=>{if(ze.length===0)return null;const bt=me[ae];return a.jsxs("div",{className:p.categoryGroup,children:[a.jsx("div",{className:p.categoryHeader,onClick:()=>T(ae),children:a.jsxs("div",{className:p.categoryTitle,children:[bt?a.jsx(yM,{size:16}):a.jsx(kM,{size:16}),(()=>{const Ot=o.find(Lt=>Lt.label===ae),Bt=Ot?.icon&&ec[Ot.icon]?ec[Ot.icon]:vM,Oe=Nn(Ot?.color)||"var(--color-purple, #8b5cf6)";return a.jsx(Bt,{size:16,className:p.categoryTitleIcon,style:{color:Oe}})})(),ae,a.jsxs("span",{className:p.categoryCount,children:["(",ze.length,")"]}),Te&&a.jsx("button",{className:p.kanbanQuickAdd,onClick:Ot=>{Ot.stopPropagation(),Te(ae)},title:$e("taskList.addTaskToCategoryTitle",{category:ae}),style:{marginLeft:"auto"},disabled:Ye!==null,children:a.jsx(_M,{size:14})})]})}),!bt&&a.jsx("div",{className:p.categoryItems,children:ze.map(Ot=>(()=>{const{taskWorkstream:Bt,taskInitiative:Oe}=Ke(Ot);return a.jsx(Cd,{task:Ot,taskWorkstream:Bt,taskInitiative:Oe,searchQuery:S,copiedId:X,taxonomies:nt,types:l,priorities:i,assigneeOptions:m,onClick:b,onOpenTaskById:j,onCopyId:D,onToggleInProgress:te,onToggleReview:P,onToggleComplete:H,onToggleCancel:be,onSetStatus:z,onArchiveTask:ie,onUnarchive:Ye?Q:void 0,onDelete:Ye?q:void 0,categories:o,isRecentlyChanged:gt.has(Ot.id),readOnlyMode:Ye,showStatusLabel:O},Ot.id)})())})]},ae)})}),!dt&&L&&x.length>0&&a.jsxs("div",{className:p.archiveList,children:[a.jsx("div",{className:p.archiveHeader,children:"Archived"}),x.map(ae=>(()=>{const{taskWorkstream:ze,taskInitiative:bt}=Ke(ae);return a.jsx(Cd,{task:ae,taskWorkstream:ze,taskInitiative:bt,searchQuery:S,copiedId:X,isArchived:!0,types:l,assigneeOptions:m,onClick:b,onCopyId:D,onSetStatus:z,onUnarchive:Q,onDelete:q,deleteActionTitle:"Delete Permanently",categories:o,showStatusLabel:O},ae.id)})())]})]})});by.displayName="TaskList";const xM="_formNotice_inuex_1",IM="_assigneeIndicator_inuex_12",TM="_assigneeIndicatorAgent_inuex_20",RM="_assigneeIndicatorUser_inuex_24",jM="_assigneeIndicatorUnassigned_inuex_28",NM="_markdownPreview_inuex_32",PM="_error_inuex_83",MM="_keyboardHint_inuex_92",EM="_taskFormLifecycle_inuex_110",DM="_taskFormMetaDivider_inuex_115",LM="_taskFormMetaGrid_inuex_122",BM="_compactMetaSection_inuex_128",WM="_createWorkstreamRow_inuex_134",FM="_createWorkstreamDropdown_inuex_140",OM="_compactMetaGrid_inuex_145",$M="_compactMetaField_inuex_151",UM="_compactMetaFieldHint_inuex_165",zM="_formFieldsetReset_inuex_169",HM="_formLayout_inuex_176",GM="_formLayoutWithSidebar_inuex_183",VM="_formMainColumn_inuex_191",qM="_activitySidebar_inuex_198",KM="_activitySidebarHeader_inuex_208",ZM="_activitySidebarTitle_inuex_215",YM="_activitySidebarCount_inuex_224",JM="_taskFormDateRow_inuex_246",QM="_taskFormDateLabel_inuex_253",XM="_taskFormDateValue_inuex_261",eE="_taskFormMetaStack_inuex_269",tE="_taskFormMetaActor_inuex_275",aE="_taskFormDateWarning_inuex_287",nE="_taskFormDateError_inuex_293",rE="_helpHeader_inuex_299",sE="_helpClose_inuex_310",oE="_markdownHelp_inuex_324",iE="_helpGrid_inuex_333",cE="_helpGridItem_inuex_339",lE="_settingsHint_inuex_351",dE="_sectionBlock_inuex_357",uE="_softSectionSurface_inuex_367",mE="_stackedList_inuex_374",pE="_stackedListSpaced_inuex_379",fE="_checklistRow_inuex_383",hE="_checklistRowDragging_inuex_392",gE="_checklistHandleBtn_inuex_396",yE="_checklistCheckboxBtn_inuex_419",kE="_checklistCheckboxBtnChecked_inuex_439",vE="_checklistItemText_inuex_444",SE="_checklistItemTextCompleted_inuex_450",wE="_checklistRemoveBtn_inuex_455",bE="_specialistChip_inuex_522",_E="_specialistChipActive_inuex_545",CE="_commentPanel_inuex_626",AE="_activitySidebarPanel_inuex_635",xE="_commentThread_inuex_643",IE="_emptyComments_inuex_663",TE="_activityLoadingThread_inuex_673",RE="_activitySkeletonItem_inuex_677",jE="_activitySkeletonMeta_inuex_683",NE="_activitySkeletonBody_inuex_684",PE="_comment_inuex_626",ME="_commentAi_inuex_740",EE="_commentUser_inuex_744",DE="_commentHeader_inuex_748",LE="_commentAuthor_inuex_772",BE="_commentTime_inuex_780",WE="_commentText_inuex_784",FE="_commentInputArea_inuex_844",OE="_commentInput_inuex_844",$E="_sendCommentBtn_inuex_876",UE="_taxonomyFieldsGrid_inuex_903",zE="_markdownPreviewContainer_inuex_910",HE="_descriptionSurface_inuex_915",at={formNotice:xM,assigneeIndicator:IM,assigneeIndicatorAgent:TM,assigneeIndicatorUser:RM,assigneeIndicatorUnassigned:jM,markdownPreview:NM,error:PM,keyboardHint:MM,taskFormLifecycle:EM,taskFormMetaDivider:DM,taskFormMetaGrid:LM,compactMetaSection:BM,createWorkstreamRow:WM,createWorkstreamDropdown:FM,compactMetaGrid:OM,compactMetaField:$M,compactMetaFieldHint:UM,formFieldsetReset:zM,formLayout:HM,formLayoutWithSidebar:GM,formMainColumn:VM,activitySidebar:qM,activitySidebarHeader:KM,activitySidebarTitle:ZM,activitySidebarCount:YM,taskFormDateRow:JM,taskFormDateLabel:QM,taskFormDateValue:XM,taskFormMetaStack:eE,taskFormMetaActor:tE,taskFormDateWarning:aE,taskFormDateError:nE,helpHeader:rE,helpClose:sE,markdownHelp:oE,helpGrid:iE,helpGridItem:cE,settingsHint:lE,sectionBlock:dE,softSectionSurface:uE,stackedList:mE,stackedListSpaced:pE,checklistRow:fE,checklistRowDragging:hE,checklistHandleBtn:gE,checklistCheckboxBtn:yE,checklistCheckboxBtnChecked:kE,checklistItemText:vE,checklistItemTextCompleted:SE,checklistRemoveBtn:wE,specialistChip:bE,specialistChipActive:_E,commentPanel:CE,activitySidebarPanel:AE,commentThread:xE,emptyComments:IE,activityLoadingThread:TE,activitySkeletonItem:RE,activitySkeletonMeta:jE,activitySkeletonBody:NE,comment:PE,commentAi:ME,commentUser:EE,commentHeader:DE,commentAuthor:LE,commentTime:BE,commentText:WE,commentInputArea:FE,commentInput:OE,sendCommentBtn:$E,taxonomyFieldsGrid:UE,markdownPreviewContainer:zE,descriptionSurface:HE};function wp({label:e,value:t,options:n,onChange:s,type:o="priority",hideLabel:l=!1,showSelectedLabel:i=!0}){const d=n.find(m=>String(m.value)===String(t));return a.jsxs("div",{className:p.field,children:[!l&&a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:e}),i&&d&&a.jsx("span",{className:p.levelLabel,style:{color:Nn(d.color)||(o==="priority"?`var(--priority-${t})`:o==="complexity"?`var(--complexity-${t})`:"var(--text-secondary)"),backgroundColor:(Nn(d.color)?`${Nn(d.color)}25`:void 0)||(o==="priority"?`color-mix(in srgb, var(--priority-${t}), transparent 85%)`:o==="complexity"?`color-mix(in srgb, var(--complexity-${t}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:d.label})]}),a.jsx("div",{className:p.levelSelect,children:n.map((m,y)=>{const k=n.findIndex(g=>String(g.value)===String(t)),S=y<=k,h=String(m.value)===String(t);return a.jsx("button",{type:"button",className:`${p.levelOption} ${S?p.levelOptionFilled:""} ${S?p[`levelOption_${o}_${m.value}`]:""} ${h?p.levelOptionSelected:""}`,onClick:()=>s(m.value),title:m.label,style:{opacity:S?1:.15,backgroundColor:S?Nn(m.color)||(o==="priority"?`var(--priority-${m.value})`:o==="complexity"?`var(--complexity-${m.value})`:"var(--text-primary)"):void 0,color:S?o==="priority"&&String(m.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:S&&(o==="priority"&&(String(m.value).toLowerCase()==="critical"||m.value===4)||o==="complexity"&&(String(m.value).toLowerCase()==="epic"||m.value===5))?`0 0 12px ${o==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(m.value))})})]})}const Eh=new Map;function GE(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t}function VE(e,t){const n=Object.entries(t).sort(([s],[o])=>s.localeCompare(o));return JSON.stringify([e,n])}function mm(e,t,n){const s=GE(e);if(!s)return"";const o=n??Eg(),l=VE(o,t);let i=Eh.get(l);return i||(i=new Intl.DateTimeFormat(o,t),Eh.set(l,i)),i.format(s)}const qE=Fe.lazy(()=>vs(()=>import("./EntityActivityTimeline-sHk8Nzbq.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),KE=Fe.lazy(()=>vs(()=>import("./TaskContextUpload-C8G7pWkX.js"),__vite__mapDeps([7,1,8,9,2,3,4,5])).then(e=>({default:e.TaskContextUpload})));function ZE({count:e}){const t=Math.max(2,Math.min(e||3,4));return a.jsx("div",{className:`${at.commentThread} ${at.activityLoadingThread}`.trim(),"aria-busy":"true","aria-live":"polite","aria-label":"Loading activity",children:Array.from({length:t},(n,s)=>a.jsxs("div",{className:at.activitySkeletonItem,children:[a.jsx("div",{className:at.activitySkeletonMeta}),a.jsx("div",{className:at.activitySkeletonBody})]},s))})}function YE({id:e,item:t,onToggle:n,onRemove:s}){const{attributes:o,listeners:l,setNodeRef:i,transform:d,transition:m,isDragging:y}=Sg({id:e}),k={transform:tf.Transform.toString(d),transition:m,opacity:y?.88:1};return a.jsxs("div",{ref:i,style:k,className:`${at.checklistRow} ${y?at.checklistRowDragging:""}`.trim(),children:[a.jsx("button",{type:"button",className:at.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...o,...l,children:a.jsx(Mk,{size:14})}),a.jsx("button",{type:"button",className:`${at.checklistCheckboxBtn} ${t.isCompleted?at.checklistCheckboxBtnChecked:""}`.trim(),onClick:n,title:t.isCompleted?"Mark incomplete":"Mark complete","aria-label":t.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:t.isCompleted?a.jsx(eo,{size:14,strokeWidth:2.1}):null}),a.jsx("span",{className:`${at.checklistItemText} ${t.isCompleted?at.checklistItemTextCompleted:""}`.trim(),children:t.title}),a.jsx("button",{type:"button",className:at.checklistRemoveBtn,onClick:s,title:"Remove checklist item","aria-label":"Remove checklist item",children:a.jsx(ac,{size:15,strokeWidth:1.9})})]})}function _y(e){const{editingTaskId:t,error:n,title:s,description:o,category:l,type:i,priority:d,complexity:m,manualComplexityEnabled:y=!1,assignee:k,scheduledDate:S,dueDate:h,workstreamInput:g="",checklistItems:v,comments:A,newCommentText:_,contextFiles:I,currentWorkspaceId:B,apiBaseUrl:V,descriptionFocused:L,showMarkdownHelp:J,showChecklist:me=!1,checklistEnabled:ve=!0,formTaxonomies:re,onTaxonomyChange:x,onOpenSettings:K,categories:ue,types:pe,priorities:X,taxonomyDisplayLabels:M,assigneeOptions:O,taxonomies:de,workstreams:ge=[],initiatives:$=[],copiedId:_e,onTitleChange:je,onDescriptionChange:se,onCategoryChange:ce,onTypeChange:Re,onPriorityChange:Pe,onComplexityChange:Ce,onAssigneeChange:Ee,onScheduledDateChange:U,onDueDateChange:T,onWorkstreamInputChange:b=()=>{},onChecklistItemsChange:j,onNewCommentTextChange:D,onDescriptionFocusedChange:te,onShowMarkdownHelpChange:P,onShowChecklistChange:H=()=>{},onSubmit:be,onAddComment:z,onAddContextFile:ie,onRemoveContextFile:ee,onUpdateContextCaption:Q,onCopyId:q,onToggleInProgress:Se,onToggleReview:we,onToggleComplete:Te,onToggleCancel:Me,onSetStatus:nt,onArchiveTask:gt,onUnarchive:lt,onOpenTaskById:St,currentTask:Ke,commentsEndRef:Ct}=e,dt=Qi(Ke),Xe=Fe.useMemo(()=>nb(de,re),[de,re]),ct=Fe.useMemo(()=>{const he=ue.find(Gt=>Gt.value===Yc),it={value:Yc,label:he?.label||ym,icon:he?.icon||"HelpCircle",color:he?.color||"var(--text-secondary)"},xe=ue.find(Gt=>Gt.value===l),tt=ue.filter(Gt=>!Gt.disabled||Gt.value===xe?.value).filter(Gt=>Gt.value!==Yc).map(Gt=>({value:Gt.value,label:Gt.disabled?`${Gt.label} (Legacy)`:Gt.label,icon:Gt.icon,color:Gt.color}));return[it,...tt]},[ue,l]),ne=Fe.useMemo(()=>{const he=pe.find(xe=>xe.value===i);return pe.filter(xe=>xe.status!=="retired"||xe.value===he?.value).map(xe=>({value:xe.value,label:xe.status==="retired"?`${xe.label} (Retired)`:xe.label,icon:xe.icon||"Box",color:xe.color||"violet-500"}))},[pe,i]),st=he=>he&&mm(he,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,Ye=st(Ke?.createdAt),Pt=st(Ke?.updatedAt||Ke?.createdAt),kt=st(Ke?.completedAt),It=Fe.useMemo(()=>{const he=new Date,it=he.getFullYear(),xe=String(he.getMonth()+1).padStart(2,"0"),jt=String(he.getDate()).padStart(2,"0");return`${it}-${xe}-${jt}`},[]),Ft=!!(h&&S&&h<S),Mt=!!(h&&h<It&&(!Ke||Ke.status!=="done"&&Ke.status!=="cancelled")),Be=v.filter(he=>he.isCompleted).length,[et,Ue]=Fe.useState(""),[Qe,yt]=Fe.useState(!1),ot=!!Ke?.isArchived,ae=!!Ke?.isDeleted,ze=Fe.useMemo(()=>ge.map(he=>{const it=rm(he);return{value:it||he.id,label:it?`${it} · ${he.title}`:he.title,icon:"Folder",color:"var(--text-secondary)"}}),[ge]),bt=Fe.useMemo(()=>ze.some(he=>String(he.value)===String(g||"").trim()),[g,ze]);Fe.useEffect(()=>{if(t){Qe&&yt(!1);return}if(g.trim()){if(bt&&Qe){yt(!1);return}!bt&&!Qe&&yt(!0)}},[t,bt,Qe,g]);const Ot=ot||ae,Bt=Fe.useRef(null),Oe=hg(Mp(vg,{activationConstraint:{distance:6}}));Fe.useLayoutEffect(()=>{const he=Bt.current;if(!he)return;const it=()=>{he.scrollTop=0;const jt=he.parentElement;jt&&(typeof jt.scrollTo=="function"?jt.scrollTo({top:0,left:0,behavior:"auto"}):jt.scrollTop=0)};it();const xe=window.requestAnimationFrame(it);return()=>window.cancelAnimationFrame(xe)},[t,Ke?.id]);const Lt=()=>{const he=et.trim();if(!he)return;const it=new Date().toISOString();j([...v,{id:`checklist-draft-${it}-${v.length}`,taskId:t||"",title:he,isCompleted:!1,order:v.length,createdAt:it,updatedAt:it}]),Ue("")},vt=Fe.useCallback(he=>{const{active:it,over:xe}=he;if(!xe||it.id===xe.id)return;const jt=v.findIndex(Na=>Na.id===it.id),tt=v.findIndex(Na=>Na.id===xe.id);if(jt<0||tt<0)return;const Gt=new Date().toISOString(),ga=sv(v,jt,tt).map((Na,ua)=>({...Na,order:ua,updatedAt:Gt}));j(ga)},[v,j]),E=he=>{const it=String(he||"").trim(),xe=he.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!xe||xe==="ai"||it.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${xe.split(" ").map(tt=>tt.charAt(0).toUpperCase()+tt.slice(1)).join(" ")}`},c=lS(O,k),Y=tm(k),ye=pd(k,c),Ie=Fe.useMemo(()=>new Map(c.map(he=>[String(he.value),he])),[c]),He=Ie.get(String(k||"unassigned")),Ve=Ke?.assigneeActor?.color||He?.color,Ne=Fe.useMemo(()=>{const he=[Ke?.assigneeActor,Ke?.createdByActor].filter(Boolean);return new Map(he.map(it=>[String(it.id),it]))},[Ke?.assigneeActor,Ke?.createdByActor]),Vt=Fe.useMemo(()=>new Map(ge.map(he=>[he.id,rm(he)||he.id])),[ge]),qt=Fe.useMemo(()=>new Map($.map(he=>[he.id,ny(he)||he.id])),[$]),Et=Fe.useMemo(()=>bf({activity:Ke?.activity,comments:A}),[A,Ke?.activity]),Tt=(he,it)=>{const xe=String(it||"").trim();if(xe){if(he==="assignee")return pd(xe,c);if(he==="workstreamId")return Vt.get(xe);if(he==="initiativeId")return qt.get(xe)}},Wt=Fe.useCallback((he,it,xe)=>{if(xe&&xe.trim())return xe.trim();const jt=String(he||"").trim();if(!jt)return it==="ai"?"AI Agent":$e("taskForm.you");const tt=Ne.get(jt);if(tt?.label)return tt.label;const Gt=Ie.get(jt)||Ie.get(jt.toLowerCase());return Gt?.label?Gt.label:it==="ai"?E(jt):pd(jt,c)||jt},[Ne,Ie,E,c]),Ht=Fe.useCallback(({actorId:he,actorType:it,actorProfile:xe,fallbackKind:jt})=>{const tt=String(he||"").trim(),Gt=tt.toLowerCase(),ga=Ne.get(tt),Na=Ie.get(tt)||Ie.get(Gt),ua=xe||ga||Na||null,ca=it==="system"?"system":it==="ai"||ua?.kind==="ai"?"agent":it==="human"||ua?.kind==="human"?"member":Na?.kind==="agent"?"agent":Na?.kind==="member"?"member":jt||(Gt===""||Gt==="user"||Gt==="human"?"member":"agent"),Dt=ca==="system"?"System":Wt(tt,ca==="agent"?"ai":"human",ua?.label||null),aa=ua?.color,Za=String(ua?.icon||(ca==="agent"?"Bot":ca==="member"?"User":"ClipboardList")),$t=ec[Za]||(ca==="agent"?Zu:ca==="member"?ni:lg);return{kind:ca,label:Dt,color:aa,ActorIcon:$t}},[Ne,Ie,Wt]),sa=Fe.useMemo(()=>{const he=Et[Et.length-1];if(!he)return null;if(he.type==="comment"){const xe=he.comment;return Wt(xe.author,xe.actor?.kind==="ai"?"ai":xe.actor?.kind==="human"?"human":null,xe.actor?.label||null)}const it=he.event;return Wt(it.actor,it.actorType,it.actorProfile?.label||null)},[Wt,Et]),Kt=Fe.useMemo(()=>{if(!Ke?.completedAt)return null;for(const it of Et){if(it.type!=="event")continue;const xe=it.event,jt=xe.details?.changes?.status?.to;if(jt==="done"||jt==="cancelled")return Wt(xe.actor,xe.actorType,xe.actorProfile?.label||null)}return sa},[Ke?.completedAt,sa,Wt,Et]),Ka=Ke?.createdByActor?.label||Wt(Ke?.createdBy||null,Ke?.createdByActor?.kind==="ai"?"ai":Ke?.createdByActor?.kind==="human"?"human":null,Ke?.createdByActor?.label||null),Fa=sa,Xa=Et.length;Fe.useLayoutEffect(()=>{if(!t)return;const he=Ct.current;if(!he)return;const it=he.parentElement,xe=()=>{if(typeof he.scrollIntoView=="function"){he.scrollIntoView({block:"end"});return}it&&(it.scrollTop=it.scrollHeight)};xe();const jt=window.requestAnimationFrame(xe);return()=>window.cancelAnimationFrame(jt)},[Xa,Ct,Ke?.id,t]);const wa=t?a.jsxs("aside",{className:at.activitySidebar,"aria-label":$e("taskForm.commentsSectionTitle"),children:[a.jsxs("div",{className:at.activitySidebarHeader,children:[a.jsx("h2",{className:at.activitySidebarTitle,children:$e("taskForm.commentsSectionTitle")}),a.jsx("span",{className:at.activitySidebarCount,children:Xa})]}),a.jsxs("div",{className:`${at.commentPanel} ${at.activitySidebarPanel}`.trim(),children:[a.jsx(Fe.Suspense,{fallback:a.jsx(ZE,{count:Xa}),children:a.jsx(qE,{activity:Ke?.activity,comments:A,formatFieldValue:Tt,resolveActorPresentation:Ht,onOpenTaskById:St,emptyMessage:$e("taskForm.noComments"),listClassName:at.commentThread,emptyClassName:at.emptyComments,endRef:Ct})}),a.jsxs("div",{className:at.commentInputArea,children:[a.jsx("textarea",{className:at.commentInput,placeholder:$e("taskForm.commentPlaceholder"),value:_,onChange:he=>D(he.target.value),onKeyDown:he=>{he.key==="Enter"&&!he.shiftKey&&(he.preventDefault(),z())},rows:4}),a.jsx("button",{type:"button",className:at.sendCommentBtn,onClick:z,disabled:!_.trim(),"aria-label":"Send comment",title:"Send comment",children:a.jsx(Pk,{size:16})})]})]})]}):null;return a.jsxs("form",{ref:Bt,onSubmit:be,className:`${p.form} ${p.appScrollbar} tf-scrollbar`,children:[n&&a.jsx("div",{className:at.error,children:n}),Ot&&a.jsx("div",{className:`${at.formNotice} tf-text-helper`,children:ae?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),a.jsxs("fieldset",{disabled:Ot,className:`${at.formFieldsetReset} ${t?at.formLayoutWithSidebar:at.formLayout}`.trim(),children:[a.jsxs("div",{className:at.formMainColumn,children:[a.jsxs("div",{className:p.field,children:[a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:"Title"}),k&&a.jsx("span",{title:`Assigned to: ${ye}`,className:[at.assigneeIndicator,Y==="agent"?at.assigneeIndicatorAgent:Y==="member"?at.assigneeIndicatorUser:at.assigneeIndicatorUnassigned].join(" "),style:Ve?{color:Ve}:void 0,children:Y==="agent"?a.jsx(Zu,{size:20}):Y==="member"?a.jsx(ni,{size:20}):a.jsx(Yi,{size:20})})]}),a.jsx("input",{type:"text",value:s,onChange:he=>je(he.target.value),placeholder:"What needs to be done?",className:p.input,required:!0,maxLength:255,autoFocus:!0})]}),a.jsxs("div",{className:p.field,children:[a.jsxs("div",{className:p.labelRow,children:[a.jsx("label",{className:p.label,children:"Description"}),a.jsx("button",{type:"button",className:p.helpLink,onClick:()=>P(!J),title:"Markdown Help",tabIndex:-1,children:a.jsx(Yi,{size:14})})]}),J&&a.jsxs("div",{className:at.markdownHelp,children:[a.jsxs("div",{className:at.helpHeader,children:[a.jsx("span",{children:"Markdown Guide"}),a.jsx("button",{onClick:()=>P(!1),className:at.helpClose,children:a.jsx(ac,{size:12})})]}),a.jsxs("div",{className:at.helpGrid,children:[a.jsx("div",{children:a.jsx("code",{children:"**bold**"})}),a.jsx("div",{children:a.jsx("code",{children:"_italic_"})}),a.jsx("div",{children:a.jsx("code",{children:"- list"})}),a.jsx("div",{children:a.jsx("code",{children:"1. list"})}),a.jsx("div",{className:at.helpGridItem,children:a.jsx("code",{children:"`inline code`"})}),a.jsxs("div",{className:at.helpGridItem,children:[a.jsx("code",{children:"```"}),a.jsx("br",{}),a.jsx("code",{children:"code block"}),a.jsx("br",{}),a.jsx("code",{children:"```"})]}),a.jsx("div",{children:a.jsx("code",{children:"[link](url)"})})]})]}),L||!o?a.jsx("textarea",{className:`${p.textarea} ${at.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",value:o,onChange:he=>se(he.target.value),onFocus:()=>te(!0),onBlur:()=>te(!1),rows:9,autoFocus:L}):a.jsx("div",{className:`${p.textarea} ${at.descriptionSurface} ${at.markdownPreview} ${at.markdownPreviewContainer}`,onClick:()=>te(!0),children:a.jsx(iy,{onTaskIdClick:St,children:o})})]}),a.jsxs("div",{className:at.compactMetaSection,children:[a.jsxs("div",{className:at.compactMetaGrid,children:[a.jsxs("div",{className:`${p.field} ${at.compactMetaField}`,children:[a.jsx("label",{id:"category-label",className:p.label,children:M?.category||"Category"}),a.jsx(ld,{value:l,options:ct,onChange:he=>ce(String(he)),required:!0,ariaLabelledBy:"category-label"})]}),a.jsxs("div",{className:`${p.field} ${at.compactMetaField}`,children:[a.jsx("label",{id:"type-label",className:p.label,children:M?.type||"Type"}),a.jsx(ld,{value:i,options:ne,onChange:he=>Re(String(he)),ariaLabelledBy:"type-label"})]}),a.jsxs("div",{className:`${p.field} ${at.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-scheduled-date",className:p.label,children:$e("taskForm.scheduledLabel")}),a.jsx("input",{id:"task-form-scheduled-date",type:"date",value:S,onChange:he=>U(he.target.value),className:`${p.input} ${p.taskFormDateInput}`})]}),a.jsxs("div",{className:`${p.field} ${at.compactMetaField}`,children:[a.jsx("label",{id:"assignee-label",className:p.label,children:"Assigned To"}),a.jsx(ld,{value:k||"unassigned",options:c,onChange:he=>Ee(String(he)),ariaLabelledBy:"assignee-label"})]}),a.jsx("div",{className:at.compactMetaField,children:a.jsx(wp,{label:M?.priority||"Priority",options:X,value:d,onChange:Pe,type:"priority",showSelectedLabel:!1})}),a.jsxs("div",{className:`${p.field} ${at.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-due-date",className:p.label,children:$e("taskForm.dueLabel")}),a.jsx("input",{id:"task-form-due-date",type:"date",value:h,onChange:he=>T(he.target.value),className:`${p.input} ${p.taskFormDateInput}`}),Ft&&a.jsx("span",{className:`${at.taskFormDateWarning} ${at.compactMetaFieldHint}`,children:$e("taskForm.dueBeforeScheduled")}),Mt&&a.jsx("span",{className:`${at.taskFormDateError} ${at.compactMetaFieldHint}`,children:$e("taskForm.overdue")})]}),y&&a.jsx("div",{className:at.compactMetaField,children:a.jsx(wp,{label:"Complexity",options:[{value:1,label:"Tiny",color:"#10b981",icon:"Gauge"},{value:2,label:"Low",color:"#14b8a6",icon:"Gauge"},{value:3,label:"Medium",color:"#3b82f6",icon:"Gauge"},{value:4,label:"High",color:"#8b5cf6",icon:"Gauge"},{value:5,label:"Epic",color:"#d946ef",icon:"Gauge"}],value:m,onChange:Ce,type:"general"})})]}),!t&&a.jsxs("div",{className:at.createWorkstreamRow,children:[a.jsx("label",{className:p.label,children:"Attach to workstream"}),a.jsxs("div",{className:p.pathInputGroup,children:[Qe?a.jsx("input",{type:"text",className:p.input,value:g,onChange:he=>b(he.target.value),placeholder:"Type a workstream name or reference","aria-label":"Attach to workstream"}):a.jsx(ld,{value:g,options:ze,onChange:he=>b(String(he)),placeholder:"Select workstream...",ariaLabel:"Attach to workstream",className:at.createWorkstreamDropdown}),a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:()=>{if(Qe){yt(!1),bt||b("");return}yt(!0)},"aria-label":Qe?"Use workstream dropdown":"Enter workstream by name",title:Qe?"Use workstream dropdown":"Enter workstream by name",children:a.jsx(to,{size:14})})]})]})]}),a.jsxs("div",{className:at.sectionBlock,children:[a.jsx("div",{className:at.taxonomyFieldsGrid,children:Xe.map(he=>{if(he.id==="approach"&&he.isSystem)return null;const it=re[he.id],xe=Array.isArray(it)?it.map(tt=>String(tt)):it!=null&&it!==""?[String(it)]:[],jt=he.options.filter(tt=>tt.status!=="retired"||xe.includes(String(tt.value)));return a.jsxs("div",{className:p.field,children:[a.jsx("label",{className:p.label,children:he.label}),he.description&&a.jsx("div",{className:`${at.settingsHint} tf-text-helper`,children:he.description}),he.widgetType==="level"?a.jsx(wp,{label:he.label,options:jt.map(tt=>({...tt,label:tt.status==="retired"?`${tt.label} (Retired)`:tt.label})),value:re[he.id]||"",onChange:tt=>x(he.id,tt),type:"general",hideLabel:!0}):he.multiSelect?a.jsx("div",{className:`${p.dropdownList} ${at.softSectionSurface}`,children:jt.map(tt=>{const Gt=String(tt.value),ga=xe.includes(Gt);return a.jsxs("button",{type:"button",className:`${at.specialistChip} ${ga?at.specialistChipActive:""}`,onClick:()=>{const Na=ga?xe.filter(ua=>ua!==Gt):[...xe,Gt];x(he.id,Na)},title:ga?"Click to remove":"Click to add",children:[ga&&a.jsx(eo,{size:12}),tt.status==="retired"?`${tt.label} (Retired)`:tt.label]},Gt)})}):a.jsxs("div",{className:p.fieldIconWrapper,style:{"--field-color":"var(--text-primary)","--field-border":"rgba(255, 255, 255, 0.1)","--field-bg":"rgba(255, 255, 255, 0.02)"},children:[(()=>{const tt=he.options.find(Na=>String(Na.value)===String(re[he.id])),Gt=tt?.icon&&ks[tt.icon]?ks[tt.icon]:Yi,ga=tt?.color||"var(--text-secondary)";return a.jsx("div",{className:p.fieldIcon,style:{color:Nn(ga)},children:a.jsx(Gt,{size:16})})})(),a.jsxs("select",{value:re[he.id]||"",onChange:tt=>x(he.id,tt.target.value),className:`${p.select} ${p.field_dynamic}`,required:he.isRequired,children:[a.jsxs("option",{value:"",children:["Select ",he.label,"..."]}),jt.map(tt=>a.jsx("option",{value:tt.value,children:tt.status==="retired"?`${tt.label} (Retired)`:tt.label},tt.value))]})]})]},he.id)})}),ve&&a.jsxs("div",{className:p.specialistSection,children:[a.jsxs("div",{className:p.toggleHeading,onClick:()=>H(!me),title:me?"Hide checklist":"Show checklist",children:[a.jsxs("label",{className:p.label,children:["Checklist"," ",v.length>0&&`(${Be}/${v.length})`]}),me?a.jsx(tl,{size:14}):a.jsx(Jc,{size:14})]}),me&&a.jsxs("div",{className:`${p.dropdownList} ${at.stackedList} ${at.stackedListSpaced}`,children:[a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("input",{type:"text",className:p.input,placeholder:"Add checklist item",value:et,onChange:he=>Ue(he.target.value),onKeyDown:he=>{he.key==="Enter"&&(he.preventDefault(),Lt())}}),a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:Lt,disabled:!et.trim(),children:"Add"})]}),v.length>0?a.jsx(gg,{sensors:Oe,collisionDetection:ov,onDragEnd:vt,children:a.jsx(yg,{items:v.map(he=>he.id),strategy:kg,children:v.map((he,it)=>a.jsx(YE,{id:he.id||`checklist-${it}`,item:he,onToggle:()=>{const xe=new Date().toISOString();j(v.map((jt,tt)=>tt===it?{...jt,isCompleted:!jt.isCompleted,updatedAt:xe}:jt))},onRemove:()=>j(v.filter((xe,jt)=>jt!==it).map((xe,jt)=>({...xe,order:jt})))},he.id||`checklist-${it}`))})}):a.jsx("div",{className:`${at.settingsHint} tf-text-helper`,children:"No checklist items yet."})]})]})]}),a.jsxs("div",{children:[a.jsx(Fe.Suspense,{fallback:null,children:a.jsx(KE,{taskId:t,taskReferenceLabel:dt,workspaceId:B,apiBaseUrl:V,contextFiles:I,onAddContextFile:ie,onRemoveContextFile:ee,onUpdateContextCaption:Q})}),a.jsx("div",{className:`${at.taskFormLifecycle} ${at.taskFormMetaDivider}`,children:a.jsx("div",{className:at.taskFormMetaGrid,children:Ke&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:at.taskFormDateRow,children:[a.jsx("span",{className:at.taskFormDateLabel,children:$e("taskForm.createdLabel")}),a.jsxs("span",{className:at.taskFormMetaStack,children:[a.jsx("span",{className:at.taskFormDateValue,children:Ye||$e("taskForm.emptyValue")}),a.jsx("span",{className:at.taskFormMetaActor,children:Ka?`by ${Ka}`:$e("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:at.taskFormDateRow,children:[a.jsx("span",{className:at.taskFormDateLabel,children:$e("taskForm.updatedLabel")}),a.jsxs("span",{className:at.taskFormMetaStack,children:[a.jsx("span",{className:at.taskFormDateValue,children:Pt||$e("taskForm.emptyValue")}),a.jsx("span",{className:at.taskFormMetaActor,children:Fa?`by ${Fa}`:$e("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:at.taskFormDateRow,children:[a.jsx("span",{className:at.taskFormDateLabel,children:$e("taskForm.completedLabel")}),a.jsxs("span",{className:at.taskFormMetaStack,children:[a.jsx("span",{className:at.taskFormDateValue,children:kt||$e("taskForm.emptyValue")}),a.jsx("span",{className:at.taskFormMetaActor,children:Kt?`by ${Kt}`:$e("taskForm.emptyValue")})]})]})]})})})]})]}),wa,a.jsxs("div",{className:at.keyboardHint,children:["Press ",a.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌥":"Alt"})," to toggle"]})]})]})}function Ki({ariaLabel:e,children:t,disabled:n=!1,onClick:s,title:o}){return a.jsx("button",{type:"button",className:`${p.taskIdBadge} ${p.taskHierarchyActionBtn}`,onClick:s,disabled:n,title:o,"aria-label":e,children:t})}function Cy({editingTaskId:e,loading:t,autoSaveState:n="idle",title:s,handleSubmit:o,resetForm:l,handleCopyId:i,copiedId:d,tasks:m,currentTask:y,currentTaskWorkstream:k,currentTaskInitiative:S,workstreamInput:h="",onWorkstreamInputChange:g,onSetWorkstreamForCurrentTask:v,handleToggleInProgress:A,handleToggleReview:_,handleToggleComplete:I,handleToggleCancel:B,handleSetStatus:V,handleArchiveTask:L,handleUnarchiveTask:J,handleRestoreDeletedTask:me,handlePermanentlyDeleteDeletedTask:ve}){const[re,x]=Fe.useState(!1),K=y??(e&&m.find(se=>se.id===e)||null),ue=!!K?.isArchived,pe=!!K?.isDeleted,X=jg(K),M=X.label||(X.isProvisional?"Pending":""),O=X.isProvisional,de=!!X.label,ge=k?rm(k)||k.id:"",$=S?Jr(S)||S.id:"";Fe.useEffect(()=>{k&&x(!1)},[k?.id]);const _e=Fe.useCallback(()=>{h.trim()&&v?.()},[v,h]),je=Fe.useCallback(()=>{x(!1),g?.(""),v?.(null)},[v,g]);return a.jsx("div",{className:p.stickyActionHeader,children:e?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:p.taskHierarchyHeader,children:[a.jsxs("div",{className:p.taskHierarchyBadgeRow,children:[k?a.jsx(a.Fragment,{children:a.jsx(Ki,{onClick:je,disabled:t||ue||pe,title:"Remove from workstream",ariaLabel:"Remove from workstream",children:a.jsx(Uu,{size:13})})}):null,S?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Gu,{copied:d===$,onClick:se=>i(se,$),disabled:t,title:"Copy initiative reference",label:$})]}):null,k?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Gu,{copied:d===ge,onClick:se=>i(se,ge),disabled:t,title:"Copy workstream reference",label:ge})]}):a.jsx(a.Fragment,{children:a.jsx(Ki,{onClick:()=>{g?.(""),x(se=>!se)},disabled:t||ue||pe,title:"Attach to workstream",ariaLabel:"Attach to workstream",children:a.jsx(Yu,{size:13})})}),M?a.jsxs("span",{className:p.taskHierarchySegment,children:[a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx(Gu,{copied:de&&d===X.label,onClick:se=>i(se,X.label),disabled:t||!de,title:de?$e("actionHeader.copyTaskIdTitle"):"Task reference pending sync",label:M})]}):null,O?a.jsx("span",{className:p.taskHierarchyMeta,title:"Temporary local reference until cloud sync assigns the final task number.",children:"Pending sync"}):null]}),re&&!k?a.jsxs("div",{className:p.taskHierarchyEditor,children:[a.jsx("input",{type:"text",className:`${p.input} ${p.taskHierarchyInput}`,value:h,onChange:se=>g?.(se.target.value),placeholder:"WS-123","aria-label":"Attach workstream reference",onKeyDown:se=>{se.key==="Enter"&&(se.preventDefault(),_e()),se.key==="Escape"&&(se.preventDefault(),g?.(""),x(!1))}}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:_e,disabled:!h.trim()||t,title:"Attach workstream","aria-label":"Attach workstream",children:a.jsx(eo,{size:14})}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>{g?.(""),x(!1)},disabled:t,title:"Cancel workstream attach","aria-label":"Cancel workstream attach",children:a.jsx(ac,{size:14})})]}):null]}),a.jsx("div",{className:p.taskSaveStatusCenter,children:a.jsx("div",{className:`${p.taskSaveStatus} ${n==="error"?p.taskSaveStatusError:""}`,"aria-live":"polite",children:n==="saving"?a.jsxs(a.Fragment,{children:[a.jsx(pr,{size:14,className:p.spinner}),a.jsx("span",{children:"Saving…"})]}):n==="saved"?a.jsx("span",{children:"Saved"}):n==="error"?a.jsx("span",{children:"Save failed"}):null})}),a.jsx("div",{className:p.editActionsGroup,children:pe&&K?.deletedRecordId?a.jsxs(a.Fragment,{children:[me&&a.jsx("button",{type:"button",className:p.actionBtn,onClick:()=>me(K.deletedRecordId||""),disabled:t,title:"Restore deleted task",children:a.jsx(kd,{size:16})}),ve&&a.jsx("button",{type:"button",className:`${p.actionBtn} ${p.deleteBtn}`,onClick:()=>ve(K.deletedRecordId||""),disabled:t,title:"Permanently delete deleted task",children:a.jsx(gm,{size:16})})]}):a.jsx(hy,{task:K,disabled:t,statusDisabled:t||ue,archiveActionMode:ue?"unarchive":"auto",onSetStatus:(se,ce)=>{if(V){V(se,ce);return}if(ce==="in-progress"){A(se);return}if(ce==="review"){_(se);return}if(ce==="done"){I(se);return}ce==="cancelled"&&B(se)},onArchiveTask:L,onUnarchiveTask:se=>J?.(se.id)})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button",onClick:l,disabled:t,className:p.secondaryHeaderBtn,title:$e("actionHeader.clearFormTitle"),children:[a.jsx(kd,{size:16}),$e("actionHeader.clear")]}),a.jsxs("button",{type:"button",onClick:se=>o(se),disabled:t||!s.trim(),className:p.primaryUpdateBtn,title:$e("actionHeader.addTaskTitle"),children:[t?a.jsx(pr,{size:16,className:p.spinner}):a.jsx(to,{size:16}),$e("actionHeader.addTask")]})]})})}const JE="_topNoticeLayer_1m6a1_1",QE="_topNotice_1m6a1_1",XE="_topNoticeMessage_1m6a1_32",eD="_topNoticeSuccess_1m6a1_38",tD="_topNoticeError_1m6a1_44",aD="_topNoticeInfo_1m6a1_50",nD="_topNoticeDismiss_1m6a1_56",Gi={topNoticeLayer:JE,topNotice:QE,topNoticeMessage:XE,topNoticeSuccess:eD,topNoticeError:tD,topNoticeInfo:aD,topNoticeDismiss:nD};function Ay({notice:e,onDismiss:t}){if(!e)return null;const n=e.tone==="error"?Gi.topNoticeError:e.tone==="success"?Gi.topNoticeSuccess:Gi.topNoticeInfo,s=e.tone==="error"?"alert":"status";return a.jsx("div",{className:Gi.topNoticeLayer,children:a.jsxs("div",{className:`${Gi.topNotice} ${n}`,role:s,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?a.jsx(vd,{size:14}):e.tone==="success"?a.jsx(eo,{size:14}):a.jsx(Ek,{size:14}),a.jsx("span",{className:Gi.topNoticeMessage,children:e.message}),t&&a.jsx("button",{type:"button",className:Gi.topNoticeDismiss,onClick:t,"aria-label":"Dismiss notice",title:"Dismiss notice",children:a.jsx(ac,{size:14})})]})})}const rD=Fe.lazy(()=>vs(()=>import("./TaskSettings-DM1o9Wla.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings})));function sD(e){const{activeTab:t,setActiveTab:n,isOpen:s,setIsOpen:o,currentTheme:l,setCurrentTheme:i,saveSettings:d,pathSaved:m,keyShortcut:y,setKeyShortcut:k,jsonBackupEnabled:S,setJsonBackupEnabled:h,mcpHostRoot:g,setMcpHostRoot:v,settingsSection:A,setSettingsSection:_,projectRoot:I,projectName:B,mcpScriptPath:V,serverHostRoot:L,showFolderBrowser:J,setShowFolderBrowser:me,folders:ve,files:re,currentBrowsePath:x,fetchFolders:K,browserTarget:ue,setBrowserTarget:pe,handleSelectPath:X,handleAddPath:M,handleRemovePath:O,tasks:de,loadingTasks:ge,archivedTasks:$,deletedTasks:_e,activeCategories:je,activeTypes:se,priorities:ce,taxonomyDisplayLabels:Re,approaches:Pe,taxonomies:Ce,searchQuery:Ee,setSearchQuery:U,filterCategories:T,setFilterCategories:b,filterTypes:j,setFilterTypes:D,filterPriorities:te,setFilterPriorities:P,filterStatus:H,setFilterStatus:be,filterAssignees:z,setFilterAssignees:ie,assigneeOptions:ee,filterTaxonomies:Q,setFilterTaxonomies:q,sortBy:Se,setSortBy:we,sortOrder:Te,toggleSortOrder:Me,showArchive:nt,setShowArchive:gt,taskScope:lt,setTaskScope:St,clearFilters:Ke,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Xe,collapsedCategories:ct,setCollapsedCategories:ne,handleEdit:st,handleDelete:Ye,handleCopyId:Pt,handleToggleComplete:kt,handleToggleCancel:It,handleToggleInProgress:Ft,handleToggleReview:Mt,handleArchiveTask:Be,handleBulkArchive:et,handleUnarchive:Ue,handleRestoreDeletedTask:Qe,handlePermanentlyDeleteDeletedTask:yt,handleEmptyDeletedTasks:ot,fetchArchive:ae,editingTaskId:ze,loading:bt,error:Ot,title:Bt,setTitle:Oe,description:Lt,setDescription:vt,checklistItems:E,setChecklistItems:c,category:Y,setCategory:ye,type:Ie,setType:He,priority:Ve,setPriority:Ne,complexity:Vt,setComplexity:qt,manualComplexityEnabled:Et,checklistDropdownEnabled:Tt,showTaskCardStatusLabel:Wt,approach:Ht,setApproach:sa,assignee:Kt,setAssignee:Ka,scheduledDate:Fa,setScheduledDate:Xa,dueDate:wa,setDueDate:he,workstreamInput:it,setWorkstreamInput:xe,formTaxonomies:jt,setFormTaxonomies:tt,comments:Gt,newCommentText:ga,setNewCommentText:Na,attachments:ua,setAttachments:ca,setAttachmentsDirty:Dt,descriptionFocused:aa,setDescriptionFocused:Za,showMarkdownHelp:$t,setShowMarkdownHelp:Qn,showChecklist:ba,setShowChecklist:Qt,showComments:Lr,setShowComments:Ia,handleSubmit:en,resetForm:Ca,handleAddComment:Jt,handleSetWorkstreamForCurrentTask:Ta,handleOpenTaskById:la,autoSaveState:vn,unsavedModalOpen:pn,setUnsavedModalOpen:Xn,pendingNavigation:ma,handleNavigation:_r,handleClose:Br,scheduleWarningPrompt:Sn,confirmScheduleWarning:Ba,cancelScheduleWarning:Cr,uiNotice:wn,clearNotice:Pn,taskReturnTrail:tn,clearReturnToParentTask:Aa,returnToPreviousTask:Wr,copiedId:_t,recentlyChangedTaskIds:bn,tasksScrollRef:fn,setTasksScrollPos:_n,currentTask:Oa,currentTaskWorkstream:Mn,currentTaskInitiative:ya,exportEnvironment:$a,setExportEnvironment:Cn,exportWorkflowsPath:da,setExportWorkflowsPath:En,exportResult:Xt,exportingResource:Ua,availableWorkflows:_a,onExportWorkflows:er,availableEnvironments:tr,handleUpdateCategory:Pa,handleRemoveCategory:na,handleSaveCategory:pa,handleUpdateCategoryIcon:hn,handleUpdateCategoryColor:an,handleSaveType:fr,handleRemoveType:hr,handleUpdateTaxonomies:ea,handleUpdatePriorities:Ss,pathValidation:za,validatePaths:ar,getCategoryPaths:Xr,commentsEndRef:gn,currentWorkspaceId:zn,settingsModel:Fr,onHeaderMouseDown:An,isDragging:Ha}=e,Ar=r.useRef(null),[Ra,ws]=Fe.useState(0);r.useLayoutEffect(()=>{if(t==="tasks"&&fn.current&&Ra>0){const Je=setTimeout(()=>{fn.current&&(fn.current.scrollTop=Ra)},50);return()=>clearTimeout(Je)}},[t,Ra,de]);const nn=Je=>{we(Je)},xr=()=>{_r(()=>{if(t==="add"||t==="settings"){if(t==="add"&&Wr())return;t==="add"&&tn.length>0&&Aa(),t==="add"&&Ca(),n("tasks")}else e.onClose?e.onClose():Br()})},gr=()=>{Xn(!1),ma?(t==="add"&&Ca(),ma()):n("tasks")},Or=async()=>{await en({preventDefault:()=>{}}),Xn(!1),ma&&ma()},yn=(Je,Ut)=>{tt(Ma=>({...Ma,[Je]:Ut})),Je==="approach"&&typeof Ut=="string"&&sa(Ut)},yr=r.useCallback(Je=>{Ca(),ye(Je),_r(()=>{n("add")})},[Ca,ye,n,_r]),xn=Fe.useMemo(()=>_e.map(Je=>({...Je.taskSnapshot,isDeleted:!0,deletedRecordId:Je.id})),[_e]),Dn=Fe.useMemo(()=>new globalThis.Map(_e.map(Je=>[Je.taskId,Je])),[_e]),nr=Fe.useMemo(()=>{const Je=bm(Ee),Ut={categories:je,types:se,priorities:ce,assigneeOptions:ee,taxonomies:Ce},Ma=je.every(Rt=>T.includes(Rt.value)),oa=se.every(Rt=>j.includes(Rt.value)),cn=Array.from(new Set(te.map(Rt=>Number(Rt)).filter(Rt=>Number.isFinite(Rt)))),bs=ce.map(Rt=>Number(Rt.value)).filter(Rt=>Number.isFinite(Rt)).every(Rt=>cn.includes(Rt)),ts=["task","in-progress","review","done","cancelled","on-hold"].every(Rt=>H.includes(Rt)),Ya=ee.length>0&&ee.every(Rt=>z.includes(Rt.value)),Wa=xd(Ce,xn);return xn.filter(Rt=>{const kr=om(Rt,Je,Ut),Hn=Ma||T.includes(Rt.category),Ln=bs||cn.includes(Qu(Rt.priority)),rr=oa||j.includes(Rt.type||Dr),Cs=ts||H.includes(Rt.status),Ir=Ya||z.includes(Rt.assignee||"unassigned"),Ur=Object.entries(Q).every(([Fs,Bn])=>{const Wn=Wa.find(Nt=>Nt.id===Fs);if(!Wn||vf(Wn,xn).every(Nt=>Bn.includes(Nt.value)))return!0;const At=Rt.taxonomies?.[Fs];return At?Array.isArray(At)?At.some(Nt=>Bn.includes(Nt)):Bn.includes(At):Bn.includes("")});return kr&&Hn&&Ln&&rr&&Cs&&Ir&&Ur}).sort((Rt,kr)=>im(Rt,kr,Se,Te,Ce))},[je,se,$,ee,xn,z,T,te,H,Q,j,ce,Ee,Se,Te,Ce,de]),es=Fe.useMemo(()=>{const Je={};return nr.forEach(Ut=>{const oa=je.find(cn=>cn.value===Ut.category||cn.label===Ut.category)?.label||Ut.category||"General";Je[oa]||(Je[oa]=[]),Je[oa].push(Ut)}),Je},[je,nr]),$r=lt==="archived"?dt.length:lt==="deleted"?nr.length:Ct.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:Ar,className:`${xt.modal} ${p.coreModal} ${t==="settings"?xt.settingsViewModal:""}`,"data-theme":l,children:[a.jsxs("div",{className:"tf-modal-header",onMouseDown:An,style:{cursor:An?Ha?"grabbing":"grab":"default"},children:[a.jsxs("div",{className:`tf-modal-title ${ta.headerTitleWidget}`,children:["Taskforce",B&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.projectSlash,children:"/"}),a.jsx("span",{className:p.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:B})]}),a.jsx("span",{className:p.taskCountBadge,title:`${lt.charAt(0).toUpperCase()+lt.slice(1)} tasks`,children:$r})]}),a.jsxs("div",{className:xt.headerActions,children:[t==="tasks"&&a.jsx(a.Fragment,{children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{_r(()=>{Ca(),n("add")})},title:"Add New Task",children:a.jsx(to,{size:18})})}),a.jsx("button",{className:`tf-control-icon ${t==="settings"?"tf-control-icon-active":""}`,onClick:()=>{t!=="settings"&&_r(()=>{n("settings")})},title:"Settings",children:a.jsx(Xp,{size:18})}),a.jsx("button",{className:"tf-control-icon",onClick:xr,title:t==="tasks"?"Close":"Back to Tasks",children:t==="tasks"?a.jsx(ac,{size:20}):a.jsx(Dk,{size:20})})]})]}),a.jsx(Ay,{notice:wn,onDismiss:Pn}),t==="add"&&a.jsx(Cy,{editingTaskId:ze,loading:bt,autoSaveState:vn,title:Bt,currentTask:Oa,currentTaskWorkstream:Mn,currentTaskInitiative:ya,workstreamInput:it,onWorkstreamInputChange:xe,onSetWorkstreamForCurrentTask:Ta,handleSubmit:en,resetForm:Ca,handleCopyId:Pt,copiedId:_t,tasks:de,handleToggleInProgress:Ft,handleToggleReview:Mt,handleToggleComplete:kt,handleToggleCancel:It,handleArchiveTask:Be,handleUnarchiveTask:Je=>{if(Oa?.isDeleted){const Ut=Dn.get(Je);Ut&&Qe(Ut.id);return}Ue(Je)},handleRestoreDeletedTask:Je=>{Qe(Je)},handlePermanentlyDeleteDeletedTask:Je=>{yt(Je)}}),t==="tasks"&&a.jsx(by,{ref:fn,tasks:de,archivedTasks:$,categories:je,types:se,priorities:ce,taxonomyDisplayLabels:Re,taxonomies:Ce,searchQuery:Ee,filterCategories:T,filterTypes:j,filterPriorities:te,filterStatus:H,filterAssignees:z,assigneeOptions:ee,filterTaxonomies:Q,sortBy:Se,sortOrder:Te,showArchive:nt,taskScope:lt,collapsedCategories:ct,loadingTasks:ge,filteredTasks:Ct,filteredArchive:dt,groupedTasks:Xe,filteredDeletedTasks:nr,groupedDeletedTasks:es,copiedId:_t,recentlyChangedTaskIds:bn,showTaskCardStatusLabel:Wt,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:U,onFilterCategoriesChange:Je=>b(Je),onFilterTypesChange:Je=>D(Je),onFilterPrioritiesChange:P,onFilterStatusChange:be,onFilterAssigneesChange:Je=>ie(Je),onTaxonomyFilterChange:(Je,Ut)=>q(Ma=>({...Ma,[Je]:Ut})),onSortByChange:nn,onSortOrderChange:Me,onShowArchiveChange:gt,onTaskScopeChange:St,onClearFilters:Ke,onToggleCategory:Je=>ne(Ut=>({...Ut,[Je]:!Ut[Je]})),onEditTask:st,onOpenTaskById:la,onCopyId:Pt,onToggleInProgress:Ft,onToggleReview:Mt,onToggleComplete:kt,onToggleCancel:It,onArchiveTask:Be,onBulkArchive:et,onUnarchive:Je=>{const Ut=Dn.get(Je);if(Ut){Qe(Ut.id);return}Ue(Je)},onDelete:Je=>{const Ut=Dn.get(Je);if(Ut){yt(Ut.id);return}Ye(Je)},onDeleteAllDeleted:()=>{ot()},onFetchArchive:ae,onAddTaskToCategory:yr,supplementalTasks:xn}),t==="add"&&a.jsx(_y,{editingTaskId:ze,error:Ot,title:Bt,description:Lt,checklistItems:E,category:Y,type:Ie,priority:Ve,complexity:Vt,manualComplexityEnabled:Et,approach:Ht,assignee:Kt,scheduledDate:Fa,dueDate:wa,workstreamInput:it,formTaxonomies:jt,onTaxonomyChange:yn,taxonomies:Ce,comments:Gt,newCommentText:ga,contextFiles:ua,currentWorkspaceId:zn,apiBaseUrl:"",descriptionFocused:aa,showMarkdownHelp:$t,showChecklist:ba,checklistEnabled:Tt,showComments:Lr,categories:je,types:se,priorities:ce,taxonomyDisplayLabels:Re,assigneeOptions:ee,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:_t,onTitleChange:Oe,onDescriptionChange:vt,onChecklistItemsChange:c,onCategoryChange:ye,onTypeChange:He,onPriorityChange:Ne,onComplexityChange:qt,onApproachChange:Je=>{sa(Je),tt(Ut=>({...Ut,approach:Je}))},onAssigneeChange:Ka,onScheduledDateChange:Xa,onDueDateChange:he,onWorkstreamInputChange:xe,onNewCommentTextChange:Na,onDescriptionFocusedChange:Za,onShowMarkdownHelpChange:Qn,onShowChecklistChange:Qt,onShowCommentsChange:Ia,onOpenSettings:Je=>{_r(()=>{_(Je),n("settings")})},onSubmit:en,commentsEndRef:gn,onAddComment:()=>Jt(ga),onOpenTaskById:la,onAddContextFile:Je=>{Dt(!0),ca(Ut=>[...Ut,Je])},onRemoveContextFile:async Je=>{Dt(!0),ca(Ut=>Ut.filter((Ma,oa)=>oa!==Je))},onUpdateContextCaption:(Je,Ut)=>{Dt(!0),ca(Ma=>Ma.map((oa,cn)=>cn!==Je?oa:typeof oa=="string"?{path:oa,caption:Ut,timestamp:new Date().toISOString()}:{...oa,caption:Ut}))},onCopyId:Pt,onToggleInProgress:Ft,onToggleReview:Mt,onToggleComplete:kt,onToggleCancel:It,onArchiveTask:Be,onUnarchive:Je=>{if(Oa?.isDeleted){const Ut=Dn.get(Je);Ut&&Qe(Ut.id);return}Ue(Je)},currentTask:Oa}),t==="settings"&&a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(rD,{settingsModel:Fr,onSectionChange:_})})]}),J&&Zi.createPortal(a.jsx("div",{className:ja.overlay,children:a.jsxs("div",{className:ja.browser,children:[a.jsxs("div",{className:ja.header,children:[a.jsxs("div",{className:ja.pathInfo,children:[a.jsx(Ro,{size:14}),a.jsx("span",{children:x||"Project Root"})]}),a.jsxs("div",{className:ja.actions,children:[x&&a.jsx("button",{className:p.helpLink,onClick:()=>{const Je=x.split("/").filter(Boolean);Je.pop(),K(Je.length?Je.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:p.helpLink,onClick:()=>me(!1),children:"Close"})]})]}),a.jsxs("div",{className:ja.list,children:[ue&&typeof ue=="object"&&a.jsxs("div",{className:`${ja.item} ${ja.itemCurrent}`,onClick:()=>X(x),children:[a.jsx(eo,{size:14})," Select Current: ./",x||"(root)"]}),ve.map(Je=>a.jsxs("div",{className:ja.item,onClick:()=>K(x+Je+"/"),children:[a.jsx(Ro,{size:14})," ",Je,"/"]},Je)),re.map(Je=>a.jsxs("div",{className:`${ja.item} ${ja.itemFile}`,onClick:()=>X(x+Je),children:[a.jsx(Pp,{size:14})," ",Je]},Je)),ve.length===0&&re.length===0&&a.jsx("div",{className:`${ja.item} ${ja.empty}`,children:"No items found"})]})]})}),document.body),pn&&a.jsx("div",{className:`${xt.overlay} ${xt.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${xt.modal} ${xt.unsavedModal}`,"data-theme":l,children:[a.jsx("div",{className:`tf-modal-header ${xt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${xt.unsavedTitle}`,children:[a.jsx(vd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${xt.form} ${xt.unsavedContent}`,children:a.jsx("p",{className:xt.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${xt.formActions} ${xt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>Xn(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:p.destructiveBtn,onClick:gr,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:p.submitBtn,onClick:Or,disabled:bt,title:"Save changes and leave",children:[bt?a.jsx(pr,{size:16,className:p.spinner}):a.jsx(dg,{size:16}),"Save"]})]})]})}),Sn&&a.jsx("div",{className:`${xt.overlay} ${xt.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${xt.modal} ${xt.unsavedModal}`,"data-theme":l,children:[a.jsx("div",{className:`tf-modal-header ${xt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${xt.unsavedTitle}`,children:[a.jsx(vd,{size:20}),"Date Warning"]})}),a.jsxs("div",{className:`${xt.form} ${xt.unsavedContent}`,children:[a.jsx("p",{className:xt.unsavedText,children:"Due date is before scheduled date."}),a.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",Sn.dueDate," · Scheduled: ",Sn.scheduledDate]})]}),a.jsxs("div",{className:`${xt.formActions} ${xt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:Cr,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:Ba,children:"Save Anyway"})]})]})})]})}const oD="_accountMenuWrap_1mocf_1",iD="_avatarBtn_1mocf_5",cD="_avatarBadge_1mocf_9",lD="_avatarImage_1mocf_24",dD="_avatarIcon_1mocf_30",uD="_accountMenu_1mocf_1",mD="_accountMenuItem_1mocf_48",pD="_accountMenuItemActive_1mocf_68",fD="_accountMenuSection_1mocf_73",hD="_accountMenuSectionLabel_1mocf_79",gD="_accountMenuMeta_1mocf_88",yD="_accountMenuHint_1mocf_93",kD="_accountIdentityEmail_1mocf_99",vD="_accountIdentityBlock_1mocf_104",SD="_accountIdentityMetaLine_1mocf_109",wD="_accountIdentityMetaAction_1mocf_116",bD="_accountIdentityMetaValue_1mocf_125",_D="_accountIdentityMetaLabel_1mocf_130",CD="_accountMenuError_1mocf_159",AD="_accountHubCard_1mocf_165",xD="_profileAvatarEditor_1mocf_172",ID="_profileEditLayout_1mocf_178",TD="_profileFieldStack_1mocf_185",RD="_profileFieldLabel_1mocf_191",ft={accountMenuWrap:oD,avatarBtn:iD,avatarBadge:cD,avatarImage:lD,avatarIcon:dD,accountMenu:uD,accountMenuItem:mD,accountMenuItemActive:pD,accountMenuSection:fD,accountMenuSectionLabel:hD,accountMenuMeta:gD,accountMenuHint:yD,accountIdentityEmail:kD,accountIdentityBlock:vD,accountIdentityMetaLine:SD,accountIdentityMetaAction:wD,accountIdentityMetaValue:bD,accountIdentityMetaLabel:_D,accountMenuError:CD,accountHubCard:AD,profileAvatarEditor:xD,profileEditLayout:ID,profileFieldStack:TD,profileFieldLabel:RD},jD="_authBlockedBanner_1virb_1",ND="_loginView_1virb_10",PD="_loginCard_1virb_20",MD="_loginCloseBtn_1virb_34",ED="_loginLogo_1virb_56",DD="_authBrandRow_1virb_62",LD="_setupHeaderRow_1virb_68",BD="_runtimeIconBadge_1virb_75",WD="_loginTitle_1virb_94",FD="_loginTitleAccent_1virb_105",OD="_loginSubtitle_1virb_109",$D="_loginError_1virb_115",UD="_loginField_1virb_121",zD="_loginFieldLabel_1virb_126",HD="_loginInput_1virb_133",GD="_loginPrimaryBtn_1virb_149",VD="_authPrimaryActions_1virb_154",qD="_registerConsent_1virb_159",KD="_registerConsentLink_1virb_167",ZD="_authModeSwitch_1virb_177",YD="_authModeSwitchLink_1virb_184",JD="_authModeLinks_1virb_199",QD="_authSecondaryActions_1virb_207",XD="_authModeLink_1virb_199",eL="_optionGrid_1virb_236",tL="_optionGroup_1virb_242",aL="_optionRow_1virb_247",nL="_inlineHint_1virb_254",rL="_actionRowEnd_1virb_260",sL="_oauthProviders_1virb_267",oL="_oauthDivider_1virb_274",iL="_oauthButtons_1virb_290",cL="_oauthButton_1virb_290",fe={authBlockedBanner:jD,loginView:ND,loginCard:PD,loginCloseBtn:MD,loginLogo:ED,authBrandRow:DD,setupHeaderRow:LD,runtimeIconBadge:BD,loginTitle:WD,loginTitleAccent:FD,loginSubtitle:OD,loginError:$D,loginField:UD,loginFieldLabel:zD,loginInput:HD,loginPrimaryBtn:GD,authPrimaryActions:VD,registerConsent:qD,registerConsentLink:KD,authModeSwitch:ZD,authModeSwitchLink:YD,authModeLinks:JD,authSecondaryActions:QD,authModeLink:XD,optionGrid:eL,optionGroup:tL,optionRow:aL,inlineHint:nL,actionRowEnd:rL,oauthProviders:sL,oauthDivider:oL,oauthButtons:iL,oauthButton:cL};function lL(e={x:0,y:0}){const[t,n]=r.useState(e),[s,o]=r.useState(!1),[l,i]=r.useState({x:0,y:0}),[d,m]=r.useState(0),y=r.useRef(null),k=r.useCallback(g=>{const v=g.target;if(!(v.closest("button")||v.closest("input")||v.closest("select")||v.closest("textarea")||v.closest('[role="button"]')||v.closest(".no-drag"))){if(y.current){const A=y.current.getBoundingClientRect();m(A.top-t.y)}o(!0),i({x:g.clientX-t.x,y:g.clientY-t.y})}},[t]),S=r.useCallback(g=>{if(s){let v=g.clientX-l.x,A=g.clientY-l.y;A<-d&&(A=-d),n({x:v,y:A})}},[s,l,d]),h=r.useCallback(()=>{o(!1)},[]);return r.useEffect(()=>(s?(window.addEventListener("mousemove",S),window.addEventListener("mouseup",h)):(window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",h)),()=>{window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",h)}),[s,S,h]),{position:t,isDragging:s,handleMouseDown:k,modalRef:y,setPosition:n}}function Ws({isOpen:e,onClose:t,title:n,children:s,footer:o,size:l="md",theme:i=Ju,className:d,headerActions:m,draggable:y=!1,isSettings:k=!1,closeOnOverlayClick:S=!0}){const h=r.useRef(null),{position:g,isDragging:v,handleMouseDown:A,modalRef:_}=lL();if(r.useEffect(()=>{const B=V=>{V.key==="Escape"&&e&&t()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e,t]),r.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const I={sm:xt.modalSizeSm,md:xt.modalSizeMd,mdWide:xt.modalSizeMdWide,lg:xt.modalSizeLg,xl:xt.modalSizeXl,full:xt.modalSizeFull};return Zi.createPortal(a.jsx("div",{className:`${xt.overlay} ${d||""} ${xt.overlayHighZ}`,ref:h,onClick:B=>{S&&B.target===h.current&&t()},children:a.jsxs("div",{ref:_,className:`tf-surface-modal tf-modal-shell ${xt.modal} tf-scrollbar-scope ${I[l]} ${y?xt.draggableModal:""} ${k?xt.settingsViewModal:""}`,"data-theme":i,style:{transform:y?`translate(${g.x}px, ${g.y}px)`:void 0,transition:v?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[a.jsxs("div",{className:`tf-modal-header ${y?xt.draggableHeader:""}`,onMouseDown:y?A:void 0,style:{cursor:y?v?"grabbing":"grab":"default"},children:[a.jsx("div",{className:"tf-modal-title",children:n}),a.jsxs("div",{className:xt.headerActions,children:[m,a.jsx("button",{className:"tf-control-icon",onClick:t,title:"Close",children:a.jsx(ac,{size:20})})]})]}),a.jsx("div",{className:xt.modalContent,children:s}),o&&a.jsx("div",{className:`${xt.formActions} ${xt.modalFooter}`,children:o})]})}),document.body)}const dL="_modalBody_1t87j_1",uL="_mutedText_1t87j_5",mL="_sectionText_1t87j_10",pL="_sectionTextSpaced_1t87j_15",fL="_sectionTextTop_1t87j_20",hL="_errorText_1t87j_25",gL="_inlineFieldLabel_1t87j_29",yL="_wrapRow_1t87j_35",kL="_actionRowEnd_1t87j_42",vL="_modalActionsEnd_1t87j_50",SL="_helpIntro_1t87j_56",wL="_supportEmailRow_1t87j_61",bL="_supportEmailAddress_1t87j_68",_L="_supportEmailBtn_1t87j_80",CL="_supportPanel_1t87j_86",AL="_supportPanelHeader_1t87j_92",xL="_supportRouteList_1t87j_104",IL="_supportRouteBtn_1t87j_110",TL="_memberRow_1t87j_114",RL="_memberTitle_1t87j_120",jL="_memberActions_1t87j_124",NL="_selectRole_1t87j_131",PL="_selectPermission_1t87j_135",ML="_inviteRow_1t87j_139",EL="_listHeading_1t87j_143",DL="_auditList_1t87j_148",LL="_auditPager_1t87j_154",BL="_labelFixed_1t87j_161",mt={modalBody:dL,mutedText:uL,sectionText:mL,sectionTextSpaced:pL,sectionTextTop:fL,errorText:hL,inlineFieldLabel:gL,wrapRow:yL,actionRowEnd:kL,modalActionsEnd:vL,helpIntro:SL,supportEmailRow:wL,supportEmailAddress:bL,supportEmailBtn:_L,supportPanel:CL,supportPanelHeader:AL,supportRouteList:xL,supportRouteBtn:IL,memberRow:TL,memberTitle:RL,memberActions:jL,selectRole:NL,selectPermission:PL,inviteRow:ML,listHeading:EL,auditList:DL,auditPager:LL,labelFixed:BL};function WL({isOpen:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"New Workspace",size:"sm",theme:t,draggable:!0,footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.cancelBtn,onClick:n,children:"Cancel"}),a.jsx("button",{type:"button",className:p.submitBtn,onClick:s,children:"Start Setup"})]}),children:a.jsx("div",{className:`${xt.form} ${mt.modalBody}`,children:a.jsx("p",{className:mt.sectionText,children:"Create and configure a new workspace."})})})}const FL=new Set(["active","trialing","grace"]),Dh={CHECKOUT_SESSION_EXPIRED:"Your previous checkout expired. Choose a plan to continue.",CHECKOUT_SESSION_SUPERSEDED:"A newer checkout replaced your previous checkout. Choose a plan to continue."},Bu={planSelectionRequired:"Choose a plan to continue.",checkoutPending:"Complete checkout to continue.",misconfigured:"Onboarding policy is misconfigured. Contact support or a system administrator.",missingEntitlement:"No entitlement is linked to this account."};function tc(e){return String(e||"").trim()}function xy(e){return tc(e).toLowerCase()}function OL(e){return tc(e).toLowerCase()}function $L(e){return!!(tc(e?.stripeCustomerId)||tc(e?.stripeSubscriptionId))}function UL(e){const t=tc(e?.trialEnd||e?.effectiveUntil);if(t){const n=new Date(t);if(!Number.isNaN(n.getTime()))return n.getTime()<=Date.now()?"Your trial end date has passed. Billing status is updating.":`Your trial is active through ${n.toLocaleString()}.`}return"Your trial is active. Continue to Taskforce or manage billing anytime."}function zL(e){return FL.has(xy(e))}function Gp(e,t){const n=xy(e?.entitlementState),s=OL(e?.gate||t),o=tc(e?.billingConflictCode).toUpperCase(),l=tc(e?.message),i=zL(n),d=$L(e);return o==="CHECKOUT_SESSION_EXPIRED"?{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Dh.CHECKOUT_SESSION_EXPIRED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:o==="CHECKOUT_SESSION_SUPERSEDED"?{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:Dh.CHECKOUT_SESSION_SUPERSEDED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:n==="trialing"?{entitlementState:n,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:UL(e),primaryAction:d?"manage_billing":"none",primaryLabel:d?"Manage Billing":null,showManageBilling:d,markCurrentPlan:!0}:i?{entitlementState:n||null,gate:s||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:l||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!0}:n==="suspended"?{entitlementState:n,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access is suspended because billing needs attention. Update billing to restore access.",primaryAction:d?"manage_billing":"open_plans",primaryLabel:d?"Manage Billing":"Open Plans",showManageBilling:d,markCurrentPlan:!1}:n==="canceled"?{entitlementState:n,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access has ended. Choose a plan to reactivate your workspace.",primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:d,markCurrentPlan:!1}:n==="pending_plan_selection"||e?.planSelectionRequired===!0||s==="plan_selection_required"?{entitlementState:n||"pending_plan_selection",gate:s||"plan_selection_required",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:l||Bu.planSelectionRequired,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:n==="checkout_pending"||s==="checkout_pending"?{entitlementState:n||"checkout_pending",gate:s||"checkout_pending",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:l||Bu.checkoutPending,primaryAction:"open_plans",primaryLabel:"Open Plans",showManageBilling:d,markCurrentPlan:!1}:s==="misconfigured"?{entitlementState:n||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Bu.misconfigured,primaryAction:"none",primaryLabel:null,showManageBilling:!1,markCurrentPlan:!1}:s==="missing_entitlement"?{entitlementState:n||null,gate:s,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Bu.missingEntitlement,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:{entitlementState:n||null,gate:s||null,isActive:!1,allowReturnToApp:!1,statusTone:l?"error":"info",message:l||null,primaryAction:"none",primaryLabel:null,showManageBilling:d,markCurrentPlan:!1}}const Vp=12,HL=new Set(["12345678","123456789","1234567890","admin123","changeme","letmein","letmein123","password","password1","password12","password123","password1234","qwerty","qwerty123","welcome","welcome123"]),GL=e=>String(e||"").trim().toLowerCase().replace(/[^a-z0-9]/g,"");function VL(e){const t=new Set,n=String(e?.email||"").trim().toLowerCase(),s=String(e?.displayName||"").trim().toLowerCase();if(n.includes("@")){const o=n.split("@")[0]||"",l=o.replace(/[^a-z0-9]/g,"");l.length>=4&&t.add(l);for(const i of o.split(/[^a-z0-9]+/))i.length>=4&&t.add(i)}for(const o of s.split(/[^a-z0-9]+/))o.length>=4&&t.add(o);return[...t]}function Iy(){return[`Use at least ${Vp} characters.`,"Avoid common passwords or obvious patterns.","Do not include your email or display name."]}function Ty(e,t){const n=String(e||"");if(!n)return{ok:!1,code:"PASSWORD_REQUIRED",message:"Password is required."};if(n.length<Vp)return{ok:!1,code:"PASSWORD_TOO_SHORT",message:`Password must be at least ${Vp} characters.`};const s=GL(n);return HL.has(s)?{ok:!1,code:"PASSWORD_TOO_COMMON",message:"Choose a less common password."}:VL(t).some(l=>s.includes(l))?{ok:!1,code:"PASSWORD_CONTAINS_PERSONAL_INFO",message:"Password cannot contain your email or display name."}:{ok:!0}}function qL({isOpen:e,theme:t,runtimeMode:n,authRequiredForApi:s,isAuthenticated:o,hasAuthIdentity:l,authIdentityLabel:i,billingLoading:d,billingError:m,billingActionError:y,billingNotice:k,billingActionBusy:S,billingIntervalChoice:h,accountProfileSummary:g,currentWorkspaceId:v,canOpenTeamManagement:A,canManageWorkspaceSync:_,workspaceCloudSyncEnabled:I,syncStatusLabel:B,workspaceSyncError:V,syncControlBusy:L,cloudAuthEnabled:J,availableAuthProviders:me,onFetchLoginMethods:ve,onUnlinkLoginMethod:re,onAddPassword:x,onLinkProvider:K,onClose:ue,onOpenWorkspaceAudit:pe,onBillingIntervalChange:X,onRefreshBilling:M,onUpdateInterval:O,onManageBilling:de,onStartCheckout:ge,onToggleWorkspaceSync:$,onOpenHelp:_e}){const je=Gp(g),se=Iy(),ce=je.message,Re=je.primaryLabel||"Start Checkout",Pe=String(g?.planName||g?.planId||"n/a").trim()||"n/a",Ce=()=>{if(je.primaryAction==="manage_billing"){de();return}ge()},[Ee,U]=r.useState([]),[T,b]=r.useState(!1),[j,D]=r.useState(null),[te,P]=r.useState(null),[H,be]=r.useState(null),[z,ie]=r.useState(!1),[ee,Q]=r.useState(""),[q,Se]=r.useState(!1),[we,Te]=r.useState(null),[Me,nt]=r.useState(!1);r.useEffect(()=>{!e||!o||!J||(b(!0),D(null),ve().then(Xe=>{b(!1),Xe.success&&Xe.methods?U(Xe.methods):D(Xe.error||"Failed to load login methods.")}))},[e,o,J,ve]);const gt=async Xe=>{P(Xe),be(null);const ct=await re(Xe);P(null),ct.success?U(ne=>ne.filter(st=>st.provider!==Xe)):be(ct.error||"Unlink failed.")},lt=async()=>{const Xe=Ty(ee);if(!Xe.ok){Te(Xe.message||"Password does not meet the password policy.");return}Se(!0),Te(null);const ct=await x(ee);if(Se(!1),!ct.success)Te(ct.error||"Failed to add password.");else{nt(!0),Q(""),ie(!1);const ne=await ve();ne.success&&ne.methods&&U(ne.methods)}},St={password:"Email & Password",google:"Google",github:"GitHub",apple:"Apple"},Ke=new Set(Ee.map(Xe=>Xe.provider)),Ct=Ke.has("password"),dt=me.filter(Xe=>Xe!=="password"&&!Ke.has(Xe));return a.jsx(Ws,{isOpen:e,onClose:ue,title:"Account Hub",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${xt.form} ${mt.modalBody}`,children:[a.jsx("p",{className:mt.mutedText,children:"Manage sign in, profile, and workspace controls from one place."}),a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Authentication"}),a.jsx("p",{className:mt.sectionText,children:n==="cloud"?s?o?"Signed in. API access is enabled.":"Cloud mode requires sign in before app usage.":"Cloud runtime with optional authentication.":"Local runtime allows guest usage without sign in."}),a.jsx("p",{className:mt.sectionTextSpaced,children:o?l?a.jsxs(a.Fragment,{children:["Signed in as ",a.jsx("span",{className:ft.accountIdentityEmail,children:i})]}):"Signed in":"Signed in as: not signed in"}),n==="cloud"&&s&&!o&&a.jsx("p",{className:mt.sectionTextTop,children:"Use the `/login` screen to sign in."})]}),o&&J&&a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Login Methods"}),T&&a.jsx("p",{className:mt.sectionText,children:"Loading..."}),j&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:j}),H&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:H}),Me&&a.jsx("p",{className:mt.sectionText,style:{color:"var(--color-success, #4ade80)"},children:"Password login added."}),!T&&Ee.length>0&&a.jsx("div",{style:{marginTop:8,display:"grid",gap:6},children:Ee.map(Xe=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[a.jsxs("span",{className:mt.sectionText,children:[a.jsx("strong",{children:St[Xe.provider]||Xe.provider}),Xe.providerEmail?a.jsxs(a.Fragment,{children:[" · ",a.jsx("span",{className:ft.accountMenuMeta,children:Xe.providerEmail})]}):null]}),Ee.length>1&&a.jsx("button",{className:p.cancelBtn,style:{fontSize:11,padding:"2px 8px"},disabled:te===Xe.provider,onClick:()=>gt(Xe.provider),children:te===Xe.provider?"Removing…":"Remove"})]},Xe.provider))}),!T&&!Ct&&!z&&a.jsx("div",{className:mt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,onClick:()=>{ie(!0),nt(!1),Te(null)},children:"Add Password Login"})}),z&&a.jsxs("div",{style:{marginTop:10,display:"grid",gap:6},children:[a.jsxs("label",{className:ft.accountMenuMeta,style:{display:"block"},children:["New password",a.jsx("input",{type:"password",className:p.input,placeholder:"Use 12+ characters",value:ee,onChange:Xe=>Q(Xe.target.value),disabled:q,style:{marginTop:4,display:"block",width:"100%"},autoComplete:"new-password"})]}),a.jsx("p",{className:ft.accountMenuMeta,style:{margin:0},children:se.join(" ")}),we&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:we}),a.jsxs("div",{className:mt.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>{ie(!1),Q(""),Te(null)},disabled:q,children:"Cancel"}),a.jsx("button",{className:p.submitBtn,onClick:lt,disabled:q||!ee,children:q?"Saving…":"Save Password"})]})]}),!T&&dt.length>0&&a.jsxs("div",{style:{marginTop:10},children:[a.jsx("p",{className:ft.accountMenuMeta,style:{marginBottom:6},children:"Link another account:"}),a.jsx("div",{className:fe.oauthButtons,children:dt.map(Xe=>a.jsx("button",{className:fe.oauthButton,onClick:()=>K(Xe),children:St[Xe]||Xe},Xe))})]})]}),a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Profile & Account"}),a.jsx("p",{className:mt.sectionText,children:"Profile editing and account preferences will live here."})]}),a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Billing"}),o?n!=="cloud"?a.jsx("p",{className:mt.sectionText,children:"Billing remains cloud-backed in local runtime and uses your connected cloud account."}):a.jsxs(a.Fragment,{children:[d&&a.jsx("p",{className:mt.sectionTextSpaced,children:"Loading billing status..."}),m&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:m}),y&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:y}),k&&a.jsx("p",{className:mt.errorText,children:k}),ce&&a.jsx("p",{className:mt.sectionText,children:ce}),a.jsxs("p",{className:mt.sectionTextSpaced,children:["Plan: ",a.jsx("code",{children:Pe})," · ","Entitlement: ",a.jsx("code",{children:String(g?.entitlementState||"n/a")})]}),a.jsxs("p",{className:mt.sectionText,children:["Stripe status: ",a.jsx("code",{children:String(g?.stripeStatus||"n/a")}),g?.effectiveUntil?` · Effective until ${new Date(g.effectiveUntil).toLocaleString()}`:""]}),a.jsx("div",{className:mt.wrapRow,children:a.jsxs("label",{className:`${ft.accountMenuMeta} ${mt.inlineFieldLabel}`,children:["Interval",a.jsxs("select",{className:p.input,value:h,onChange:Xe=>X(Xe.target.value==="year"?"year":"month"),disabled:S,children:[a.jsx("option",{value:"month",children:"Monthly"}),a.jsx("option",{value:"year",children:"Yearly"})]})]})}),a.jsxs("div",{className:mt.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,onClick:M,disabled:S||d,children:"Refresh Billing"}),a.jsx("button",{className:p.cancelBtn,onClick:O,disabled:S||!g?.stripeSubscriptionId,children:"Update Interval"}),a.jsx("button",{className:p.cancelBtn,onClick:de,disabled:S||!g?.stripeCustomerId,children:"Manage Billing"}),a.jsx("button",{className:p.submitBtn,onClick:Ce,disabled:S||je.primaryAction==="manage_billing"&&!g?.stripeCustomerId,children:S?"Working...":Re})]})]}):a.jsx("p",{className:mt.sectionText,children:"Sign in to manage subscription billing."})]}),a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Workspace Audit Log"}),a.jsx("p",{className:mt.sectionText,children:"Audit entries are workspace-scoped for the active workspace, not global account history."}),a.jsxs("p",{className:mt.sectionText,children:["Active workspace: ",a.jsx("code",{children:v})]}),a.jsx("div",{className:mt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,onClick:pe,disabled:!A,children:"Open Workspace Audit"})})]}),a.jsxs("div",{className:ft.accountHubCard,children:[a.jsx("strong",{children:"Workspace Cloud Sync"}),a.jsx("p",{className:mt.sectionText,children:_?I?`Enabled · ${B}`:"Disabled":"Sign in to cloud account to enable workspace sync."}),V&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:V}),a.jsx("div",{className:mt.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,disabled:!_||L,onClick:()=>$(!I),children:I?"Disable Sync":"Enable Sync"})})]}),a.jsxs("div",{className:`${xt.formActions} ${mt.modalActionsEnd}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:_e,children:"Help & Support"}),a.jsx("button",{className:p.submitBtn,onClick:ue,children:"Close"})]})]})})}var Lh=(e,t,n,s,o,l)=>{if(l===0)e.rect(t,n,s,o);else{let i=s-l,d=o-l;e.translate(t,n),e.arc(l,l,l,Math.PI,Math.PI*1.5),e.lineTo(i,0),e.arc(i,l,l,Math.PI*1.5,Math.PI*2),e.lineTo(s,d),e.arc(i,d,l,Math.PI*2,Math.PI*.5),e.lineTo(l,o),e.arc(l,d,l,Math.PI*.5,Math.PI),e.closePath(),e.translate(-t,-n)}},KL=(e,t,n,s,o,l)=>{e.fillStyle=l;let i=s/3,d=o/3;e.fillRect(t,n,1,o),e.fillRect(i+t,n,1,o),e.fillRect(i*2+t,n,1,o),e.fillRect(i*3+t,n,1,o),e.fillRect(i*4+t,n,1,o),e.fillRect(t,n,s,1),e.fillRect(t,d+n,s,1),e.fillRect(t,d*2+n,s,1),e.fillRect(t,d*3+n,s,1),e.fillRect(t,d*4+n,s,1)},ZL=e=>!!e.match(/^\s*data:([a-z]+\/[a-z]+(;[a-z-]+=[a-z-]+)?)?(;base64)?,[a-z0-9!$&',()*+;=\-._~:@/?%\s]*\s*$/i),Ry=(e,t)=>new Promise((n,s)=>{let o=new Image;o.addEventListener("load",()=>n(o)),o.addEventListener("error",s),!ZL(e)&&t&&(o.crossOrigin=t),o.src=e}),YL=e=>new Promise((t,n)=>{let s=new FileReader;s.addEventListener("load",o=>{try{if(!o?.target?.result)throw Error("No image data");t(Ry(o.target.result))}catch(l){n(l)}}),s.readAsDataURL(e)}),JL=typeof File<"u",Bh=e=>Math.PI/180*e,Wh={x:.5,y:.5},QL=class{constructor(e){this.imageState=Wh,this.config={border:25,borderRadius:0,scale:1,rotate:0,color:[0,0,0,.5],backgroundColor:"",borderColor:void 0,showGrid:!1,gridColor:"#666",disableBoundaryChecks:!1,disableHiDPIScaling:!1,disableCanvasRotation:!0,crossOrigin:void 0,...e},this.pixelRatio=typeof window<"u"&&window.devicePixelRatio&&!this.config.disableHiDPIScaling?window.devicePixelRatio:1}getPixelRatio(){return this.pixelRatio}getImageState(){return this.imageState}setImageState(e){this.imageState=e}updateConfig(e){this.config={...this.config,...e}}isVertical(){return!this.config.disableCanvasRotation&&this.config.rotate%180!=0}getBorders(e){let t=e??this.config.border;return Array.isArray(t)?t:[t,t]}getDimensions(){let{width:e,height:t,rotate:n,border:s}=this.config,o={width:0,height:0},[l,i]=this.getBorders(s);return this.isVertical()?(o.width=t,o.height=e):(o.width=e,o.height=t),o.width+=l*2,o.height+=i*2,{canvas:o,rotate:n,width:e,height:t,border:s}}getXScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.width/this.config.height,t=this.imageState.width/this.imageState.height;return Math.min(1,e/t)}getYScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.height/this.config.width,t=this.imageState.height/this.imageState.width;return Math.min(1,e/t)}getCroppingRect(e){if(!this.imageState.width||!this.imageState.height)return{x:0,y:0,width:1,height:1};let t=e||{x:this.imageState.x,y:this.imageState.y},n=1/this.config.scale*this.getXScale(),s=1/this.config.scale*this.getYScale(),o={x:t.x-n/2,y:t.y-s/2,width:n,height:s},l=0,i=1-o.width,d=0,m=1-o.height;return(this.config.disableBoundaryChecks||n>1||s>1)&&(l=-o.width,i=1,d=-o.height,m=1),{...o,x:Math.max(l,Math.min(o.x,i)),y:Math.max(d,Math.min(o.y,m))}}getInitialSize(e,t){let n,s,o=this.getDimensions();return o.height/o.width>t/e?(n=o.height,s=n/t*e):(s=o.width,n=s/e*t),{height:n,width:s}}async loadImage(e){let t;if(JL&&e instanceof File)t=await YL(e);else if(typeof e=="string")t=await Ry(e,this.config.crossOrigin);else throw Error("Invalid image source");let n={...this.getInitialSize(t.width,t.height),resource:t,x:.5,y:.5};return this.imageState=n,n}clearImage(){this.imageState=Wh}calculatePosition(e=this.imageState,t){let[n,s]=this.getBorders(t);if(!e.width||!e.height)throw Error("Image dimension is unknown.");let o=this.getCroppingRect(),l=e.width*this.config.scale,i=e.height*this.config.scale,d=-o.x*l,m=-o.y*i;return this.isVertical()?(d+=s,m+=n):(d+=n,m+=s),{x:d,y:m,height:i,width:l}}paint(e){e.save(),e.scale(this.pixelRatio,this.pixelRatio),e.translate(0,0),e.fillStyle="rgba("+this.config.color.slice(0,4).join(",")+")";let t=this.config.borderRadius,n=this.getDimensions(),[s,o]=this.getBorders(n.border),l=n.canvas.height,i=n.canvas.width;t=Math.max(t,0),t=Math.min(t,i/2-s,l/2-o),e.beginPath(),Lh(e,s,o,i-s*2,l-o*2,t),e.rect(i,0,-i,l),e.fill("evenodd"),this.config.borderColor&&(e.strokeStyle="rgba("+this.config.borderColor.slice(0,4).join(",")+")",e.lineWidth=1,e.beginPath(),Lh(e,s+.5,o+.5,i-s*2-1,l-o*2-1,t),e.stroke()),this.config.showGrid&&KL(e,s,o,i-s*2,l-o*2,this.config.gridColor),e.restore()}paintImage(e,t,n,s=this.pixelRatio){if(!t.resource)return;let o=this.calculatePosition(t,n);e.save(),e.translate(e.canvas.width/2,e.canvas.height/2),e.rotate(this.config.rotate*Math.PI/180),e.translate(-(e.canvas.width/2),-(e.canvas.height/2)),this.isVertical()&&e.translate((e.canvas.width-e.canvas.height)/2,(e.canvas.height-e.canvas.width)/2),e.scale(s,s),e.globalCompositeOperation="destination-over",e.drawImage(t.resource,o.x,o.y,o.width,o.height),this.config.backgroundColor&&(e.fillStyle=this.config.backgroundColor,e.fillRect(0,0,e.canvas.width,e.canvas.height)),e.restore()}getImage(){let e=this.getCroppingRect(),t=this.imageState;if(!t.resource)throw Error("No image resource available, please report this to: https://github.com/mosch/react-avatar-editor/issues");e.x*=t.resource.width,e.y*=t.resource.height,e.width*=t.resource.width,e.height*=t.resource.height;let n=document.createElement("canvas");this.isVertical()?(n.width=Math.round(e.height),n.height=Math.round(e.width)):(n.width=Math.round(e.width),n.height=Math.round(e.height));let s=n.getContext("2d");if(!s)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return s.translate(n.width/2,n.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(n.width/2),-(n.height/2)),this.isVertical()&&s.translate((n.width-n.height)/2,(n.height-n.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,n.width,n.height)),s.drawImage(t.resource,-e.x,-e.y),n}getImageScaledToCanvas(){let e=this.getDimensions(),t=this.imageState,n=document.createElement("canvas");if(this.isVertical()?(n.width=e.height,n.height=e.width):(n.width=e.width,n.height=e.height),!t.resource)return n;let s=n.getContext("2d");if(!s)return n;let o=this.calculatePosition(t,0);return s.save(),s.translate(n.width/2,n.height/2),s.rotate(this.config.rotate*Math.PI/180),s.translate(-(n.width/2),-(n.height/2)),this.isVertical()&&s.translate((n.width-n.height)/2,(n.height-n.width)/2),this.config.backgroundColor&&(s.fillStyle=this.config.backgroundColor,s.fillRect(0,0,n.width,n.height)),s.drawImage(t.resource,o.x,o.y,o.width,o.height),s.restore(),n}calculateDragPosition(e,t,n,s){let o=n-e,l=s-t;if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let i=this.imageState.width*this.config.scale,d=this.imageState.height*this.config.scale,{x:m,y}=this.getCroppingRect();m*=i,y*=d;let k=this.config.rotate;k%=360,k=k<0?k+360:k;let S=Math.cos(Bh(k)),h=Math.sin(Bh(k)),g=m+o*S+l*h,v=y+-o*h+l*S,A=1/this.config.scale*this.getXScale(),_=1/this.config.scale*this.getYScale();return{x:g/i+A/2,y:v/d+_/2}}},Fh=()=>{},XL=()=>{let e=!1;try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",Fh,t),window.removeEventListener("test",Fh,t)}catch{e=!1}return e},jy=r.forwardRef((e,t)=>{let{scale:n=1,rotate:s=0,border:o=25,borderRadius:l=0,width:i=200,height:d=200,color:m=[0,0,0,.5],showGrid:y=!1,gridColor:k="#666",disableBoundaryChecks:S=!1,disableHiDPIScaling:h=!1,disableCanvasRotation:g=!0,image:v,position:A,backgroundColor:_,crossOrigin:I,onLoadStart:B,onLoadFailure:V,onLoadSuccess:L,onImageReady:J,onImageChange:me,onMouseUp:ve,onMouseMove:re,onPositionChange:x,borderColor:K,style:ue}=e,pe=r.useRef(null),X=r.useRef(new QL({width:i,height:d,border:o,borderRadius:l,scale:n,rotate:s,color:m,backgroundColor:_,borderColor:K,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:I})),M=r.useRef(!1),O=r.useRef(void 0),de=r.useRef(void 0),[ge,$]=r.useState(!1),[_e,je]=r.useState(!1),[se,ce]=r.useState(X.current.getImageState()),Re=r.useRef(ve);Re.current=ve;let Pe=r.useRef(re);Pe.current=re;let Ce=r.useRef(x);Ce.current=x,r.useEffect(()=>{X.current.updateConfig({width:i,height:d,border:o,borderRadius:l,scale:n,rotate:s,color:m,backgroundColor:_,borderColor:K,showGrid:y,gridColor:k,disableBoundaryChecks:S,disableHiDPIScaling:h,disableCanvasRotation:g,crossOrigin:I})},[i,d,o,l,n,s,m,_,K,y,k,S,h,g,I]);let Ee=r.useCallback(()=>{if(!pe.current)throw Error("No canvas found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return pe.current},[]),U=r.useCallback(()=>{let ie=Ee().getContext("2d");if(!ie)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return ie},[Ee]),T=r.useCallback(async ie=>{je(!0),B?.();try{let ee=await X.current.loadImage(ie);M.current=!1,$(!1),ce(ee),J?.(),L?.(ee)}catch{V?.()}finally{je(!1)}},[B,J,L,V]),b=r.useCallback(()=>{let ie=Ee();U().clearRect(0,0,ie.width,ie.height),X.current.clearImage(),ce(X.current.getImageState())},[Ee,U]),j=r.useCallback(()=>{let ie=U(),ee=Ee();ie.clearRect(0,0,ee.width,ee.height),X.current.paint(ie),X.current.paintImage(ie,se,o)},[U,Ee,se,o,i,d,l,n,s,m,_,K,y,k,S,h,g,I]),D=r.useCallback(ie=>{ie.preventDefault(),M.current=!0,O.current=void 0,de.current=void 0,$(!0)},[]),te=r.useCallback(()=>{M.current=!0,O.current=void 0,de.current=void 0,$(!0)},[]);r.useImperativeHandle(t,()=>({getImage:()=>X.current.getImage(),getImageScaledToCanvas:()=>X.current.getImageScaledToCanvas(),getCroppingRect:()=>X.current.getCroppingRect()}),[]),r.useEffect(()=>{let ie=U();v&&T(v),X.current.paint(ie);let ee=Se=>{if(!M.current)return;Se.cancelable&&Se.preventDefault();let we="targetTouches"in Se?Se.targetTouches[0].pageX:Se.clientX,Te="targetTouches"in Se?Se.targetTouches[0].pageY:Se.clientY,Me=O.current,nt=de.current;if(O.current=we,de.current=Te,Me!==void 0&&nt!==void 0){let gt=X.current.getImageState();if(gt.width&>.height){let lt=X.current.calculateDragPosition(we,Te,Me,nt);Ce.current?.(lt);let St={...gt,...lt};X.current.setImageState(St),ce(St)}}Pe.current?.(Se)},Q=()=>{M.current&&(M.current=!1,$(!1),Re.current?.())},q=XL()?{passive:!1}:!1;return document.addEventListener("mousemove",ee,q),document.addEventListener("mouseup",Q,q),document.addEventListener("touchmove",ee,q),document.addEventListener("touchend",Q,q),()=>{document.removeEventListener("mousemove",ee,!1),document.removeEventListener("mouseup",Q,!1),document.removeEventListener("touchmove",ee,!1),document.removeEventListener("touchend",Q,!1)}},[]),r.useEffect(()=>{v?T(v):!v&&se.x!==.5&&se.y!==.5&&b()},[v,i,d,_]),r.useEffect(()=>{j()},[j]),r.useEffect(()=>{if(!_e)return;let ie=pe.current;if(!ie)return;let ee=ie.getContext("2d");if(!ee)return;let Q,q=performance.now(),Se=we=>{let Te=(we-q)/1e3,Me=.03+Math.sin(Te*2.5)*.02+.02;ee.save(),ee.clearRect(0,0,ie.width,ie.height),ee.fillStyle=`rgba(255,255,255,${Me})`,ee.fillRect(0,0,ie.width,ie.height),ee.restore(),Q=requestAnimationFrame(Se)};return Q=requestAnimationFrame(Se),()=>cancelAnimationFrame(Q)},[_e]);let P=r.useRef({image:v,width:i,height:d,position:A,scale:n,rotate:s,imageX:se.x,imageY:se.y});r.useEffect(()=>{let ie=P.current;(ie.image!==v||ie.width!==i||ie.height!==d||ie.position!==A||ie.scale!==n||ie.rotate!==s||ie.imageX!==se.x||ie.imageY!==se.y)&&(me?.(),P.current={image:v,width:i,height:d,position:A,scale:n,rotate:s,imageX:se.x,imageY:se.y})},[v,i,d,A,n,s,se.x,se.y,me]);let H=X.current.getDimensions(),be=X.current.getPixelRatio(),z={width:H.canvas.width,height:H.canvas.height,cursor:ge?"grabbing":"grab",touchAction:"none",maxWidth:"none",maxHeight:"none"};return Fe.createElement("canvas",{width:H.canvas.width*be,height:H.canvas.height*be,onMouseDown:D,onTouchStart:te,style:{...z,...ue},ref:pe})});jy.displayName="AvatarEditor";const eB="_avatarManagerBody_1bfwv_1",tB="_editorPanel_1bfwv_7",aB="_editorFrame_1bfwv_13",nB="_gifPreviewImage_1bfwv_21",rB="_emptyPreview_1bfwv_28",sB="_controlPanel_1bfwv_41",oB="_zoomField_1bfwv_47",iB="_zoomSlider_1bfwv_52",cB="_actionGrid_1bfwv_57",lB="_fileInput_1bfwv_63",dB="_messageStack_1bfwv_67",Ls={avatarManagerBody:eB,editorPanel:tB,editorFrame:aB,gifPreviewImage:nB,emptyPreview:rB,controlPanel:sB,zoomField:oB,zoomSlider:iB,actionGrid:cB,fileInput:lB,messageStack:dB},bp=512,uB=48,Wu=512;function Oh(e,t,n){return new Promise(s=>{e.toBlob(s,t,n)})}function mB(e,t){const n=String(e).trim()||"avatar",s=n.lastIndexOf(".");return s<=0?`${n}${t}`:`${n.slice(0,s)}${t}`}async function pB(e,t){const n=e.getImageScaledToCanvas(),s=document.createElement("canvas");s.width=Wu,s.height=Wu;const o=s.getContext("2d");if(!o)throw new Error("Image editing requires a 2D canvas context.");o.drawImage(n,0,0,Wu,Wu);const i=await Oh(s,"image/webp",.9)||await Oh(s,"image/jpeg",.9);if(!i)throw new Error("Unable to prepare profile photo.");const d=i.type||"image/jpeg",m=d==="image/webp"?".webp":".jpg";return new File([i],mB(t,m),{type:d,lastModified:Date.now()})}function fB({isOpen:e,theme:t,title:n="Edit Photo",currentImageUrl:s,editorImageUrl:o="",fallbackInitial:l,accept:i,busy:d,hasPendingImage:m,canRemove:y,error:k,notice:S,onClose:h,onApplyImage:g,onRemoveImage:v,onDiscardPendingImage:A}){const _=r.useRef(null),I=r.useRef(null),[B,V]=r.useState(null),[L,J]=r.useState(""),[me,ve]=r.useState(1.1),[re,x]=r.useState(null),[K,ue]=r.useState(null);r.useEffect(()=>{e||(V(null),J(""),ve(1.1),x(null),ue(null))},[e]),r.useEffect(()=>{if(!B){J("");return}const se=URL.createObjectURL(B);return J(se),()=>URL.revokeObjectURL(se)},[B]);const pe=L||o||s,X=B?.name||"avatar",M=String(l||"").trim().charAt(0).toUpperCase(),O=re||k,de=K||S,ge=r.useCallback(se=>{if(x(null),ue(null),!!se){if(!se.type.startsWith("image/")){x("Profile photo must be an image file.");return}se.type==="image/gif"&&ue("Animated GIFs will upload without repositioning."),V(se),ve(1.1)}},[]),$=r.useCallback(async()=>{x(null);const se=_.current;if(B?.type==="image/gif"){await g(B)&&h();return}if(!se||!pe){x("Choose a profile photo first.");return}try{const ce=await pB(se,X);await g(ce,B)&&h()}catch(ce){x(ce instanceof Error?ce.message:"Unable to prepare profile photo.")}},[pe,g,h,B,X]),_e=B?.type==="image/gif"||!!pe,je=r.useMemo(()=>a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.secondaryButton,onClick:h,disabled:d,children:"Cancel"}),a.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:()=>{$()},disabled:d||!_e,children:d?"Applying...":"Apply Photo"})]}),[d,_e,$,h]);return a.jsx(Ws,{isOpen:e,onClose:h,title:n,size:"md",theme:t,draggable:!0,footer:je,children:a.jsxs("div",{className:Ls.avatarManagerBody,children:[a.jsxs("div",{className:Ls.editorPanel,children:[a.jsx("div",{className:`tf-surface-inset ${Ls.editorFrame}`,children:B?.type==="image/gif"&&L?a.jsx("img",{src:L,alt:"",className:Ls.gifPreviewImage}):pe?a.jsx(jy,{ref:_,image:pe,width:bp,height:bp,border:uB,borderRadius:bp/2,scale:me,color:[15,15,26,.72],backgroundColor:"transparent",style:{width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",display:"block",borderRadius:"var(--radius-lg)",boxShadow:"var(--box-shadow-sm)"},disableCanvasRotation:!0}):a.jsx("div",{className:Ls.emptyPreview,"aria-hidden":"true",children:M})}),a.jsxs("div",{className:Ls.controlPanel,children:[a.jsx("input",{ref:I,type:"file","aria-label":"Choose profile photo",accept:i,className:Ls.fileInput,onChange:se=>ge(se.target.files?.[0]||null),disabled:d}),a.jsxs("div",{className:Ls.actionGrid,children:[a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>I.current?.click(),disabled:d,children:[a.jsx(Lk,{size:16}),"Choose"]}),m&&A&&a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:A,disabled:d,children:[a.jsx(kd,{size:16}),"Discard"]}),y&&v&&a.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:v,disabled:d,children:[a.jsx(gm,{size:16}),"Remove"]})]}),a.jsxs("label",{className:`tf-field-stack ${Ls.zoomField}`,children:[a.jsx("span",{className:"tf-field-label",children:"Zoom"}),a.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:me,onChange:se=>ve(Number(se.target.value)),className:Ls.zoomSlider,disabled:d||!pe||B?.type==="image/gif"})]})]})]}),(O||de)&&a.jsxs("div",{className:Ls.messageStack,children:[O&&a.jsx("p",{className:"tf-text-error",children:O}),de&&!O&&a.jsx("p",{className:"tf-text-helper",children:de})]})]})})}const hB="_editableAvatarButton_1ga39_1",gB="_editableAvatarImage_1ga39_47",yB="_editableAvatarFallback_1ga39_54",kB="_editableAvatarBadge_1ga39_65",Fu={editableAvatarButton:hB,editableAvatarImage:gB,editableAvatarFallback:yB,editableAvatarBadge:kB};function vB({label:e,imageUrl:t,fallback:n,accentColor:s,size:o=52,width:l,height:i,radius:d,editBadgeSize:m,editIconSize:y=16,disabled:k=!1,className:S="",onClick:h}){const g=String(t||"").trim(),v=l??o,A=i??o,_=typeof d=="number"?`${d}px`:d,I=typeof m=="number"?`${m}px`:m;return a.jsxs("button",{type:"button",className:`${Fu.editableAvatarButton} ${S}`.trim(),"aria-label":e,title:e,onClick:h,disabled:k,style:{"--editable-avatar-size":`${o}px`,"--editable-avatar-width":`${v}px`,"--editable-avatar-height":`${A}px`,..._?{"--editable-avatar-radius":_}:{},...I?{"--editable-avatar-badge-size":I}:{},...s?{"--editable-avatar-accent":s}:{}},children:[g?a.jsx("img",{src:g,alt:"",className:Fu.editableAvatarImage}):a.jsx("span",{className:Fu.editableAvatarFallback,children:n}),a.jsx("span",{className:Fu.editableAvatarBadge,"aria-hidden":"true",children:a.jsx(Bk,{size:y})})]})}function SB({isOpen:e,theme:t,onClose:n,onSave:s,displayName:o,email:l,avatarDisplayUrl:i,accountBadgeInitial:d,saveBusy:m,avatarBusy:y,saveError:k,saveNotice:S,onDisplayNameChange:h,onOpenAvatarManager:g}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"Edit Profile",size:"sm",theme:t,draggable:!0,footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:p.secondaryButton,onClick:n,disabled:m||y,children:"Cancel"}),a.jsx("button",{type:"button",className:p.primaryUpdateBtn,onClick:s,disabled:m||y||!o.trim(),children:m?"Saving...":"Save Profile"})]}),children:a.jsxs("div",{className:`${xt.form} ${mt.modalBody}`,children:[a.jsxs("div",{className:ft.profileEditLayout,children:[a.jsx("div",{className:ft.profileAvatarEditor,children:a.jsx(vB,{label:"Edit profile photo",imageUrl:i,fallback:d,disabled:m||y,onClick:g})}),a.jsxs("div",{className:ft.profileFieldStack,children:[a.jsxs("label",{className:ft.profileFieldLabel,children:[a.jsx("span",{children:"Display name"}),a.jsx("input",{className:p.input,type:"text",value:o,onChange:v=>h(v.target.value),placeholder:"Display name",disabled:m})]}),a.jsxs("label",{className:ft.profileFieldLabel,children:[a.jsx("span",{children:"Email"}),a.jsx("input",{className:p.input,type:"email",value:l,readOnly:!0,disabled:!0})]})]})]}),k&&a.jsx("p",{className:`${fe.loginError} ${mt.errorText}`,children:k}),S&&!k&&a.jsx("p",{className:mt.errorText,children:S})]})})}const qp="support@taskforcehq.ai";function Ou(e){return String(e||"").trim()}function wB(e={}){const t=Ou(e.workspaceName),n=Ou(e.workspaceId),s=Ou(e.accountLabel),o=Ou(e.runtimeMode),l=[t?`Workspace: ${t}`:"",n?`Workspace ID: ${n}`:"",s?`Account: ${s}`:"",o?`Runtime: ${o}`:""].filter(Boolean),i=["Hi Taskforce team,","","I need help with:","",l.length>0?"Context:":"",...l,(l.length>0,""),"What happened:",""].filter((m,y,k)=>m!==""||k[y-1]!==""),d=new URLSearchParams({subject:"Taskforce support request",body:i.join(`
|
|
4
|
+
`)});return`mailto:${qp}?${d.toString()}`}function bB({isOpen:e,theme:t,onClose:n,onOpenSettings:s,onOpenAccountHub:o,supportMailtoHref:l}){const[i,d]=r.useState("idle"),m=async()=>{try{await navigator.clipboard.writeText(qp),d("copied"),window.setTimeout(()=>d("idle"),1600)}catch{d("failed"),window.setTimeout(()=>d("idle"),2200)}};return a.jsx(Ws,{isOpen:e,onClose:n,title:"Help & Support",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${xt.form} ${mt.modalBody}`,children:[a.jsxs("div",{className:mt.helpIntro,children:[a.jsx("p",{className:"tf-text-body",children:"Need a hand with Taskforce? Send us what you were trying to do, what happened, and any workspace context that would help us reproduce it."}),a.jsxs("div",{className:mt.supportEmailRow,children:[a.jsx("code",{className:mt.supportEmailAddress,children:qp}),a.jsxs("button",{className:`${p.submitBtn} ${mt.supportEmailBtn}`,onClick:()=>{m()},type:"button",children:[i==="copied"?a.jsx(eo,{size:16}):a.jsx(Qp,{size:16}),i==="copied"?"Copied":i==="failed"?"Copy Failed":"Copy Email"]})]}),a.jsxs("a",{className:`${p.cancelBtn} ${mt.supportEmailBtn}`,href:l,children:[a.jsx(ug,{size:16}),"Open Email App"]})]}),a.jsxs("div",{className:`${mt.supportPanel} tf-surface-panel`,children:[a.jsxs("div",{className:mt.supportPanelHeader,children:[a.jsx(Wk,{size:16}),a.jsxs("div",{children:[a.jsx("h3",{className:"tf-heading-card",children:"Before you email"}),a.jsx("p",{className:"tf-text-secondary",children:"These are the fastest places to check for common workspace, account, and setup issues."})]})]}),a.jsxs("div",{className:mt.supportRouteList,children:[a.jsxs("button",{className:`${p.cancelBtn} ${mt.supportRouteBtn}`,onClick:s,children:[a.jsx(Xp,{size:15}),"Open Settings"]}),o&&a.jsxs("button",{className:`${p.cancelBtn} ${mt.supportRouteBtn}`,onClick:o,children:[a.jsx(Fk,{size:15}),"Open Account Hub"]})]})]}),a.jsx("div",{className:`${xt.formActions} ${mt.modalActionsEnd}`,children:a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Close"})})]})})}function _B({prompt:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:!!e,onClose:n,title:"Date Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&a.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),a.jsxs("div",{className:p.formActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:s,children:"Save Anyway"})]})]})})}function CB({isOpen:e,theme:t,onClose:n,onConfirm:s}){return a.jsx(Ws,{isOpen:e,onClose:n,title:"Cloud Sync Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${p.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Turning on cloud sync can renumber task, document, and image references to match the cloud workspace."}),a.jsxs("p",{className:"tf-text-helper",children:["Labels like ",a.jsx("code",{children:"T-12"}),", ",a.jsx("code",{children:"D-4"}),", and ",a.jsx("code",{children:"IMG-2"})," may change. Plain file attachments are not renumbered."]}),a.jsxs("div",{className:p.formActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:n,children:"Go Back"}),a.jsx("button",{className:p.submitBtn,onClick:s,children:"Enable Sync Anyway"})]})]})})}const AB="_syncStatusModal_4pd1g_1",xB="_syncStatusTop_4pd1g_6",IB="_syncStatusMetaHeader_4pd1g_15",TB="_syncStatusHeaderInfo_4pd1g_22",RB="_syncToggle_4pd1g_43",jB="_syncStatusBadge_4pd1g_47",NB="_syncToggleControl_4pd1g_75",PB="_syncToggleControlEnabled_4pd1g_91",MB="_syncToggleControlDisabled_4pd1g_98",EB="_syncToggleControlBusy_4pd1g_102",DB="_syncToggleControlBlocked_4pd1g_107",LB="_syncToggleInput_4pd1g_112",BB="_syncToggleState_4pd1g_125",WB="_syncToggleStateOn_4pd1g_136",FB="_syncToggleStateOff_4pd1g_141",OB="_syncToggleThumb_4pd1g_146",$B="_syncStatusSummaryValue_4pd1g_173",UB="_syncStatusSummaryCompact_4pd1g_180",zB="_syncStatusRepairBanner_4pd1g_190",HB="_syncStatusRepairHeader_4pd1g_200",GB="_syncStatusRepairBadge_4pd1g_207",VB="_syncStatusRepairMeta_4pd1g_216",qB="_syncStatusRepairText_4pd1g_223",KB="_syncStatusLabel_4pd1g_257",ZB="_syncStatusSectionHeader_4pd1g_265",YB="_syncStatusCompactGrid_4pd1g_278",JB="_syncStatusCompactItem_4pd1g_284",QB="_syncStatusValue_4pd1g_295",XB="_syncStatusValueError_4pd1g_325",eW="_syncStatusActions_4pd1g_329",tW="_syncStatusPanel_4pd1g_336",aW="_syncStatusPanelHeader_4pd1g_346",nW="_syncStatusPanelMeta_4pd1g_353",rW="_syncStatusEventsList_4pd1g_375",sW="_syncStatusEventItem_4pd1g_384",oW="_syncStatusEventItemError_4pd1g_391",iW="_syncStatusEventItemMuted_4pd1g_396",cW="_syncStatusEventLine_4pd1g_401",lW="_syncStatusSecondaryActions_4pd1g_411",dW="_syncStatusPrimaryActions_4pd1g_425",uW="_syncStatusPrimaryActionSlot_4pd1g_432",mW="_syncStatusActionPlaceholder_4pd1g_440",rt={syncStatusModal:AB,syncStatusTop:xB,syncStatusMetaHeader:IB,syncStatusHeaderInfo:TB,syncToggle:RB,syncStatusBadge:jB,syncToggleControl:NB,syncToggleControlEnabled:PB,syncToggleControlDisabled:MB,syncToggleControlBusy:EB,syncToggleControlBlocked:DB,syncToggleInput:LB,syncToggleState:BB,syncToggleStateOn:WB,syncToggleStateOff:FB,syncToggleThumb:OB,syncStatusSummaryValue:$B,syncStatusSummaryCompact:UB,syncStatusRepairBanner:zB,syncStatusRepairHeader:HB,syncStatusRepairBadge:GB,syncStatusRepairMeta:VB,syncStatusRepairText:qB,syncStatusLabel:KB,syncStatusSectionHeader:ZB,syncStatusCompactGrid:YB,syncStatusCompactItem:JB,syncStatusValue:QB,syncStatusValueError:XB,syncStatusActions:eW,syncStatusPanel:tW,syncStatusPanelHeader:aW,syncStatusPanelMeta:nW,syncStatusEventsList:rW,syncStatusEventItem:sW,syncStatusEventItemError:oW,syncStatusEventItemMuted:iW,syncStatusEventLine:cW,syncStatusSecondaryActions:lW,syncStatusPrimaryActions:dW,syncStatusPrimaryActionSlot:uW,syncStatusActionPlaceholder:mW};function pW({isOpen:e,theme:t,currentWorkspaceLabel:n,syncStatusMeta:s,workspaceCloudSyncEnabled:o,syncControlBusy:l,canManageWorkspaceSync:i,workspaceSyncSummary:d,workspaceSyncRecommendedAction:m,workspaceSyncRepairBusy:y,referenceMismatchCount:k,syncStageLabel:S,workspaceSyncPendingChanges:h,formattedLastSyncTime:g,formattedLastPullTime:v,formattedLastPushTime:A,syncLastError:_,workspaceSyncDiagnostics:I,activeReferenceMismatchSummaries:B,syncDiagnosticsSummary:V,syncEventRows:L,syncEventsListRef:J,workspaceSyncRepairQueued:me,workspaceSyncBusy:ve,workspaceSyncCopied:re,runtimeMode:x,isAuthenticated:K,onClose:ue,onToggleWorkspaceSync:pe,onRepairSync:X,onCopyReport:M,onOpenLogin:O,onRetrySync:de}){return a.jsx(Ws,{isOpen:e,onClose:ue,title:"Sync Manager",size:"mdWide",theme:t,draggable:!0,children:a.jsxs("div",{className:`${xt.form} ${rt.syncStatusModal}`,style:{gap:"10px"},children:[a.jsxs("div",{className:rt.syncStatusTop,children:[a.jsx("div",{className:rt.syncStatusHeaderInfo,children:a.jsxs("div",{className:rt.syncStatusMetaHeader,children:[a.jsx("div",{className:rt.syncStatusBadge,style:{borderColor:s.border,background:s.background,color:s.color},children:s.label}),a.jsxs("span",{className:rt.syncStatusLabel,children:["Workspace: ",a.jsx("code",{children:n})]})]})}),a.jsx("label",{className:rt.syncToggle,children:a.jsxs("span",{className:[rt.syncToggleControl,o?rt.syncToggleControlEnabled:rt.syncToggleControlDisabled,l?rt.syncToggleControlBusy:"",i?"":rt.syncToggleControlBlocked].filter(Boolean).join(" "),children:[a.jsx("input",{className:rt.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:o,disabled:!i||l,onChange:ge=>pe(ge.target.checked)}),a.jsx("span",{className:`${rt.syncToggleState} ${rt.syncToggleStateOn}`,children:"On"}),a.jsx("span",{className:`${rt.syncToggleState} ${rt.syncToggleStateOff}`,children:"Off"}),a.jsx("span",{className:rt.syncToggleThumb})]})})]}),a.jsxs("div",{className:rt.syncStatusSummaryCompact,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Health"}),a.jsx("span",{className:rt.syncStatusSummaryValue,children:d})]}),a.jsxs("div",{className:rt.syncStatusSummaryCompact,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Next Step"}),a.jsx("span",{className:rt.syncStatusSummaryValue,children:m})]}),y&&a.jsxs("div",{className:rt.syncStatusRepairBanner,children:[a.jsxs("div",{className:rt.syncStatusRepairHeader,children:[a.jsxs("div",{className:rt.syncStatusRepairBadge,children:[a.jsx(pr,{size:13,className:p.spinner}),a.jsx("span",{children:"Repair In Progress"})]}),a.jsx("span",{className:rt.syncStatusRepairMeta,children:"Advanced recovery mode"})]}),a.jsx("span",{className:rt.syncStatusRepairText,children:k>0?`Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again, including ${k} detected reference mismatch${k===1?"":"es"}. The panel may stay busy for a while during large repairs.`:"Taskforce is clearing the saved sync cursor and reconciling workspace state from the cloud again. The panel may stay busy for a while during large repairs."})]}),a.jsx("div",{className:rt.syncStatusSectionHeader,children:a.jsx("span",{className:rt.syncStatusLabel,children:"Current Session"})}),a.jsxs("div",{className:rt.syncStatusCompactGrid,children:[a.jsxs("div",{className:rt.syncStatusCompactItem,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Stage"}),a.jsx("span",{className:rt.syncStatusValue,children:S})]}),a.jsxs("div",{className:rt.syncStatusCompactItem,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Local Changes"}),a.jsx("span",{className:rt.syncStatusValue,children:h})]}),a.jsxs("div",{className:rt.syncStatusCompactItem,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Last Successful"}),a.jsx("span",{className:rt.syncStatusValue,children:g})]})]}),a.jsx("div",{className:rt.syncStatusSectionHeader,children:a.jsx("span",{className:rt.syncStatusLabel,children:"Activity"})}),a.jsxs("div",{className:rt.syncStatusCompactGrid,children:[a.jsxs("div",{className:rt.syncStatusCompactItem,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Last Pull"}),a.jsx("span",{className:rt.syncStatusValue,children:v})]}),a.jsxs("div",{className:rt.syncStatusCompactItem,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Last Push"}),a.jsx("span",{className:rt.syncStatusValue,children:A})]})]}),_!=="None"&&a.jsxs("div",{className:rt.syncStatusPanel,style:{background:"rgba(239, 68, 68, 0.05)",borderColor:"rgba(239, 68, 68, 0.2)"},children:[a.jsxs("div",{className:rt.syncStatusSectionHeader,style:{marginTop:0},children:[a.jsx(vd,{size:12,color:"#fda4af"}),a.jsxs("span",{className:rt.syncStatusLabel,style:{color:"#fda4af"},children:["Last Error (",I.lastErrorAt?new Date(I.lastErrorAt).toLocaleTimeString():"Recent",")"]})]}),a.jsx("span",{className:`${rt.syncStatusValue} ${rt.syncStatusValueError}`,children:_})]}),k>0&&a.jsxs("div",{className:rt.syncStatusPanel,style:{background:"rgba(250, 204, 21, 0.08)",borderColor:"rgba(250, 204, 21, 0.22)"},children:[a.jsxs("div",{className:rt.syncStatusPanelHeader,children:[a.jsx("span",{className:rt.syncStatusLabel,style:{color:"#fde68a"},children:"Identifier Integrity"}),a.jsxs("span",{className:rt.syncStatusPanelMeta,children:[k," mismatch",k===1?"":"es"," detected"]})]}),a.jsx("span",{className:rt.syncStatusValue,children:"Task, document, or image reference numbers disagreed during normal sync. Cloud-backed sync preserves the incoming cloud reference and renumbers the displaced local item to the next available reference."}),B.length>0&&a.jsx("div",{style:{marginTop:"10px",display:"flex",flexDirection:"column",gap:"8px"},children:B.map(ge=>a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",padding:"8px 10px",borderRadius:"8px",background:"rgba(15, 23, 42, 0.18)",border:"1px solid rgba(250, 204, 21, 0.16)"},children:[a.jsx("span",{className:rt.syncStatusValue,style:{fontSize:"12px",wordBreak:"break-all"},children:ge.pathLabel}),ge.refsLabel?a.jsx("span",{className:rt.syncStatusPanelMeta,children:ge.refsLabel}):null]},ge.key))})]}),a.jsxs("div",{className:rt.syncStatusPanel,children:[a.jsxs("div",{className:rt.syncStatusPanelHeader,children:[a.jsx("span",{className:rt.syncStatusLabel,children:"Local Sync Diagnostics"}),a.jsx("span",{className:rt.syncStatusPanelMeta,style:{fontSize:"10px"},children:"AI profiles & metadata"})]}),a.jsx("div",{className:rt.syncStatusCompactGrid,style:{gridTemplateColumns:"repeat(2, 1fr)"},children:V.map(ge=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"8px"},children:[a.jsx("span",{className:rt.syncStatusLabel,style:{fontSize:"9px",textTransform:"capitalize"},children:ge.label}),a.jsx("span",{className:rt.syncStatusValue,style:{fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:ge.value})]},ge.label))})]}),a.jsxs("div",{className:rt.syncStatusPanel,children:[a.jsx("div",{className:rt.syncStatusPanelHeader,children:a.jsx("span",{className:rt.syncStatusLabel,children:"Recent Events"})}),a.jsx("div",{ref:J,className:rt.syncStatusEventsList,style:{height:"120px"},children:L.map(ge=>a.jsx("div",{className:[rt.syncStatusEventItem,ge.tone==="error"?rt.syncStatusEventItemError:"",ge.tone==="muted"?rt.syncStatusEventItemMuted:""].filter(Boolean).join(" "),style:{padding:"6px 8px",borderRadius:"6px"},children:a.jsx("span",{className:rt.syncStatusEventLine,style:{fontSize:"11px"},children:ge.text})},ge.key))})]}),a.jsxs("div",{className:`${xt.formActions} ${rt.syncStatusActions}`,children:[a.jsxs("div",{className:rt.syncStatusSecondaryActions,children:[a.jsx("button",{className:p.cancelBtn,onClick:X,disabled:y,title:y?"Repair is running now.":me?"Repair is queued and will start when the current sync finishes.":ve?"Queue a repair to start automatically when the current sync finishes.":"Advanced recovery: clear the saved pull cursor and re-fetch cloud state from the beginning.",children:y?a.jsxs(a.Fragment,{children:[a.jsx(pr,{size:14,className:p.spinner}),a.jsx("span",{style:{marginLeft:"6px"},children:"Repairing..."})]}):me?"Repair Queued":"Repair"}),a.jsxs("button",{className:p.cancelBtn,onClick:M,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[a.jsx(Qp,{size:14}),a.jsx("span",{style:{marginLeft:"6px"},children:re?"Copied":"Copy Report"})]})]}),a.jsxs("div",{className:rt.syncStatusPrimaryActions,children:[a.jsx("div",{className:rt.syncStatusPrimaryActionSlot,children:x==="local"&&!K?a.jsx("button",{className:p.submitBtn,onClick:O,children:"Sign In / Register"}):a.jsx("div",{className:rt.syncStatusActionPlaceholder,"aria-hidden":"true"})}),a.jsx("div",{className:rt.syncStatusPrimaryActionSlot,children:a.jsx("button",{className:p.submitBtn,onClick:de,disabled:ve,children:ve?a.jsxs(a.Fragment,{children:[a.jsx(pr,{size:14,className:p.spinner}),"Syncing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Ok,{size:14}),"Sync"]})})})]})]})]})})}function fW({isOpen:e,theme:t,teamPlanMode:n,teamMgmtError:s,teamManagementTab:o,teamUsersLoading:l,teamUsers:i,teamActionBusyUserId:d,teamInviteFeedback:m,teamInviteEmail:y,teamInviteRole:k,teamInvitePermissionMode:S,teamInviteBusy:h,pendingInvites:g,teamAuditLoading:v,teamAuditEvents:A,teamAuditPage:_,teamAuditPages:I,teamAuditHasMore:B,onClose:V,onOpenMembersTab:L,onOpenInvitesTab:J,onOpenAuditTab:me,onMemberRoleChange:ve,onMemberPermissionChange:re,onToggleMemberDisabled:x,onRevokeInvite:K,onRemoveMember:ue,onInviteEmailChange:pe,onInviteRoleChange:X,onInvitePermissionModeChange:M,onSubmitInvite:O,onLoadAuditPrevious:de,onLoadAuditNext:ge}){return a.jsx(Ws,{isOpen:e,onClose:V,title:"Team Management",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${xt.form} ${mt.modalBody}`,children:[n==="personal"&&a.jsx("p",{className:fe.loginError,children:"Team management is only available in TEAM accounts."}),s&&a.jsx("p",{className:fe.loginError,children:s}),a.jsxs("div",{className:`${p.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[a.jsx("button",{className:`${p.settingsTabBtn} ${o==="members"?p.settingsTabBtnActive:""}`,onClick:L,children:"Members"}),a.jsx("button",{className:`${p.settingsTabBtn} ${o==="invites"?p.settingsTabBtnActive:""}`,onClick:J,children:"Invites"}),a.jsx("button",{className:`${p.settingsTabBtn} ${o==="audit"?p.settingsTabBtnActive:""}`,onClick:me,children:"Audit Log"})]}),o==="members"&&a.jsxs("div",{className:ft.accountHubCard,children:[l&&a.jsx("p",{className:mt.mutedText,children:"Loading members..."}),!l&&i.length===0&&a.jsx("p",{className:mt.mutedText,children:"No users found."}),!l&&i.map($=>a.jsxs("div",{className:mt.memberRow,children:[a.jsx("div",{className:mt.memberTitle,children:$.displayName||$.email}),a.jsxs("div",{className:ft.accountMenuMeta,children:[$.email," · ",$.status,$.disabled?" · deactivated":""]}),a.jsxs("div",{className:mt.memberActions,children:[a.jsxs("select",{className:`${p.input} ${mt.selectRole}`,value:$.role,onChange:_e=>ve($.userId,_e.target.value),disabled:d===$.userId,children:[a.jsx("option",{value:"owner",children:"Owner"}),a.jsx("option",{value:"admin",children:"Admin"}),a.jsx("option",{value:"member",children:"Member"})]}),$.role==="member"&&a.jsxs("select",{className:`${p.input} ${mt.selectPermission}`,value:$.permissionMode,onChange:_e=>re($.userId,_e.target.value),disabled:d===$.userId,children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:p.cancelBtn,disabled:d===$.userId,onClick:()=>x($.userId,!$.disabled),children:$.disabled?"Reactivate":"Deactivate"}),$.status==="invited"&&a.jsx("button",{className:p.cancelBtn,disabled:d===$.userId,onClick:()=>K($.userId),children:"Revoke Invite"}),a.jsx("button",{className:p.cancelBtn,disabled:d===$.userId,onClick:()=>ue($.userId),children:"Remove"})]})]},$.userId))]}),o==="invites"&&a.jsxs("div",{className:ft.accountHubCard,children:[m&&a.jsx("p",{className:mt.sectionText,children:m}),a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("label",{className:`${p.label} ${mt.labelFixed}`,children:"Email"}),a.jsx("input",{className:p.input,value:y,onChange:$=>pe($.target.value),placeholder:"name@company.com"})]}),a.jsxs("div",{className:p.pathInputGroup,children:[a.jsx("label",{className:`${p.label} ${mt.labelFixed}`,children:"Role"}),a.jsxs("select",{className:`${p.input} ${mt.selectRole}`,value:k,onChange:$=>X($.target.value==="admin"?"admin":"member"),children:[a.jsx("option",{value:"member",children:"Member"}),a.jsx("option",{value:"admin",children:"Admin"})]}),k==="member"&&a.jsxs("select",{className:`${p.input} ${mt.selectPermission}`,value:S,onChange:$=>M($.target.value==="read-only"?"read-only":"read-write"),children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:p.submitBtn,disabled:h||!y.trim()||n!=="team",onClick:O,children:h?"Sending...":"Send Invite"})]}),a.jsxs("div",{className:mt.inviteRow,children:[a.jsx("div",{className:mt.listHeading,children:"Pending Invites"}),g.length===0&&a.jsx("p",{className:mt.mutedText,children:"No pending invites."}),g.map($=>a.jsxs("div",{className:mt.memberRow,children:[a.jsx("div",{className:mt.memberTitle,children:$.displayName||$.email}),a.jsxs("div",{className:ft.accountMenuMeta,children:[$.email," · ",$.role]})]},$.userId))]})]}),o==="audit"&&a.jsxs("div",{className:ft.accountHubCard,children:[v&&a.jsx("p",{className:mt.mutedText,children:"Loading audit entries..."}),!v&&A.length===0&&a.jsx("p",{className:mt.mutedText,children:"No audit events for this workspace."}),!v&&a.jsx("div",{className:mt.auditList,children:A.map($=>a.jsxs("div",{className:mt.memberRow,children:[a.jsx("div",{className:ft.accountMenuMeta,children:new Date($.createdAt).toLocaleString()}),a.jsx("div",{className:mt.memberTitle,children:$.action}),a.jsxs("div",{className:ft.accountMenuMeta,children:[$.actorUserId," (",$.actorRole,")"]})]},$.id))}),a.jsxs("div",{className:mt.auditPager,children:[a.jsx("button",{className:p.cancelBtn,disabled:v||_===0,onClick:de,children:"Previous"}),a.jsxs("span",{className:ft.accountMenuMeta,children:["Page ",_+1," of ",I]}),a.jsx("button",{className:p.cancelBtn,disabled:v||!B||_+1>=I,onClick:ge,children:"Next"})]})]}),a.jsx("div",{className:`${xt.formActions} ${mt.modalActionsEnd}`,children:a.jsx("button",{className:p.cancelBtn,onClick:V,children:"Close"})})]})})}const Ny=e=>{const t=e.status||"task";return t==="done"||t==="cancelled"?"completed":t},hW=(e,t,n)=>{if(Ny(e)===t)return null;const o={status:t};return t==="task"||t==="on-hold"?(o.inProgress=!1,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="in-progress"?(o.inProgress=!0,o.readyForReview=!1,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="review"?(o.inProgress=!1,o.readyForReview=!0,o.completed=!1,o.cancelled=!1,o.completedAt=null,o):t==="done"||t==="completed"?(o.status="done",o.inProgress=!1,o.readyForReview=!1,o.completed=!0,o.cancelled=!1,o.completedAt=n,o):(t==="cancelled"&&(o.status="cancelled"),o)},gW=({targetTasks:e,overTaskId:t,isBelowOverItem:n})=>{if(!t)return e.length;const s=e.findIndex(o=>o.id===t);return s<0?e.length:s+(n?1:0)},Py=(e,t=new Map)=>{const n=new Map(t);return e.forEach((s,o)=>{n.set(s.id,{...n.get(s.id)||{},orderInDay:o})}),n},_f=e=>Array.from(e.entries()).map(([t,n])=>({taskId:t,updates:n})),My=({sourceColumnId:e,targetColumnId:t,sourceTasks:n,updates:s})=>!e||e===t?s:Py(n,s),yW=({activeTask:e,sourceColumnId:t,targetTasks:n,sourceTasks:s,insertAt:o})=>{const l=[...n];l.splice(o,0,e);let i=new Map;return l.forEach((d,m)=>{if(d.id===e.id){i.set(d.id,{...i.get(d.id)||{},...e.scheduledDate?{scheduledDate:null,scheduledWeekKey:null}:{},orderInDay:m});return}i.set(d.id,{...i.get(d.id)||{},orderInDay:m})}),i=My({sourceColumnId:t,targetColumnId:"backlog",sourceTasks:s,updates:i}),_f(i)},kW=({activeTask:e,targetTasks:t,insertAt:n})=>{const s=[...t];return s.splice(n,0,e),_f(Py(s))},vW=({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,insertAt:l,scheduledDate:i,scheduledWeekKey:d})=>{const m=[...s];m.splice(l,0,e);let y=new Map;return m.forEach((k,S)=>{if(k.id===e.id){y.set(k.id,{...y.get(k.id)||{},scheduledDate:i,scheduledWeekKey:d,orderInDay:S});return}y.set(k.id,{...y.get(k.id)||{},orderInDay:S})}),y=My({sourceColumnId:t,targetColumnId:n,sourceTasks:o,updates:y}),_f(y)},SW=({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,overTaskId:l,isBelowOverItem:i,scheduleDates:d,parseToIsoWeekKey:m,todayDate:y})=>{const k=["mon","tue","wed","thu","fri","sat","sun"];if(!(n==="backlog"||n==="expired"||k.includes(n)))return null;const h=gW({targetTasks:s,overTaskId:l,isBelowOverItem:i});if(n==="expired")return t!=="expired"?null:{kind:"updates",updates:kW({activeTask:e,targetTasks:s,insertAt:h})};if(n==="backlog")return{kind:"updates",updates:yW({activeTask:e,sourceColumnId:t,targetTasks:s,sourceTasks:o,insertAt:h})};if(!k.includes(n))return null;const g=d[n];return g?!(e.status==="done"||e.status==="cancelled")&&g<y?{kind:"blocked",reason:"Only completed work can be scheduled in the past."}:{kind:"updates",updates:vW({activeTask:e,sourceColumnId:t,targetColumnId:n,targetTasks:s,sourceTasks:o,insertAt:h,scheduledDate:g,scheduledWeekKey:m(g)}),selectedDate:g}:null},Vu="expired::";function wW({tasks:e,columns:t,groupBy:n,searchQuery:s,copiedId:o,taxonomies:l,types:i,priorities:d,approaches:m,assigneeOptions:y=[],onUpdateTask:k,onTaskClick:S,onOpenTaskById:h,onCopyId:g,onToggleInProgress:v,onToggleReview:A,onToggleComplete:_,onToggleCancel:I,onSetStatus:B,onArchiveTask:V,onUnarchive:L,onDelete:J,allTasks:me=[],onAddTaskToColumn:ve,emptyColumnMode:re="show",filterCategories:x=[],filterTypes:K=[],filterPriorities:ue=[],filterStatus:pe=[],filterAssignees:X=[],filtersReady:M=!0,scheduleFilteredTaskIds:O,categories:de=[],compressed:ge=!1,readOnlyMode:$=null,recentlyChangedTaskIds:_e=[],scheduleDates:je,onScheduleDaySelected:se,persistedScrollLeft:ce,onScrollLeftChange:Re,sortBy:Pe="created",sortOrder:Ce="desc",planningDropTargets:Ee=null,onAssignTaskToWorkstream:U,onAssignWorkstreamToInitiative:T,showTaskCardStatusLabel:b=!0,workstreams:j=[],initiatives:D=[]}){const[te,P]=r.useState(null),[H,be]=r.useState(!1),[z,ie]=r.useState(!1),ee=r.useMemo(()=>new Set(_e),[_e]),Q=r.useMemo(()=>new Map(j.map(E=>[E.id,E])),[j]),q=r.useMemo(()=>new Map(D.map(E=>[E.id,E])),[D]),Se=r.useCallback(E=>{const c=E.workstreamId&&Q.get(E.workstreamId)||null,Y=c?.initiativeId&&q.get(c.initiativeId)||null;return{taskWorkstream:c,taskInitiative:Y}},[q,Q]),we=r.useMemo(()=>new Set(e.map(E=>E.id)),[e]),Te=r.useCallback(E=>E.startsWith(Vu)?E.slice(Vu.length):E,[]),Me=r.useCallback(E=>we.has(Te(E)),[we,Te]),nt=r.useMemo(()=>new Set(O||[]),[O]),gt=r.useRef(null),lt=r.useCallback(E=>{const c=E?.data?.current||{},Y=String(E?.id||"");let ye=String(c.taskId||""),Ie=String(c.workstreamId||"");!ye&&Y&&Me(Y)&&(ye=Te(Y)),!Ie&&Y.startsWith("planning-workstream:")&&(Ie=Y.slice(20));let He=String(c.type||"");return He||(ye?He="task-card":Ie&&(He="planning-workstream")),{activeId:Y,type:He,taskId:ye,workstreamId:Ie}},[Te,Me]),St=hg(Mp(vg,{activationConstraint:{distance:10}}),Mp(dv,{coordinateGetter:lv})),Ke=Ny,Ct=r.useMemo(()=>{const E=new Date,c=E.getFullYear(),Y=String(E.getMonth()+1).padStart(2,"0"),ye=String(E.getDate()).padStart(2,"0");return`${c}-${Y}-${ye}`},[]),dt=r.useMemo(()=>{const E=ye=>{const Ie=ye.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!Ie)return null;const He=new Date(Date.UTC(Number(Ie[1]),Number(Ie[2])-1,Number(Ie[3]))),Ve=He.getUTCDay()||7;He.setUTCDate(He.getUTCDate()+4-Ve);const Ne=new Date(Date.UTC(He.getUTCFullYear(),0,1)),Vt=Math.ceil(((He.getTime()-Ne.getTime())/864e5+1)/7);return`${He.getUTCFullYear()}-W${String(Vt).padStart(2,"0")}`};return{dates:{...(()=>{const ye=new Date,Ie=ye.getDay(),He=Ie===0?-6:1-Ie,Ve=new Date(ye);Ve.setDate(ye.getDate()+He);const Ne=Et=>{const Tt=Et.getFullYear(),Wt=String(Et.getMonth()+1).padStart(2,"0"),Ht=String(Et.getDate()).padStart(2,"0");return`${Tt}-${Wt}-${Ht}`},Vt={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((Et,Tt)=>{const Wt=new Date(Ve);Wt.setDate(Ve.getDate()+Tt),Vt[Et]=Ne(Wt)}),Vt})(),...je||{}},parseToIsoWeekKey:E}},[je]),Xe=E=>{const c=E.scheduledDate||null;return c?new Map([[dt.dates.mon,"mon"],[dt.dates.tue,"tue"],[dt.dates.wed,"wed"],[dt.dates.thu,"thu"],[dt.dates.fri,"fri"],[dt.dates.sat,"sat"],[dt.dates.sun,"sun"]]).get(c)||"__offweek":"backlog"},ct=r.useMemo(()=>{if(n==="schedule")return[];const E=new Set(t.map(Ie=>String(Ie.value))),c=new Set(t.map(Ie=>Ie.label)),Y=[],ye=Ie=>{const He=n==="status"?Ke(Ie):Ie[n],Ve=String(He??"");if(!Ve||E.has(Ve)||c.has(Ve))return null;if(n==="category"){const Ne=de.find(Vt=>Vt.value===Ve||Vt.label===Ve);return{value:Ve,label:Ne?.label||Ve,icon:Ne?.icon||"Folder",color:Ne?.color}}if(n==="type"){const Ne=i?.find(Vt=>Vt.value===Ve||Vt.label===Ve);return{value:Ve,label:Ne?.label||Ve,icon:Ne?.icon||"CheckSquare",color:Ne?.color}}if(n==="priority"){const Ne=d?.find(Vt=>Number(Vt.value)===Number(Ve));return{value:Number.isFinite(Number(Ve))?Number(Ve):Ve,label:Ne?.label||Ve,icon:Ne?.icon||"Flag",color:Ne?.color}}if(n==="complexity")return{value:Number.isFinite(Number(Ve))?Number(Ve):Ve,label:Ve,icon:"Gauge"};if(n==="status")return{value:Ve,label:Ve,icon:"Circle"};if(n==="assignee"){const Ne=y.find(Vt=>Vt.value===Ve);return{value:Ve,label:Ne?.label||Ve,icon:Ne?.icon==="HelpCircle"?"Circle":Ne?.icon,color:Ne?.color}}return{value:Ve,label:Ve}};for(const Ie of e){const He=ye(Ie);He&&(Y.push(He),E.add(String(He.value)),c.add(He.label))}return Y},[y,de,n,t,d,e,i]),ne=r.useMemo(()=>[...t,...ct],[ct,t]),st=r.useMemo(()=>{const E=new Map;for(const c of ne)E.set(String(c.value),c),E.has(c.label)||E.set(c.label,c);return E},[ne]),Ye=r.useMemo(()=>{const E={};return ne.forEach(Y=>{E[String(Y.value)]=0}),(me.length>0?me:e).forEach(Y=>{let ye="";if(n==="status")ye=Ke(Y);else if(n==="schedule")ye=Xe(Y);else{const He=Y[n];ye=String(He??"")}const Ie=st.get(ye);if(Ie&&E[String(Ie.value)]++,n==="schedule"){const He=Y.status==="done"||Y.status==="cancelled";Y.scheduledDate&&!He&&Y.scheduledDate<Ct&&st.has("expired")&&(E.expired=(E.expired||0)+1)}}),E},[me,e,ne,n,st,Ct]),Pt=r.useMemo(()=>{const E={};if(ne.forEach(c=>{E[String(c.value)]=[]}),e.forEach(c=>{let Y="";if(n==="status")Y=Ke(c);else if(n==="schedule")Y=Xe(c);else{const Ie=c[n];Y=String(Ie??"")}const ye=st.get(Y);if(ye){if(n==="schedule"&&String(ye.value)==="backlog"&&!nt.has(c.id))return;E[String(ye.value)].push(c)}if(n==="schedule"){const Ie=c.status==="done"||c.status==="cancelled";c.scheduledDate&&!Ie&&c.scheduledDate<Ct&&E.expired&&E.expired.push(c)}}),n==="schedule"){const c=(ye,Ie)=>{const He=typeof ye.orderInDay=="number"?ye.orderInDay:Number.MAX_SAFE_INTEGER,Ve=typeof Ie.orderInDay=="number"?Ie.orderInDay:Number.MAX_SAFE_INTEGER;return He!==Ve?He-Ve:String(ye.createdAt||"").localeCompare(String(Ie.createdAt||""))},Y=(ye,Ie)=>im(ye,Ie,Pe,Ce,l);Object.keys(E).forEach(ye=>{if(ye==="backlog"||ye==="expired"){E[ye].sort(Y);return}E[ye].sort(c)})}return E},[e,me,ne,n,st,nt,Ct,Pe,Ce]),kt=te?Te(te):null,It=kt?e.find(E=>E.id===kt):null,Ft=r.useRef(null),Mt=r.useRef(null),Be=r.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),et=r.useRef(-1),Ue=(E,c)=>M?n==="category"?!x.includes(String(E)):n==="type"?!K.includes(String(E)):n==="priority"?!ue.some(Y=>Number(Y)===Number(E)):n==="status"?String(E)==="completed"?!pe.includes("done")&&!pe.includes("cancelled"):!pe.includes(String(E)):n==="assignee"?!X.includes(String(E)):!1:!1,Qe=r.useMemo(()=>{let ye=0;return ne.forEach((Ie,He)=>{const Ve=Pt[String(Ie.value)]||[],Ne=Ue(Ie.value,Ie.label),Vt=n!=="schedule"&&re==="hide"&&Ve.length===0;if(Ne||Vt)return;const qt=re==="collapse"&&Ve.length===0;ye+=qt?72:320,ye+=4}),ye},[ne,Pt,re,n,x,K,ue,pe,X,M]),yt=r.useCallback(E=>{if(!Re)return;const c=Math.max(0,Math.round(E));c!==et.current&&(et.current=c,Re(c))},[Re]);r.useEffect(()=>{const E=Ft.current,c=Mt.current;if(!E||!c)return;let Y=!1,ye=!1;const Ie=()=>{!E||ye||(Y=!0,E.scrollLeft=c.scrollLeft,yt(c.scrollLeft),setTimeout(()=>Y=!1,0))},He=()=>{!c||Y||(ye=!0,c.scrollLeft=E.scrollLeft,yt(E.scrollLeft),setTimeout(()=>ye=!1,0))};return c.addEventListener("scroll",Ie),E.addEventListener("scroll",He),()=>{c.removeEventListener("scroll",Ie),E.removeEventListener("scroll",He)}},[yt]);const ot=r.useRef(!1);r.useEffect(()=>{if(ot.current)return;if(typeof ce!="number"||!Number.isFinite(ce)){ot.current=!0;return}const E=Ft.current,c=Mt.current;if(!E||!c)return;const Y=Math.max(0,E.scrollWidth-E.clientWidth),ye=Math.min(Math.max(0,ce),Y);E.scrollLeft=ye,c.scrollLeft=ye,ot.current=!0},[ce,Qe]),r.useEffect(()=>{const E=()=>{const c=Ft.current;if(!c){ie(!1);return}ie(c.scrollWidth>c.clientWidth+4)};return E(),window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E)}},[Qe,ne.length,Pt]),r.useEffect(()=>{const E=Y=>{const ye=Be.current;if(ye.pointerId===null||ye.pointerId!==Y.pointerId)return;const Ie=Y.clientX-ye.startX,He=Y.clientY-ye.startY;if(!ye.didPan){if(Math.abs(Ie)<7||Math.abs(Ie)<Math.abs(He))return;ye.didPan=!0,be(!0),document.body.style.userSelect="none"}const Ve=ye.startScrollLeft-Ie;Ft.current&&(Ft.current.scrollLeft=Ve),Mt.current&&(Mt.current.scrollLeft=Ve),Y.preventDefault()},c=()=>{const Y=Be.current;Y.pointerId!==null&&(Y.pointerId=null,Y.didPan=!1,H&&(be(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",E),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),document.body.style.userSelect=""}},[H]);const ae=E=>{!z||E.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(Be.current.pointerId=E.pointerId,Be.current.startX=E.clientX,Be.current.startY=E.clientY,Be.current.startScrollLeft=Ft.current?.scrollLeft||0,Be.current.didPan=!1)},ze=E=>{P(E.active.id)},bt=E=>{const c=lt(E.active),Y=String(E.over?.data?.current?.type||"");c.type==="task-card"&&Y.startsWith("planning-")?gt.current=`${String(E.over?.id||"")}:${Y}`:gt.current&&(gt.current=null)},Ot=E=>{const{active:c,over:Y}=E;gt.current=null,P(null);const ye=lt(c),Ie=ye.type,He=String(Y?.data?.current?.type||""),Ve=ye.taskId,Ne=ye.workstreamId,Vt=String(Y?.data?.current?.workstreamId||""),qt=String(Y?.data?.current?.initiativeId||"");if(Ie==="task-card"&&He==="planning-workstream-target"&&Ve&&Vt){U?.(Ve,Vt);return}if(Ie==="planning-workstream"){if(He==="planning-initiative-target"&&Ne&&qt){T?.(Ne,qt);return}return}const Et=String(c.id),Tt=Y?String(Y.id):null,Wt=Te(Et);Tt&&Te(Tt);const Ht=e.find(he=>he.id===Wt);if(!Ht||!Tt)return;const sa=Bt(Et),Ka=String(c?.data?.current?.sortable?.containerId||"")||sa,Xa=String(Y?.data?.current?.sortable?.containerId||"")||Bt(Tt);if(!Xa)return;const wa=st.get(Xa)||ne.find(he=>String(he.value)===Xa||he.label===Xa);if(wa){if(n==="schedule"){const xe=String(wa.value),jt=Tt&&Me(Tt)?Te(Tt):null,tt=Y?.rect,ga=c.rect.current.translated||c.rect.current.initial,Na=!!(tt&&ga&&ga.top+ga.height/2>tt.top+tt.height/2),ua=(Pt[xe]||[]).filter(aa=>aa.id!==Wt),ca=(Pt[String(Ka)]||[]).filter(aa=>aa.id!==Wt),Dt=SW({activeTask:Ht,sourceColumnId:Ka,targetColumnId:xe,targetTasks:ua,sourceTasks:ca,overTaskId:jt,isBelowOverItem:Na,scheduleDates:dt.dates,parseToIsoWeekKey:dt.parseToIsoWeekKey,todayDate:Ct});if(!Dt)return;if(Dt.kind==="blocked"){window.alert(Dt.reason);return}Dt.updates.forEach(({taskId:aa,updates:Za})=>k(aa,Za)),Dt.selectedDate&&se?.(Dt.selectedDate);return}let he=wa.value;if(n==="status"){const xe=String(he),jt=hW(Ht,xe,new Date().toISOString());jt&&k(Ht.id,jt);return}(n==="priority"||n==="complexity")&&(he=Number(he));const it=Ht[n];if(String(it??"")!==String(he??"")){const xe={[n]:he};k(Ht.id,xe)}}},Bt=E=>{if(st.has(E)){const ye=st.get(E);return ye?String(ye.value):E}if(n==="schedule"&&E.startsWith(Vu))return"expired";const c=Te(E),Y=e.find(ye=>ye.id===c);if(Y){let ye="";n==="status"?ye=Ke(Y):n==="schedule"?ye=Xe(Y):ye=String(Y[n]??"");const Ie=st.get(ye);return Ie?String(Ie.value):null}return null},Oe={sideEffects:uv({styles:{active:{opacity:"0"}}})},Lt=E=>{try{const c=cv(E);if(c.length>0){const Y=c.find(Vt=>String(Vt.id).startsWith("planning-"));if(Y)return[Y];const ye=E.pointerCoordinates;if(!ye)return[c[0]];const Ie=c.filter(Vt=>{const qt=String(Vt.id);return Me(qt)&&qt!==te});if(Ie.length===0){const qt=c.filter(Wt=>{const Ht=String(Wt.id);return!Me(Ht)}).find(Wt=>!!Bt(String(Wt.id)))||null,Et=qt?Bt(String(qt.id)):null,Tt=(E.droppableContainers||[]).filter(Wt=>{const Ht=String(Wt.id);return!Me(Ht)||Ht===te?!1:Et?Bt(Ht)===Et:!0});if(Tt.length>0){const Wt=Yf({...E,droppableContainers:Tt});if(Wt.length>0)return[Wt[0]]}return qt?[qt]:[c[0]]}const He=Ie;let Ve=He[0],Ne=Number.POSITIVE_INFINITY;for(const Vt of He){const qt=E.droppableRects?.get(Vt.id);if(!qt)continue;const Et=qt.left+qt.width/2,Tt=qt.top+qt.height/2,Wt=ye.x-Et,Ht=ye.y-Tt,sa=Wt*Wt+Ht*Ht;sa<Ne&&(Ne=sa,Ve=Vt)}return[Ve]}return Yf(E)}catch(c){return console.error("[TaskKanban] collision detection error",c),[]}},vt={searchQuery:s,copiedId:o,taxonomies:l,types:i,priorities:d,approaches:m,assigneeOptions:y,onCopyId:g,onToggleInProgress:v,onToggleReview:A,onToggleComplete:_,onToggleCancel:I,onSetStatus:B,onArchiveTask:V,onUnarchive:L,onDelete:J,onOpenTaskById:h,categories:de,readOnlyMode:$,changedTaskIdSet:ee,resolveTaskHierarchy:Se,groupBy:n,showStatusLabel:b};return a.jsxs(gg,{sensors:St,collisionDetection:Lt,onDragStart:ze,onDragOver:bt,onDragEnd:Ot,onDragCancel:E=>{gt.current=null,P(null)},children:[Ee,a.jsxs("div",{className:p.kanbanWrapper,children:[a.jsx("div",{ref:Mt,className:`${p.kanbanTopScroll} tf-scrollbar`,children:a.jsx("div",{className:p.kanbanTopScrollSpacer,style:{width:`${Qe}px`}})}),a.jsx("div",{className:p.kanbanContainer,ref:Ft,children:ne.map(E=>{const c=Pt[String(E.value)]||[],Y=Ue(E.value,E.label),ye=n!=="schedule"&&re==="hide"&&c.length===0,Ie=n==="schedule",He=Ie&&ne.some(Ht=>String(Ht.value)==="backlog"),Ve=Ie&&String(E.value)==="backlog",Ne=Ie&&String(E.value)==="expired",Vt=Pt.backlog||[],Et=re==="collapse"&&Vt.length===0?72:320,Tt=Ve?0:Ne?He?Et+4:0:void 0,Wt=Ve?6:Ne?5:void 0;return Y||ye?null:a.jsx(bW,{id:String(E.value),title:E.label,color:E.color,icon:E.icon,tasks:c,activeId:te,activeTaskId:kt,totalCount:Ye[String(E.value)],onAddTask:()=>ve?.(n,E.value),onTaskClick:S,commonCardProps:vt,collapseEmpty:re==="collapse",compressed:ge,onHeaderPointerDown:ae,isHeaderPanning:H,headerPanEnabled:z,stickyLeft:Tt,stickyZIndex:Wt,isPast:!!E.isPast,isSelected:!!E.isSelected,isWeekend:!!E.isWeekend,disableSorting:!1,scheduleDate:n==="schedule"?dt.dates[String(E.value)]:void 0,onScheduleDaySelected:se},String(E.value))})})]}),Zi.createPortal(a.jsx(iv,{dropAnimation:Oe,children:It?(()=>{const{taskWorkstream:E,taskInitiative:c}=Se(It);return a.jsx(Cd,{task:It,taskWorkstream:E,taskInitiative:c,isOverlay:!0,...vt,isArchived:It.isArchived,categories:de,compressed:ge,isRecentlyChanged:ee.has(It.id)})})():null}),document.body)]})}function bW({id:e,title:t,color:n,icon:s,tasks:o,activeId:l=null,activeTaskId:i=null,totalCount:d,onAddTask:m,onTaskClick:y,commonCardProps:k,collapseEmpty:S,compressed:h,onHeaderPointerDown:g,isHeaderPanning:v=!1,headerPanEnabled:A=!1,stickyLeft:_,stickyZIndex:I,isPast:B=!1,isSelected:V=!1,isWeekend:L=!1,disableSorting:J=!1,scheduleDate:me,onScheduleDaySelected:ve}){const{setNodeRef:re}=af({id:e,data:{type:"Column"}}),x=S&&o.length===0,K=i?o.filter(O=>O.id!==i):o,ue=typeof _=="number",pe=r.useRef(null),X=O=>e==="expired"?`${Vu}${O}`:O,M=O=>{if(!me||!ve)return;const de=O.target;de&&(de.closest('[data-task-card="true"]')||de.closest(`.${p.kanbanCardWrapper}`)||ve(me))};return a.jsxs("div",{ref:re,className:`${p.kanbanColumn} ${x?p.kanbanColumnCollapsed:""} ${ue?p.kanbanColumnSticky:""} ${B?p.kanbanColumnPast:""} ${V?p.kanbanColumnSelectedDay:""} ${L?p.kanbanColumnWeekend:""}`,style:ue?{left:`${_}px`,zIndex:I??4}:void 0,onClick:M,children:[a.jsxs("div",{className:`${p.kanbanHeader} ${A?p.kanbanHeaderDraggable:""} ${v?p.kanbanHeaderPanning:""}`,style:{borderTopColor:Nn(n)||"var(--color-purple)"},onPointerDown:g,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[(()=>{const O=s&&ec[s]?ec[s]:Ro,de=Nn(n)||"var(--color-purple)";return a.jsx(O,{size:16,style:{color:de}})})(),!x&&a.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!x||d>0)&&a.jsx("span",{className:p.kanbanCount,children:x?d:`${o.length} / ${d}`}),!k.readOnlyMode&&a.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:O=>{O.stopPropagation(),m()},title:`Add task to ${t}`,"aria-label":`Add task to ${t}`,"data-no-header-pan":"true",children:a.jsx(to,{size:14})})]})]}),a.jsx("div",{className:p.kanbanDroppable,children:a.jsx("div",{className:`${p.kanbanDroppableScroll} ${p.appScrollbar} tf-scrollbar`,ref:pe,children:J?K.map(O=>a.jsx("div",{className:p.kanbanCardWrapper,children:(()=>{const{taskWorkstream:de,taskInitiative:ge}=k.resolveTaskHierarchy?.(O)||{};return a.jsx(Cd,{task:O,taskWorkstream:de,taskInitiative:ge,onClick:y,...k,isArchived:O.isArchived,readOnlyMode:k.readOnlyMode||null,compressed:h,isRecentlyChanged:!1})})()},O.id)):a.jsx(yg,{id:e,items:K.map(O=>X(O.id)),strategy:kg,children:K.map(O=>a.jsx(_W,{sortableId:X(O.id),task:O,onClick:y,commonCardProps:k,compressed:h,isRecentlyChanged:k.changedTaskIdSet?.has(O.id)},X(O.id)))})})})]})}function _W({sortableId:e,task:t,onClick:n,commonCardProps:s,compressed:o,isRecentlyChanged:l=!1}){const i=!!s?.readOnlyMode,{attributes:d,listeners:m,setNodeRef:y,transform:k,transition:S,isDragging:h}=Sg({id:e,disabled:i,data:{type:"task-card",taskId:t.id}}),g={transform:tf.Transform.toString(k),transition:S,opacity:h?0:1,pointerEvents:h?"none":"auto"},v=s?.groupBy==="schedule",A=!v&&l;return a.jsx("div",{ref:y,style:g,...i?{}:d,...i?{}:m,className:`${p.kanbanCardWrapper} ${A?p.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:_,taskInitiative:I}=s.resolveTaskHierarchy?.(t)||{};return a.jsx(Cd,{task:t,taskWorkstream:_,taskInitiative:I,onClick:n,...s,isArchived:t.isArchived,readOnlyMode:s?.readOnlyMode||null,compressed:o,isRecentlyChanged:v?!1:l})})()})}function CW(e,t,n){const s=String(t);if(e==="category"){const o=n.categories.find(l=>String(l.value)===s||l.label===s);return o?{category:o.label}:{}}if(e==="type")return{type:s};if(e==="priority")return Number.isFinite(Number(t))?{priority:Number(t)}:{};if(e==="complexity")return Number.isFinite(Number(t))?{complexity:Number(t)}:{};if(e==="approach"){const o=n.approaches.find(l=>String(l.value)===s||l.label===s);return o?{approach:o.value,taxonomyApproach:o.value}:{}}return e==="assignee"?s.trim().length>0?{assignee:s}:{}:e==="status"?s==="completed"?{status:"done"}:s==="task"||s==="on-hold"||s==="in-progress"||s==="review"||s==="done"||s==="cancelled"?{status:s}:{}:e==="schedule"?s==="backlog"||s==="expired"?{}:{scheduledDate:s}:{}}function AW(e){switch(e){case"auth-required":return{summary:"Sync is paused until you sign in again.",recommendedAction:"Sign in, then press Sync to retry."};case"attach-cloud":return{summary:"This workspace still needs its first cloud pull before local pushes can run.",recommendedAction:"Keep this window open for the first cloud pull. If it seems stuck, press Repair."};case"provision-local":return{summary:"This workspace is still doing its first cloud upload before normal pulls can run.",recommendedAction:"Keep this window open until the first cloud upload finishes."};case"repair-active":return{summary:"Repair is already running for this workspace.",recommendedAction:"Wait for repair to finish before retrying sync."};case"retry-pending":return{summary:"Sync hit a temporary problem and is waiting for its scheduled retry.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."};case"push-in-flight":case"pull-in-flight":return{summary:"A sync request is already running for this workspace.",recommendedAction:"Wait for the current sync request to finish."};case"lease-held":return{summary:"Another local window is already syncing this workspace.",recommendedAction:"Use a single local window for sync, or close the other syncing window."};case"invalid-workspace":return{summary:"Workspace setup is required before sync can run.",recommendedAction:"Open or create a named workspace before retrying sync."};case"cloud-auth-unconfigured":return{summary:"Cloud sync is unavailable because cloud authentication is not configured.",recommendedAction:"Configure cloud authentication before turning on sync."};case"runtime-not-local":return{summary:"Workspace sync controls are only available in the local runtime.",recommendedAction:"Open this workspace in the local app to manage sync."};case"sync-disabled":return{summary:"Workspace sync is currently turned off.",recommendedAction:"Turn on sync when you are ready to connect this workspace to cloud."};default:return null}}function xW(e){const t=e.runtimeMode==="local"&&e.isAuthenticated;if(t){const n=AW(e.retryBlockedReason||e.pullBlockedReason||e.pushBlockedReason||null);return{actionable:t,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:n?.summary||e.workspaceSyncSummary,recommendedAction:n?.recommendedAction||e.workspaceSyncRecommendedAction,lastError:e.workspaceSyncError}}return{actionable:t,status:"off",syncEnabledLabel:"no",summary:"Sign in to enable workspace sync controls on this device.",recommendedAction:"Sign in to manage workspace sync for this workspace.",lastError:"Sign in to enable workspace sync controls on this device."}}function pm(e,t){return e==="deleted"?!1:e==="archived"?t:!t}function IW(e,t,n){const s=t.filter(d=>pm(n,!!d.isArchived)),o=n==="deleted"?[]:e.filter(d=>pm(n,!!d.isArchived)).map(d=>({...d,workstreams:s.filter(m=>m.initiativeId===d.id)})),l=s.filter(d=>!d.initiativeId),i=[...o.flatMap(d=>d.workstreams),...l];return{initiatives:o,standaloneWorkstreams:l,visibleWorkstreams:i,initiativeById:new Map(o.map(d=>[d.id,d])),workstreamById:new Map(i.map(d=>[d.id,d]))}}function Ey(e){return typeof e.occurredAt=="string"&&e.occurredAt.trim().length>0?e.occurredAt:"unknown-time"}function TW(e){return typeof e.eventType=="string"&&e.eventType.trim().length>0?e.eventType.trim():"sync"}function RW(e){const t=Sm(e.details),n=t?t.source:null;return typeof n=="string"?n.trim():""}function $h(e){const t=String(e||"").trim();switch(t){case"auth-required":return"sign in required";case"lease-held":return"another window is already syncing";case"sync-disabled":return"sync is turned off";case"attach-cloud":return"initial cloud pull required";case"provision-local":return"initial cloud upload required";default:return t.length>0?t.replace(/-/g," "):"blocked"}}function Uh(e){const t=String(e||"").trim();switch(t){case"attach-cloud":return"initial cloud pull";case"provision-local":return"initial cloud upload";case"active":return"active sync";case"error":return"error recovery";case"idle":return"idle sync";default:return t.length>0?t.replace(/-/g," "):"sync"}}function jW(e){const t=Ey(e),n=Sm(e.details),s=RW(e);return s==="retry.blocked"?`${t} manual retry blocked: ${$h(n?.reason)} during ${Uh(n?.phase)}`:s==="repair.started"?`${t} manual repair started: ${Uh(n?.repairPhase)} selected`:s==="repair.blocked"?`${t} manual repair blocked: ${$h(n?.reason)}`:null}function el(e,t=0){const n=String(e.id??"").trim();return n?`id:${n}`:[String(e.occurredAt||"").trim()||"unknown-time",String(e.eventType||"").trim()||"sync",String(e.status||"").trim()||"unknown-status",String(e.statusCode??""),String(e.changeCount??""),String(e.requestMs??""),String(e.errorMessage||"").trim(),yw(e.details),String(t)].join("|")}function NW(e,t,n=15){const s=new Map;for(const[o,l]of e.entries())s.set(el(l,o),l);for(const[o,l]of t.entries())s.set(el(l,o),l);return Array.from(s.values()).sort((o,l)=>String(l.occurredAt||"").localeCompare(String(o.occurredAt||""))).slice(0,Math.max(1,n))}function PW(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(el(e[n],n)!==el(t[n],n))return!1;return!0}function Dy(e){const t=jW(e);if(t)return t;const n=Ey(e),s=TW(e),o=e.status==="error"?"failed":"succeeded",l=Number(e.changeCount),i=Number.isFinite(l)?` (${Math.max(0,Math.floor(l))} change${Math.floor(l)===1?"":"s"})`:"",d=Number(e.requestMs),m=Number.isFinite(d)?` in ${Math.max(0,Math.floor(d))}ms`:"",y=Number(e.statusCode),k=Number.isFinite(y)?` [${Math.floor(y)}]`:"",S=typeof e.errorMessage=="string"&&e.errorMessage.trim().length>0?`: ${e.errorMessage.trim()}`:"";return`${n} ${s} ${o}${i}${m}${k}${S}`}function Kp(e){if(!e)return"Never";const t=new Date(e);return Number.isNaN(t.getTime())?"Never":t.toLocaleString()}function MW(e){switch(e){case"off":return{label:"Off",icon:"off",color:"#94a3b8",border:"rgba(148, 163, 184, 0.35)",background:"rgba(148, 163, 184, 0.12)"};case"syncing":return{label:"Syncing",icon:"cloud",color:"#60a5fa",border:"rgba(96, 165, 250, 0.35)",background:"rgba(59, 130, 246, 0.12)"};case"attention":return{label:"Needs Attention",icon:"cloud",color:"#fda4af",border:"rgba(253, 164, 175, 0.4)",background:"rgba(239, 68, 68, 0.12)"};default:return{label:"Healthy",icon:"cloud",color:"#86efac",border:"rgba(134, 239, 172, 0.4)",background:"rgba(34, 197, 94, 0.12)"}}}function Ly(e,t,n){if(t)return"Repairing";if(n&&e==="error")return"Recovering";switch(e){case"provision-local":return"Initial cloud upload";case"attach-cloud":return"Initial cloud pull";case"active":return"Active";case"error":return"Error";default:return"Idle"}}function EW(e){return[{label:"AI profile snapshot",value:`${e.aiProfileSnapshotCount} local profile${e.aiProfileSnapshotCount===1?"":"s"}`},{label:"AI profile raw response",value:`${e.aiProfileSnapshotRawCount} from route`},{label:"Last pushed AI profiles",value:`${e.lastPushedAiProfileCount} tracked`},{label:"AI watermark map",value:`${e.lastPushedAiProfileWatermarkCount} tracked`},{label:"Document snapshot",value:`${e.documentSnapshotCount} local doc${e.documentSnapshotCount===1?"":"s"}`},{label:"Asset snapshot",value:`${e.assetSnapshotCount} local asset${e.assetSnapshotCount===1?"":"s"}`},{label:"Queued full AI sync",value:e.forceFullAiProfilePushQueued?"Yes":"No"},{label:"AI snapshot last fetch",value:Kp(e.aiProfileSnapshotLastFetchAt)},{label:"AI snapshot fetch error",value:e.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:e.aiProfileSnapshotLastSkipReason||"None"}]}function DW({syncRecentEvents:e,syncRecentEventsError:t,syncRecentEventsLoading:n}){return n&&e.length===0?[{key:"loading",text:"Loading recent sync events...",tone:"muted"}]:t?[{key:"error",text:t,tone:"error"}]:e.length===0?[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}]:e.map((s,o)=>({key:el(s,o),text:Dy(s),tone:s.status==="error"?"error":"default"}))}function By(e){const t=[];for(const n of e){if(String(n.errorMessage||"").toLowerCase().includes("reference number mismatch")){t.push(n);continue}if(String(n.status||"").toLowerCase()==="success")break}return t}function LW(e){return By(e).length}function BW(e){return By(e).map((t,n)=>{const s=t.details&&typeof t.details=="object"?t.details:null,o=String(s?.path||"").trim(),l=String(s?.referenceLabel||"").trim(),i=String(s?.taskTitle||s?.existingTaskTitle||"").trim(),d=Number(s?.existingReferenceNumber),m=Number(s?.incomingReferenceNumber),y=o||i||l||`Mismatch ${n+1}`,k=Number.isFinite(d)||Number.isFinite(m)?`Existing ${Number.isFinite(d)?d:"?"} vs incoming ${Number.isFinite(m)?m:"?"}`:l?`Both claimed ${l}`:null;return{key:el(t,n),pathLabel:y,refsLabel:k}})}function WW({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:k,referenceMismatchCount:S,syncRecentEvents:h}){const g=["Taskforce Sync Manager",`Workspace ID: ${e}`,`Status: ${t}`,`Summary: ${n}`,`Recommended action: ${s}`,`Last successful sync: ${o}`,`Last pull from cloud: ${l}`,`Last push to cloud: ${i}`,`Last error at: ${Kp(d.lastErrorAt)}`,`Pending local changes: ${m}`,`Last error: ${y}`,`Sync stage: ${k}`,`Push blocked reason: ${d.pushBlockedReason||"None"}`,`Pull blocked reason: ${d.pullBlockedReason||"None"}`,`Retry blocked reason: ${d.retryBlockedReason||"None"}`,`Repair active: ${d.repairActive?"Yes":"No"}`,`Push in flight: ${d.pushInFlight?"Yes":"No"}`,`Pull in flight: ${d.pullInFlight?"Yes":"No"}`,`Retry pending: ${d.retryPending?"Yes":"No"}`,`AI profile snapshot: ${d.aiProfileSnapshotCount}`,`AI profile raw response: ${d.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${d.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${d.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${Kp(d.aiProfileSnapshotLastFetchAt)}`,`AI snapshot fetch error: ${d.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${d.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${d.documentSnapshotCount}`,`Asset snapshot: ${d.assetSnapshotCount}`,`Reference mismatches detected: ${S}`,`Queued full AI sync: ${d.forceFullAiProfilePushQueued?"Yes":"No"}`],v=h.map(A=>Dy(A));return[...g,"","Recent sync events",...v.length>0?v:["No recent sync events recorded."]].join(`
|
|
5
|
+
`)}const zh="/api/taskforce/account/profile-summary",FW=9e4,Gc=new Map;function $u(){return typeof performance<"u"?performance.now():Date.now()}function Wy(e,t){const n=String(e||"").trim();if(!n)return"";const s=String(t||"").trim();return s?`${n}::${s}`:n}function Hh(e,t){Gc.delete(Wy(e,t?.identityKey))}async function OW(e,t){const n=String(e||"").trim(),s=Wy(e,t?.identityKey);if(!s||!n)return null;const o=t?.force===!0,l=Date.now(),i=Gc.get(s);if(!o&&i?.payload!==void 0&&l-i.fetchedAt<FW)return zt("account_profile_summary_cache_hit",{url:n,cacheKey:s,ageMs:l-i.fetchedAt}),i.payload;if(!o&&i?.promise)return zt("account_profile_summary_request_reused",{url:n,cacheKey:s}),i.promise;const d=$u(),m=(async()=>{const y=await fetch(n,{method:"GET",credentials:"include"});if(!y.ok)throw new Error(String((await y.json().catch(()=>({})))?.error||"Failed to load account summary."));const S=await y.json().catch(()=>({}))||null;return Gc.set(s,{payload:S,fetchedAt:Date.now(),promise:null}),zt("account_profile_summary_loaded",{url:n,cacheKey:s,durationMs:Math.round($u()-d),fromCache:!1}),S})().catch(y=>{const k=i?.payload??null;if(k)return Gc.set(s,{payload:k,fetchedAt:i?.fetchedAt??Date.now(),promise:null}),zt("account_profile_summary_failed",{url:n,cacheKey:s,durationMs:Math.round($u()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!0}),k;throw Gc.delete(s),zt("account_profile_summary_failed",{url:n,cacheKey:s,durationMs:Math.round($u()-d),error:y instanceof Error?y.message:String(y||"Unknown error"),returnedStale:!1}),y});return Gc.set(s,{payload:i?.payload??null,fetchedAt:i?.fetchedAt??0,promise:m}),m}const $W=1024,UW=5*1024*1024,zW=[.9,.82,.74,.66,.58],HW=[.9,.82,.74,.66,.58],GW=[1,.85,.7,.55,.4],VW=new Set(["image/png","image/jpeg","image/webp"]);function qW(e,t){const n=document.createElement("canvas");return n.width=Math.max(1,Math.round(e)),n.height=Math.max(1,Math.round(t)),n}async function KW(e){const t=URL.createObjectURL(e);try{const n=await new Promise((s,o)=>{const l=new Image;l.onload=()=>s(l),l.onerror=()=>o(new Error("Failed to load image.")),l.src=t});return{width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,source:n}}finally{URL.revokeObjectURL(t)}}async function ZW(e){const t=qW(e.width,e.height),n=t.getContext("2d");if(!n)throw new Error("Image optimization requires a 2D canvas context.");return n.drawImage(e.image.source,0,0,t.width,t.height),await new Promise((s,o)=>{t.toBlob(l=>{if(l){s(l);return}o(new Error("Failed to encode resized image."))},e.type,e.quality)})}const YW={loadImage:KW,renderToBlob:ZW};function Gh(e,t){return e==="image/png"?".png":e==="image/jpeg"?".jpg":e==="image/webp"?".webp":(t.includes(".")?t.slice(t.lastIndexOf(".")):"")||".img"}function Vh(e,t){const n=String(e||"").trim();if(!n)return`avatar${t}`;const s=n.lastIndexOf(".");return s<=0?`${n}${t}`:`${n.slice(0,s)}${t}`}function JW(e){const t=e==="image/jpeg"?"image/jpeg":"image/webp";return Array.from(new Set([t,"image/webp","image/jpeg"]))}function QW(e){return e==="image/webp"?zW:e==="image/jpeg"?HW:[void 0]}async function XW(e,t,n=YW){const s=Number.isFinite(t?.maxBytes)&&(t?.maxBytes||0)>0?Math.floor(t?.maxBytes):UW,o=Number.isFinite(t?.maxDimension)&&(t?.maxDimension||0)>0?Math.floor(t?.maxDimension):$W;if(e.size<=s)return{file:e,optimized:!1,exceededLimit:!1};if(!VW.has(e.type))return{file:e,optimized:!1,exceededLimit:!0};const l=await n.loadImage(e),i=Math.max(l.width,l.height,1),d=Math.min(1,o/i);let m=null;for(const k of GW){const S=Math.min(1,d*k),h=Math.max(1,Math.round(l.width*S)),g=Math.max(1,Math.round(l.height*S));for(const v of JW(e.type))for(const A of QW(v)){const _=await n.renderToBlob({image:l,width:h,height:g,type:v,quality:A});if((!m||_.size<m.size)&&(m=_),_.size<=s)return{file:new File([_],Vh(e.name,Gh(_.type||v,e.name)),{type:_.type||v,lastModified:e.lastModified}),optimized:!0,exceededLimit:!1}}}if(!m)return{file:e,optimized:!1,exceededLimit:!0};const y=new File([m],Vh(e.name,Gh(m.type||e.type,e.name)),{type:m.type||e.type,lastModified:e.lastModified});return{file:y,optimized:y.size<e.size,exceededLimit:y.size>s}}const Zp="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",Fy="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",qh="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function e4({projectName:e,currentWorkspaceId:t,brandLabel:n="TaskForce",brandHomeLabel:s="Go to Kanban",onBrandClick:o,runtimeMode:l="local",theme:i=Ju,meta:d,actions:m}){const y=Ig(i)?Fy:Zp,k=String(e||"").trim(),S=String(t||"").trim(),h=S.toLowerCase(),g=!!(k&&(l!=="cloud"||h&&h!=="default")),v=()=>{if(!S||typeof navigator>"u")return;const I=navigator.clipboard;I?.writeText&&I.writeText(S).catch(()=>{})},A=I=>{I.key!=="Enter"&&I.key!==" "||(I.preventDefault(),v())},_=a.jsxs(a.Fragment,{children:[a.jsx("img",{src:y,alt:"Taskforce Logo",className:p.brandIcon,onError:I=>{const B=I.currentTarget;B.src!==qh?B.src=qh:B.style.display="none"}}),a.jsx("span",{children:n}),l==="cloud"&&a.jsx("span",{className:p.brandCloudSuffix,children:"HQ"})]});return a.jsxs("div",{className:`${p.header} ${ta.standaloneHeader}`,children:[a.jsxs("div",{className:`${p.headerTitle} ${ta.standaloneTitle}`,children:[o?a.jsx("button",{type:"button",className:p.brandHomeButton,onClick:o,title:s,"aria-label":s,children:_}):a.jsx("span",{className:p.brandHomeStatic,children:_}),g&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.projectSlash,children:"/"}),a.jsx("span",{className:p.projectName,title:S?`Workspace ID: ${S}`:void 0,role:S?"button":void 0,tabIndex:S?0:void 0,onClick:v,onMouseDown:I=>I.preventDefault(),onKeyDown:A,children:k})]}),d]}),a.jsx("div",{className:p.headerActions,style:{gap:"16px"},children:m})]})}function t4({value:e,placeholder:t,active:n=!1,onChange:s,onClear:o,clearTitle:l}){return a.jsxs("div",{className:p.searchContainer,style:{width:"240px"},children:[a.jsx($k,{size:16,className:p.searchIcon}),a.jsx("input",{type:"text",className:`${p.searchInput} ${n?p.searchActive:""}`,placeholder:t,value:e,onChange:i=>s(i.target.value)}),e&&o&&a.jsx("button",{className:p.clearSearchBtn,onClick:o,title:l,children:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function Kh({label:e,value:t,options:n,onChange:s,trailingAction:o,width:l}){return a.jsxs("div",{className:p.groupByContainer,style:l?{width:l}:void 0,children:[a.jsx("span",{className:p.groupByLabel,children:e}),a.jsx("select",{className:`${p.select} ${p.groupBySelect}`,value:t,onChange:i=>s(i.target.value),children:n.map(i=>a.jsx("option",{value:i.value,children:i.label},String(i.value)))}),o]})}function _p({actions:e}){return a.jsx(a.Fragment,{children:e.map(t=>a.jsx("button",{className:`tf-control-icon ${t.active?"tf-control-icon-active":""} ${t.className||""}`.trim(),onClick:t.onClick,title:t.title,disabled:t.disabled,"aria-disabled":t.ariaDisabled,children:t.icon},t.key))})}function Zh(){return a.jsx("div",{className:p.headerDivider})}function a4({icon:e,label:t,onClick:n,disabled:s=!1}){return a.jsxs("button",{className:p.primaryUpdateBtn,onClick:n,disabled:s,children:[e," ",t]})}function Cf({children:e}){return a.jsx("div",{className:p.filterToolbar,style:{padding:"8px 24px",borderBottom:"1px solid var(--border-primary)",background:"var(--bg-secondary)",boxShadow:"0 4px 18px rgba(8, 10, 24, 0.12)",display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap",position:"relative",zIndex:50},children:e})}function n4(){return a.jsx(Cf,{children:a.jsx("div",{"aria-hidden":"true",style:{minHeight:"32px",flex:1}})})}function r4({categoryFilterOptions:e,typeFilterOptions:t,priorities:n,taxonomyDisplayLabels:s,filterCategories:o,setFilterCategories:l,filterTypes:i,setFilterTypes:d,filterPriorities:m,setFilterPriorities:y,filterStatus:k,setFilterStatus:S,filterAssignees:h,setFilterAssignees:g,assigneeOptions:v,initiativeFilterOptions:A=[],selectedInitiativeId:_="",setSelectedInitiativeId:I=()=>{},workstreamFilterOptions:B=[],selectedWorkstreamId:V="",setSelectedWorkstreamId:L=()=>{},taskScope:J,setTaskScope:me,showArchive:ve,setShowArchive:re,fetchArchive:x,onDeleteAllDeleted:K,clearFilters:ue}){return a.jsxs(a.Fragment,{children:[a.jsx(ky,{}),a.jsx(qi,{label:s?.category||$e("standalone.categoryLabel"),options:e,selected:o,onChange:pe=>l(pe),variant:"value"}),a.jsx(qi,{label:s?.type||$e("standalone.typeLabel"),options:t,selected:i,onChange:pe=>d(pe),variant:"value"}),a.jsx(qi,{label:s?.priority||$e("standalone.priorityLabel"),options:n,selected:m,onChange:pe=>y(pe),variant:"value"}),a.jsx(qi,{label:$e("standalone.statusLabel"),options:Xs,selected:k,onChange:pe=>S(pe),variant:"value"}),a.jsx(qi,{label:$e("standalone.assigneeLabel"),options:v,selected:h,onChange:pe=>g(pe),variant:"value"}),a.jsx("div",{className:p.headerDivider,style:{height:"16px",margin:"0 8px"}}),a.jsx(Ph,{label:"Initiative",options:A,selected:_,onChange:I,allLabel:"All Initiatives",title:"Filter by initiative"}),a.jsx(Ph,{label:"Workstream",options:B,selected:V,onChange:L,allLabel:"All Workstreams",title:"Filter by workstream"}),a.jsx(Sy,{scope:J,onScopeChange:pe=>{me(pe),pe==="archived"?(re(!0),x()):ve&&re(!1)},className:p.groupByContainer,labelClassName:p.groupByLabel}),a.jsx("div",{style:{flex:1}}),J==="deleted"&&K&&a.jsx(wy,{onClick:K,className:`${p.bulkArchiveBtn} ${p.taskToolbarAction} ${p.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),a.jsx(vy,{onClick:ue})]})}function s4(e){return a.jsx(Cf,{children:a.jsx(r4,{...e})})}const qu=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],Ku=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function o4({typeFilters:e,setTypeFilters:t,attachmentFilters:n,setAttachmentFilters:s,clearFilters:o}){return a.jsxs(Cf,{children:[a.jsx(ky,{}),a.jsx(qi,{label:"Attachment",options:Ku,selected:n,onChange:l=>s(l),variant:"value"}),a.jsx(qi,{label:"Type",options:qu,selected:e,onChange:l=>t(l),variant:"value"}),a.jsx("div",{style:{flex:1}}),a.jsx(vy,{onClick:o})]})}const i4="_drawerBody_ljth8_1",c4="_paneShell_ljth8_9",l4="_collapsedPaneShell_ljth8_18",d4="_collapsedPaneHeader_ljth8_27",u4="_collapsedPaneLabel_ljth8_39",m4="_treePane_ljth8_49",p4="_treePaneSplit_ljth8_59",f4="_detailPane_ljth8_63",h4="_paneHeader_ljth8_73",g4="_paneHeaderLabel_ljth8_87",y4="_paneContent_ljth8_96",k4="_sectionTitle_ljth8_105",v4="_sectionHeaderRow_ljth8_113",S4="_headerActionGroup_ljth8_120",w4="_toggleActive_ljth8_127",b4="_sectionGroup_ljth8_133",_4="_treeList_ljth8_158",C4="_treeChildren_ljth8_164",A4="_treeRow_ljth8_172",x4="_treeRowDetailOpen_ljth8_184",I4="_treeRowDropReady_ljth8_190",T4="_treeRowDropActive_ljth8_194",R4="_treeRowDropMode_ljth8_200",j4="_treeChevron_ljth8_200",N4="_rowButton_ljth8_201",P4="_detailsButton_ljth8_202",M4="_treeRowDragging_ljth8_206",E4="_treeChevronPlaceholder_ljth8_230",D4="_rowContent_ljth8_252",L4="_rowTopRow_ljth8_262",B4="_referenceBadgeButton_ljth8_271",W4="_referenceBadgeStatic_ljth8_277",F4="_rowTitle_ljth8_298",O4="_rowMeta_ljth8_312",$4="_detailsButtonActive_ljth8_340",U4="_emptyPanel_ljth8_347",z4="_emptyPanelTitle_ljth8_356",H4="_emptyPanelText_ljth8_362",G4="_sectionNote_ljth8_368",V4="_detailHero_ljth8_375",q4="_detailReferenceRow_ljth8_382",K4="_detailTitle_ljth8_389",Z4="_detailDescription_ljth8_396",Y4="_detailActionRow_ljth8_407",J4="_metricGrid_ljth8_414",Q4="_metricCard_ljth8_421",X4="_editorCard_ljth8_426",eF="_editorField_ljth8_433",tF="_editorLabel_ljth8_439",aF="_editorHint_ljth8_445",nF="_editorActions_ljth8_450",rF="_metricValue_ljth8_456",sF="_metricLabel_ljth8_463",oF="_progressTrack_ljth8_470",iF="_progressFill_ljth8_478",cF="_listCard_ljth8_484",lF="_activityTimelineList_ljth8_493",dF="_activityTimelineEmpty_ljth8_502",uF="_deferredPanelFallback_ljth8_506",mF="_sectionDropReady_ljth8_532",pF="_sectionDropActive_ljth8_537",fF="_sectionDropMode_ljth8_543",hF="_attachReferenceRow_ljth8_547",gF="_attachReferenceInput_ljth8_554",yF="_listItem_ljth8_559",kF="_listItemButton_ljth8_568",vF="_detailCardButton_ljth8_577",SF="_listItemText_ljth8_582",wF="_listItemTitle_ljth8_597",bF="_listItemMeta_ljth8_611",_F="_detailChildCard_ljth8_616",CF="_detailChildCardArchived_ljth8_628",AF="_detailChildCardTopRow_ljth8_633",xF="_detailChildReferenceRow_ljth8_642",IF="_taskStatusIcon_ljth8_649",Ae={drawerBody:i4,paneShell:c4,collapsedPaneShell:l4,collapsedPaneHeader:d4,collapsedPaneLabel:u4,treePane:m4,treePaneSplit:p4,detailPane:f4,paneHeader:h4,paneHeaderLabel:g4,paneContent:y4,sectionTitle:k4,sectionHeaderRow:v4,headerActionGroup:S4,toggleActive:w4,sectionGroup:b4,treeList:_4,treeChildren:C4,treeRow:A4,treeRowDetailOpen:x4,treeRowDropReady:I4,treeRowDropActive:T4,treeRowDropMode:R4,treeChevron:j4,rowButton:N4,detailsButton:P4,treeRowDragging:M4,treeChevronPlaceholder:E4,rowContent:D4,rowTopRow:L4,referenceBadgeButton:B4,referenceBadgeStatic:W4,rowTitle:F4,rowMeta:O4,detailsButtonActive:$4,emptyPanel:U4,emptyPanelTitle:z4,emptyPanelText:H4,sectionNote:G4,detailHero:V4,detailReferenceRow:q4,detailTitle:K4,detailDescription:Z4,detailActionRow:Y4,metricGrid:J4,metricCard:Q4,editorCard:X4,editorField:eF,editorLabel:tF,editorHint:aF,editorActions:nF,metricValue:rF,metricLabel:sF,progressTrack:oF,progressFill:iF,listCard:cF,activityTimelineList:lF,activityTimelineEmpty:dF,deferredPanelFallback:uF,sectionDropReady:mF,sectionDropActive:pF,sectionDropMode:fF,attachReferenceRow:hF,attachReferenceInput:gF,listItem:yF,listItemButton:kF,detailCardButton:vF,listItemText:SF,listItemTitle:wF,listItemMeta:bF,detailChildCard:_F,detailChildCardArchived:CF,detailChildCardTopRow:AF,detailChildReferenceRow:xF,taskStatusIcon:IF},TF="_header_c26na_1",RF="_title_c26na_31",jF="_icon_c26na_40",Cp={header:TF,title:RF,icon:jF};function NF({label:e,count:t,showZeroCount:n=!1,expanded:s,expandedTitle:o,collapsedTitle:l,onToggle:i,className:d=""}){const m=typeof t=="number"&&(n||t>0),y=s?tl:Jc;return a.jsxs("button",{type:"button",className:`${Cp.header} ${d}`.trim(),onClick:i,"aria-expanded":s,title:s?o:l,children:[a.jsxs("span",{className:Cp.title,children:[e,m?` (${t})`:""]}),a.jsx(y,{className:Cp.icon,size:14,"aria-hidden":"true"})]})}const PF=Fe.lazy(()=>vs(()=>import("./EntityActivityTimeline-sHk8Nzbq.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),MF=Fe.lazy(()=>vs(()=>import("./ContextAttachmentManager-DoMe2OpY.js"),__vite__mapDeps([8,1,9,2,3,4,5])).then(e=>({default:e.ContextAttachmentManager}))),dd=332,Qs=392,Ap=56;function Oy(e,t,n,s,o){return(e?Ap:dd)+(t?n?Ap:Qs:0)+(s?o?Ap:Qs:0)}function EF(e,t){const n=String(t||"").trim(),s=new Map;for(const o of e){const l=String(o?.value||"").trim();if(!l||l==="unassigned"||typeof o.archivedAt=="string"&&o.archivedAt.trim().length>0)continue;const i=String(o.label||l).trim()||l,d=String(o.kind||"").trim().toLowerCase(),m=String(o.username||"").trim().toLowerCase(),y=d==="agent"?`agent:${m||i.toLowerCase()}`:`value:${l}`;(!s.has(y)||l===n)&&s.set(y,{...o,value:l,label:i})}return Array.from(s.values()).sort((o,l)=>o.label.localeCompare(l.label,void 0,{sensitivity:"base"}))}function xp(e){return e?e.split(/[-_\s]+/g).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):"No status"}function ud({label:e,entityType:t,interactive:n=!0}){const[s,o]=Fe.useState(!1),l=Fe.useCallback(async i=>{i.stopPropagation();try{await navigator.clipboard.writeText(e),o(!0),window.setTimeout(()=>o(!1),1200)}catch{o(!1)}},[e]);return n?a.jsx(cy,{copied:s,label:e,onClick:l,title:`Copy ${t} reference`,ariaLabel:s?`Copied ${t} reference`:`Copy ${t} reference`,className:Ae.referenceBadgeButton,children:e}):a.jsx("span",{className:`${p.taskIdBadge} ${Ae.referenceBadgeStatic}`.trim(),children:a.jsx("span",{children:e})})}function Ip({rowId:e,rowType:t,referenceLabel:n,title:s,meta:o,active:l,detailOpen:i=!1,canExpand:d=!1,expanded:m=!1,onToggleExpand:y,onToggleScope:k,onToggleDetails:S}){const{active:h}=wg(),g=String(h?.data?.current?.type||""),v=t==="workstream"&&g==="task-card",A=t==="initiative"&&g==="planning-workstream",_=t==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:I,isOver:B}=af({id:`${_}:${e}`,data:t==="workstream"?{type:_,workstreamId:e}:{type:_,initiativeId:e}}),V=t==="workstream",{attributes:L,listeners:J,setNodeRef:me,transform:ve,isDragging:re}=mv({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!V}),x=V&&ve?{transform:tf.Translate.toString(ve)}:void 0,K=v||A;return a.jsxs("div",{ref:I,style:x,className:`${Ae.treeRow} ${i?Ae.treeRowDetailOpen:""} ${K?Ae.treeRowDropReady:""} ${B?Ae.treeRowDropActive:""} ${re?Ae.treeRowDragging:""} ${K?Ae.treeRowDropMode:""}`,children:[d?a.jsx("button",{type:"button",className:Ae.treeChevron,onClick:y,title:m?"Collapse workstreams":"Expand workstreams",children:m?a.jsx(tl,{size:15}):a.jsx(Jc,{size:15})}):a.jsx("span",{className:`${Ae.treeChevron} ${Ae.treeChevronPlaceholder}`,"aria-hidden":"true"}),a.jsxs("div",{className:Ae.rowContent,children:[a.jsxs("div",{className:Ae.rowTopRow,children:[n?a.jsx(ud,{label:n,entityType:t}):a.jsx("span",{"aria-hidden":"true"}),a.jsx("button",{type:"button",className:`${Ae.detailsButton} ${l?Ae.detailsButtonActive:""}`,onClick:k,title:l?"Clear board scope":"Scope board to this item",children:a.jsx(pg,{size:14})})]}),a.jsxs("button",{type:"button",ref:V?me:void 0,className:Ae.rowButton,onClick:S,...V?L:{},...V?J:{},children:[a.jsx("span",{className:Ae.rowTitle,children:s}),a.jsx("span",{className:Ae.rowMeta,children:o})]})]})]})}function Tp({label:e,onExpand:t}){return a.jsx("div",{className:`${Ae.paneShell} ${Ae.collapsedPaneShell}`.trim(),children:a.jsxs("div",{className:Ae.collapsedPaneHeader,children:[a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:`Expand ${e}`,children:a.jsx(Jc,{size:16})}),a.jsx("span",{className:Ae.collapsedPaneLabel,children:e})]})})}function Yh(){return a.jsxs("div",{className:Ae.deferredPanelFallback,"aria-hidden":"true",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}function DF({initiatives:e,standaloneWorkstreams:t,allStandaloneWorkstreams:n=t,activeInitiativeId:s,activeWorkstreamId:o,expandedInitiativeIds:l,detail:i,secondaryPane:d,onCreateInitiative:m,onCreateWorkstream:y,onToggleInitiative:k,onSelectInitiative:S,onSelectWorkstream:h,onOpenInitiativeDetails:g,onOpenWorkstreamDetails:v}){const[A,_]=Fe.useState(!1),I=Fe.useCallback(L=>{if(!A)return L.workstreams;const J=new Set(L.workstreams.map(ve=>ve.id)),me=(L.allWorkstreams||[]).filter(ve=>!!ve.isArchived&&!J.has(ve.id));return[...L.workstreams,...me]},[A]),B=Fe.useMemo(()=>{if(!A)return t;const L=new Set(t.map(me=>me.id)),J=n.filter(me=>!!me.isArchived&&!L.has(me.id));return[...t,...J]},[n,A,t]),V=Fe.useMemo(()=>{const L=e.reduce((me,ve)=>me+(ve.allWorkstreams||[]).filter(re=>!!re.isArchived).length,0),J=n.filter(me=>!!me.isArchived).length;return L+J},[n,e]);return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ae.sectionGroup,children:[a.jsxs("div",{className:Ae.sectionHeaderRow,children:[a.jsx("div",{className:Ae.sectionTitle,children:"Initiatives"}),a.jsxs("div",{className:Ae.headerActionGroup,children:[V>0?a.jsx("button",{type:"button",className:`tf-control-icon ${A?Ae.toggleActive:""}`.trim(),title:A?"Hide archived workstreams in tray":"Show archived workstreams in tray","aria-label":A?"Hide archived workstreams in tray":"Show archived workstreams in tray","aria-pressed":A,onClick:()=>_(L=>!L),children:A?a.jsx(ef,{size:15}):a.jsx(mg,{size:15})}):null,a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:m,children:a.jsx(to,{size:15})})]})]}),a.jsx("div",{className:Ae.treeList,children:e.length===0?a.jsxs("div",{className:Ae.emptyPanel,children:[a.jsx("div",{className:Ae.emptyPanelTitle,children:"No initiatives yet"}),a.jsxs("div",{className:Ae.emptyPanelText,children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",a.jsx("code",{children:"+"})," action above to create the first one."]})]}):e.map(L=>{const J=l.has(L.id),me=I(L),ve=L.workstreamCount||0,re=me.filter(ue=>!!ue.isArchived).length,K=`${A&&re>0?`${ve} workstreams + ${re} archived`:`${ve} workstreams`} • ${L.taskCount} tasks${L.isArchived?" • archived":""}`;return a.jsxs("div",{children:[a.jsx(Ip,{rowId:L.id,rowType:"initiative",referenceLabel:Jr(L),title:L.title,meta:K,active:s===L.id&&!o,detailOpen:i?.type==="initiative"&&i.item.id===L.id,canExpand:me.length>0,expanded:J,onToggleExpand:()=>k(L.id),onToggleScope:()=>S(L.id),onToggleDetails:()=>{if(i?.type==="initiative"&&i.item.id===L.id){g("");return}g(L.id)}}),J&&me.length>0&&a.jsx("div",{className:Ae.treeChildren,children:me.map(ue=>a.jsx(Ip,{rowId:ue.id,rowType:"workstream",referenceLabel:No(ue),title:ue.title,meta:`${ue.taskCount} tasks • ${ue.progressPercent}% complete${ue.isArchived?" • archived":""}`,active:o===ue.id,detailOpen:i?.type==="workstream"&&i.item.id===ue.id||d?.kind==="detail"&&d.detail.item.id===ue.id,onToggleScope:()=>h(ue.id,L.id),onToggleDetails:()=>{if(d?.kind==="detail"&&d.detail.item.id===ue.id){v("");return}if(i?.type==="workstream"&&i.item.id===ue.id){v("");return}v(ue.id)}},ue.id))})]},L.id)})})]}),a.jsxs("div",{className:Ae.sectionGroup,children:[a.jsxs("div",{className:Ae.sectionHeaderRow,children:[a.jsx("div",{className:Ae.sectionTitle,children:"Workstreams"}),a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:y,children:a.jsx(to,{size:15})})]}),a.jsx("div",{className:Ae.treeList,children:B.length===0?a.jsxs("div",{className:Ae.emptyPanel,children:[a.jsx("div",{className:Ae.emptyPanelTitle,children:"No standalone workstreams yet"}),a.jsxs("div",{className:Ae.emptyPanelText,children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",a.jsx("code",{children:"+"})," action above to add one."]})]}):B.map(L=>a.jsx(Ip,{rowId:L.id,rowType:"workstream",referenceLabel:No(L),title:L.title,meta:`${L.taskCount} tasks • ${L.progressPercent}% complete${L.isArchived?" • archived":""}`,active:o===L.id,detailOpen:i?.type==="workstream"&&i.item.id===L.id||d?.kind==="detail"&&d.detail.item.id===L.id,onToggleScope:()=>h(L.id,null),onToggleDetails:()=>{if(i?.type==="workstream"&&i.item.id===L.id){v("");return}v(L.id)}},L.id))})]})]})}function Jh({detail:e,currentWorkspaceId:t,onOpenNestedWorkstreamDetails:n,onEdit:s,onArchive:o,onUnarchive:l,onCreateTaskInWorkstream:i,onCreateWorkstreamInInitiative:d,onOpenTaskById:m,onRemoveTaskFromWorkstream:y,onAssignInitiativeToWorkstream:k,onAttachTaskToWorkstreamByReference:S,onAttachWorkstreamToInitiativeByReference:h,onAddPlanningContextFile:g,onRemovePlanningContextFile:v,onUpdatePlanningContextCaption:A,parentInitiative:_=null,assigneeOptions:I}){const[B,V]=Fe.useState(""),[L,J]=Fe.useState(!1),[me,ve]=Fe.useState(!0),{active:re}=wg(),x=String(re?.data?.current?.type||""),K=e.type==="workstream"&&x==="task-card",ue=e.type==="initiative"&&x==="planning-workstream",pe=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:X,isOver:M}=af({id:`${pe}:detail:${e.item.id}`,data:e.type==="initiative"?{type:pe,initiativeId:e.item.id}:{type:pe,workstreamId:e.item.id}}),O=e.type==="initiative"?"Workstreams":"Tasks",de=Fe.useMemo(()=>{if(e.type!=="initiative")return[];const P=new Set(e.item.workstreams.map(be=>be.id)),H=(e.item.allWorkstreams||[]).filter(be=>!!be.isArchived&&!P.has(be.id));return[...e.item.workstreams,...H]},[e.item,e.type]),ge=Fe.useMemo(()=>e.type!=="workstream"?[]:e.item.tasks||[],[e.item,e.type]),$=e.type==="initiative"?de.filter(P=>!!P.isArchived).length:ge.filter(P=>!!P.isArchived).length,_e=L?de:de.filter(P=>!P.isArchived),je=L?ge:ge.filter(P=>!P.isArchived),se=e.type==="initiative"?"Initiative":"Workstream",ce=e.type==="initiative"?Jr(e.item):No(e.item);Fe.useEffect(()=>{V(""),J(!1),ve(!0)},[e.item.id,e.type]);const Re=Fe.useCallback(()=>{const P=B.trim();P&&(e.type==="initiative"?h?.(e.item.id,P):S?.(e.item.id,P),V(""))},[B,e.item.id,e.type,S,h]),Pe=e.type==="initiative"?"Attach workstream to initiative":"Attach task to workstream",Ce=e.type==="initiative"?"archived workstreams":"archived tasks",Ee=e.type==="workstream"&&_?Jr(_):"",U=Fe.useMemo(()=>{const P=new Map;for(const H of I){const be=String(H.value||"").trim();be&&(P.set(be,H),P.set(be.toLowerCase(),H))}return P},[I]),T=Fe.useCallback((P,H,be)=>{if(be&&be.trim())return be.trim();const z=String(P||"").trim();if(!z)return H==="ai"?"AI Agent":"You";const ie=U.get(z)||U.get(z.toLowerCase());return ie?.label?ie.label:z},[U]),b=Fe.useCallback(P=>{const H=String(P.actorId||"").trim(),be=U.get(H)||U.get(H.toLowerCase()),z=P.actorProfile||be||null,ie=P.actorType==="system"?"system":P.actorType==="ai"||z?.kind==="ai"||be?.kind==="agent"?"agent":P.actorType==="human"||z?.kind==="human"||be?.kind==="member"?"member":P.fallbackKind||"member",ee=String(z&&"icon"in z&&z.icon?z.icon:ie==="agent"?"Bot":ie==="member"?"User":"ClipboardList"),Q=ec[ee]||(ie==="agent"?Zu:ie==="member"?ni:lg);return{kind:ie,label:ie==="system"?"System":T(H,ie==="agent"?"ai":"human",z&&"label"in z&&z.label||null),color:z&&"color"in z&&z.color||void 0,ActorIcon:Q}},[U,T]),j=Fe.useCallback((P,H)=>{const be=String(H||"").trim();if(be){if(P==="ownerId")return U.get(be)?.label||U.get(be.toLowerCase())?.label||be;if(P==="initiativeId"&&_&&be===_.id)return Jr(_)||_.title}},[U,_]),te=Fe.useMemo(()=>yy({activity:e.item.activity,comments:e.item.comments}),[e.item.activity,e.item.comments]).length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ae.detailHero,children:[ce?a.jsxs("div",{className:Ae.detailReferenceRow,children:[e.type==="workstream"?a.jsxs(a.Fragment,{children:[a.jsx(Ki,{onClick:P=>{if(P.stopPropagation(),Ee){k?.(e.item.id,null);return}s()},title:Ee?"Remove from initiative":"Attach to initiative",ariaLabel:Ee?"Remove from initiative":"Attach to initiative",children:Ee?a.jsx(Uu,{size:13}):a.jsx(Yu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),Ee?a.jsxs(a.Fragment,{children:[a.jsx(ud,{label:Ee,entityType:"initiative"}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}):null]}):null,a.jsx(ud,{label:ce,entityType:e.type})]}):null,a.jsx("h3",{className:Ae.detailTitle,children:e.item.title}),a.jsx("p",{className:Ae.detailDescription,children:e.item.description?.trim()||(e.type==="initiative"?"A top-level planning container that groups related workstreams.":"A coordination lane that groups related tasks and keeps execution organized.")}),a.jsx("div",{className:Ae.progressTrack,"aria-label":`${e.item.progressPercent}% complete`,children:a.jsx("div",{className:Ae.progressFill,style:{width:`${e.item.progressPercent}%`}})}),a.jsxs("div",{className:Ae.detailActionRow,children:[a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:s,children:a.jsxs("span",{children:["Edit ",se]})}),e.item.isArchived?a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:l,children:a.jsx("span",{children:"Unarchive"})}):a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:o,children:a.jsx("span",{children:"Archive"})})]})]}),a.jsxs("div",{className:Ae.metricGrid,children:[a.jsxs("div",{className:Ae.metricCard,children:[a.jsx("span",{className:Ae.metricValue,children:e.item.taskCount}),a.jsx("span",{className:Ae.metricLabel,children:"Tasks in scope"})]}),a.jsxs("div",{className:Ae.metricCard,children:[a.jsx("span",{className:Ae.metricValue,children:e.item.completedTaskCount}),a.jsx("span",{className:Ae.metricLabel,children:"Done / terminal"})]}),a.jsxs("div",{className:Ae.metricCard,children:[a.jsx("span",{className:Ae.metricValue,children:e.item.ownerLabel||"Unassigned"}),a.jsx("span",{className:Ae.metricLabel,children:"Owner"})]}),a.jsxs("div",{className:Ae.metricCard,children:[a.jsx("span",{className:Ae.metricValue,children:(e.item.commentCount||0)+(e.item.attachmentCount||0)}),a.jsx("span",{className:Ae.metricLabel,children:"Context items"})]})]}),a.jsxs("div",{ref:X,className:`${Ae.listCard} ${K||ue?Ae.sectionDropReady:""} ${M?Ae.sectionDropActive:""} ${K||ue?Ae.sectionDropMode:""}`.trim(),children:[a.jsxs("div",{className:Ae.sectionHeaderRow,children:[a.jsx("div",{className:Ae.sectionTitle,children:O}),a.jsxs("div",{className:Ae.headerActionGroup,children:[$>0?a.jsx("button",{type:"button",className:`tf-control-icon ${L?Ae.toggleActive:""}`.trim(),title:L?`Hide ${Ce}`:`Show ${Ce}`,"aria-label":L?`Hide ${Ce}`:`Show ${Ce}`,"aria-pressed":L,onClick:()=>J(P=>!P),children:L?a.jsx(ef,{size:15}):a.jsx(mg,{size:15})}):null,e.type==="initiative"?a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream in this initiative","aria-label":"Create workstream in this initiative",onClick:()=>d?.(e.item.id),children:a.jsx(to,{size:15})}):a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create task in this workstream","aria-label":"Create task in this workstream",onClick:()=>i?.(e.item.id),children:a.jsx(to,{size:15})})]})]}),a.jsxs("div",{className:Ae.attachReferenceRow,children:[a.jsx(Ki,{onClick:P=>{P.stopPropagation(),Re()},disabled:!B.trim(),title:Pe,ariaLabel:Pe,children:a.jsx(Yu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),a.jsx("input",{type:"text",className:`${p.input} ${Ae.attachReferenceInput}`.trim(),placeholder:e.type==="initiative"?"Paste workstream reference (e.g. WS-123)":"Paste task reference (e.g. T-123)",value:B,onChange:P=>V(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),Re())}})]}),e.type==="initiative"?_e.length>0?_e.map(P=>{const H=No(P),be=()=>n?.(P.id);return a.jsx("div",{className:`${Ae.listItemButton} ${Ae.detailCardButton}`.trim(),children:a.jsxs("div",{className:`${Ae.listItem} ${Ae.detailChildCard} ${P.isArchived?Ae.detailChildCardArchived:""}`.trim(),children:[a.jsx("div",{className:Ae.detailChildCardTopRow,children:a.jsxs("div",{className:Ae.detailChildReferenceRow,children:[a.jsx(Ki,{onClick:z=>{z.stopPropagation(),k?.(P.id,null)},title:"Remove from initiative",ariaLabel:"Remove from initiative",children:a.jsx(Uu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),H?a.jsx(ud,{label:H,entityType:"workstream"}):a.jsx("span",{"aria-hidden":"true"})]})}),a.jsxs("div",{role:"button",tabIndex:0,className:Ae.listItemText,onClick:be,onKeyDown:z=>{z.key!=="Enter"&&z.key!==" "||(z.preventDefault(),be())},children:[a.jsx("span",{className:Ae.listItemTitle,children:P.title}),a.jsxs("span",{className:Ae.listItemMeta,children:[P.taskCount," tasks • ",P.progressPercent,"% complete",P.isArchived?" • archived":""]})]})]})},P.id)}):a.jsxs("div",{className:Ae.emptyPanel,children:[a.jsx("div",{className:Ae.emptyPanelTitle,children:"No workstreams yet"}),a.jsx("div",{className:Ae.emptyPanelText,children:"Add the first workstream to break the initiative into clearer lanes of execution."})]}):je.length>0?[...je].sort((P,H)=>{const be=hd(P.status).value==="done",z=hd(H.status).value==="done";return be===z?0:be?1:-1}).map(P=>{const H=P.referenceNumber?`T-${P.referenceNumber}`:"",be=hd(P.status),z=ec[be.icon||"Square"],ie=Nn(be.color)||"var(--text-secondary)",ee=()=>m?.(P.id),Q=`${xp(P.status)}${P.isArchived?" • archived":""}`;return a.jsx("div",{className:`${Ae.listItemButton} ${Ae.detailCardButton}`.trim(),children:a.jsxs("div",{className:`${Ae.listItem} ${Ae.detailChildCard} ${P.isArchived?Ae.detailChildCardArchived:""}`.trim(),children:[a.jsxs("div",{className:Ae.detailChildCardTopRow,children:[a.jsxs("div",{className:Ae.detailChildReferenceRow,children:[a.jsx(Ki,{onClick:q=>{q.stopPropagation(),y?.(P.id,e.item.id)},title:"Remove from workstream",ariaLabel:"Remove from workstream",children:a.jsx(Uu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"}),H?a.jsx(ud,{label:H,entityType:"task"}):a.jsx("span",{"aria-hidden":"true"})]}),a.jsx("span",{className:Ae.taskStatusIcon,style:{color:ie},"aria-label":be.shortLabel||xp(P.status),title:be.shortLabel||xp(P.status),children:z?a.jsx(z,{size:18,strokeWidth:2.4}):null})]}),a.jsxs("div",{role:"button",tabIndex:0,className:Ae.listItemText,onClick:ee,onKeyDown:q=>{q.key!=="Enter"&&q.key!==" "||(q.preventDefault(),ee())},children:[a.jsx("span",{className:Ae.listItemTitle,children:P.title}),a.jsx("span",{className:Ae.listItemMeta,children:Q})]})]})},P.id)}):a.jsxs("div",{className:Ae.sectionNote,children:["No tasks are linked to this workstream yet. Use the ",a.jsx("code",{children:"+"})," action above to add the first one."]})]}),a.jsx("div",{className:Ae.listCard,children:a.jsx(Fe.Suspense,{fallback:a.jsx(Yh,{}),children:a.jsx(MF,{ownerType:e.type,ownerId:e.item.id,ownerReferenceLabel:ce,workspaceId:t,attachments:e.item.attachments||[],onAddAttachment:P=>g?.(e.type,e.item.id,P),onRemoveAttachment:P=>v?.(e.type,e.item.id,P),onUpdateAttachmentCaption:(P,H)=>A?.(e.type,e.item.id,P,H)})})}),a.jsxs("div",{className:Ae.listCard,children:[a.jsx(NF,{label:"Recent Activity",count:te,showZeroCount:!0,expanded:me,expandedTitle:"Hide recent activity",collapsedTitle:"Show recent activity",onToggle:()=>ve(P=>!P)}),me?a.jsx(Fe.Suspense,{fallback:a.jsx(Yh,{}),children:a.jsx(PF,{activity:e.item.activity,comments:e.item.comments,formatFieldValue:j,resolveActorPresentation:b,onOpenTaskById:m,emptyMessage:`No ${e.type} activity yet.`,listClassName:Ae.activityTimelineList,emptyClassName:Ae.activityTimelineEmpty})}):null]})]})}function Qh({editor:e,draftTitle:t,draftDescription:n,draftOwner:s,draftInitiativeId:o,assigneeOptions:l,draftInitiativeSummary:i,onChangeDraftTitle:d,onChangeDraftDescription:m,onChangeDraftOwner:y,onChangeDraftInitiativeId:k,onCancel:S,onSubmit:h,isSubmitting:g,onAssignInitiativeToWorkstream:v}){const A=e.entityType==="initiative"?"Initiative":"Workstream",_=g?e.mode==="create"?`Creating ${A}...`:`Saving ${A}...`:e.mode==="create"?`Create ${A}`:`Save ${A}`,I=Fe.useMemo(()=>EF(l,s),[l,s]),B=Fe.useCallback(L=>{L.preventDefault(),h()},[h]),V=Fe.useCallback(()=>{e.mode!=="edit"||e.entityType!=="workstream"||v?.(e.targetId)},[e,v]);return a.jsxs("form",{className:Ae.editorCard,onSubmit:B,children:[a.jsxs("div",{className:Ae.editorField,children:[a.jsx("label",{className:Ae.editorLabel,children:"Title"}),a.jsx("input",{className:p.input,disabled:g,value:t,onChange:L=>d(L.target.value),placeholder:e.entityType==="initiative"?"Q3 Product Launch":"Content Production"})]}),a.jsxs("div",{className:Ae.editorField,children:[a.jsx("label",{className:Ae.editorLabel,children:"Description"}),a.jsx("textarea",{className:p.textarea,disabled:g,value:n,onChange:L=>m(L.target.value),placeholder:e.entityType==="initiative"?"Describe the broader outcome this initiative is meant to achieve.":"Describe the lane of work this workstream will coordinate.",rows:5})]}),e.entityType==="workstream"&&a.jsxs("div",{className:Ae.editorField,children:[a.jsx("label",{className:Ae.editorLabel,children:"Initiative"}),i&&a.jsxs("div",{className:Ae.editorHint,children:["Current: ",i.title]}),a.jsxs("div",{className:Ae.attachReferenceRow,children:[e.mode==="edit"&&a.jsxs(a.Fragment,{children:[a.jsx(Ki,{onClick:L=>{L.stopPropagation(),V()},disabled:g||!o.trim(),title:"Attach workstream to initiative",ariaLabel:"Attach workstream to initiative",children:a.jsx(Yu,{size:13})}),a.jsx("span",{className:p.taskHierarchyDivider,children:"/"})]}),a.jsx("input",{type:"text",className:`${p.input} ${Ae.attachReferenceInput}`.trim(),disabled:g,placeholder:"Paste initiative reference (e.g. IN-123)",value:o,onChange:L=>k(L.target.value),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),V())}})]})]}),a.jsxs("div",{className:Ae.editorField,children:[a.jsx("label",{className:Ae.editorLabel,children:"Owner"}),a.jsxs("select",{className:`${p.select} ${p.groupBySelect}`,disabled:g,value:s,onChange:L=>y(L.target.value),children:[a.jsx("option",{value:"",children:"Unassigned"}),I.map(L=>a.jsx("option",{value:L.value,children:L.label},L.value))]})]}),a.jsxs("div",{className:Ae.editorActions,children:[a.jsx("button",{type:"button",className:p.secondaryHeaderBtn,onClick:S,disabled:g,children:"Cancel"}),a.jsx("button",{type:"submit",className:p.primaryUpdateBtn,disabled:g,children:_})]})]})}function LF({open:e,leftOffset:t=0,initiatives:n,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:l,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,editor:y,secondaryPane:k,currentWorkspaceId:S,assigneeOptions:h,draftInitiativeSummary:g,draftTitle:v,draftDescription:A,draftOwner:_,draftInitiativeId:I,onChangeDraftTitle:B,onChangeDraftDescription:V,onChangeDraftOwner:L,onChangeDraftInitiativeId:J,onCollapseTreePane:me,onExpandTreePane:ve,onCollapsePrimaryPane:re,onExpandPrimaryPane:x,onCollapseSecondaryPane:K,onExpandSecondaryPane:ue,onBackFromSecondary:pe,treeCollapsed:X,primaryCollapsed:M,secondaryCollapsed:O,onCancelEditor:de,onSubmitEditor:ge,isSubmittingEditor:$,onCreateInitiative:_e,onCreateWorkstream:je,onToggleInitiative:se,onSelectInitiative:ce,onSelectWorkstream:Re,onOpenInitiativeDetails:Pe,onOpenWorkstreamDetails:Ce,onOpenNestedWorkstreamDetails:Ee,onEditInitiative:U,onEditWorkstream:T,onArchiveInitiative:b,onUnarchiveInitiative:j,onArchiveWorkstream:D,onUnarchiveWorkstream:te,onCreateTaskInWorkstream:P,onCreateWorkstreamInInitiative:H,onAssignInitiativeToWorkstream:be,onOpenTaskById:z,onRemoveTaskFromWorkstream:ie,onAttachTaskToWorkstreamByReference:ee,onAttachWorkstreamToInitiativeByReference:Q,onAddPlanningContextFile:q,onRemovePlanningContextFile:Se,onUpdatePlanningContextCaption:we}){const Te=!!(m||y),Me=!!k,nt=Oy(X,Te,M,Me,O),gt=y?y.entityType==="initiative"?y.mode==="create"?"New Initiative":"Edit Initiative":y.mode==="create"?"New Workstream":"Edit Workstream":m?.type==="initiative"?"Initiative":"Workstream",lt=k?.kind==="editor"?k.editor.mode==="create"?"New Workstream":"Edit Workstream":"Workstream",St=Fe.useCallback(Ke=>{const Ct=String(Ke.initiativeId||"").trim();return Ct&&n.find(dt=>dt.id===Ct)||null},[n]);return a.jsx("aside",{style:{position:"absolute",top:0,left:e?`${t}px`:`${t-nt-24}px`,bottom:0,width:`${nt}px`,minWidth:`${nt}px`,borderRight:"1px solid var(--border-color)",background:"var(--bg-secondary)",boxSizing:"border-box",display:"flex",flexDirection:"column",zIndex:35,overflow:"hidden",pointerEvents:e?"auto":"none",transition:"left 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"left"},children:a.jsxs("div",{className:Ae.drawerBody,children:[X?a.jsx(Tp,{label:"Planning",onExpand:ve}):a.jsxs("div",{className:`${Ae.paneShell} ${p.appScrollbar} tf-scrollbar ${Ae.treePane} ${Te&&!M?Ae.treePaneSplit:""}`.trim(),style:{flex:`0 0 ${dd}px`,width:`${dd}px`,minWidth:`${dd}px`,maxWidth:`${dd}px`},children:[a.jsxs("div",{className:Ae.paneHeader,children:[a.jsx("span",{className:Ae.paneHeaderLabel,children:"Planning"}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:me,children:a.jsx(jo,{size:16})})]}),a.jsx("div",{className:Ae.paneContent,children:a.jsx(DF,{initiatives:n,standaloneWorkstreams:s,allStandaloneWorkstreams:o,activeInitiativeId:l,activeWorkstreamId:i,expandedInitiativeIds:d,detail:m,secondaryPane:k,onCreateInitiative:_e,onCreateWorkstream:je,onToggleInitiative:se,onSelectInitiative:ce,onSelectWorkstream:Re,onOpenInitiativeDetails:Pe,onOpenWorkstreamDetails:Ce})})]}),Te&&(M?a.jsx(Tp,{label:gt,onExpand:x}):a.jsxs("div",{className:`${Ae.paneShell} ${p.appScrollbar} tf-scrollbar ${Ae.detailPane}`.trim(),style:{flex:`0 0 ${Qs}px`,width:`${Qs}px`,minWidth:`${Qs}px`,maxWidth:`${Qs}px`},children:[a.jsxs("div",{className:Ae.paneHeader,children:[a.jsx("span",{className:Ae.paneHeaderLabel,children:gt}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:re,children:a.jsx(jo,{size:16})})]}),a.jsx("div",{className:Ae.paneContent,children:y?a.jsx(Qh,{editor:y,draftTitle:v,draftDescription:A,draftOwner:_,draftInitiativeId:I,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:B,onChangeDraftDescription:V,onChangeDraftOwner:L,onChangeDraftInitiativeId:J,onCancel:de,onSubmit:ge,isSubmitting:$,onAssignInitiativeToWorkstream:be}):m?a.jsx(Jh,{detail:m,currentWorkspaceId:S,assigneeOptions:h,onOpenNestedWorkstreamDetails:m.type==="initiative"?Ee:void 0,onCreateTaskInWorkstream:m.type==="workstream"?P:void 0,onCreateWorkstreamInInitiative:m.type==="initiative"?H:void 0,onOpenTaskById:m.type==="workstream"?z:void 0,onRemoveTaskFromWorkstream:m.type==="workstream"?ie:void 0,onAssignInitiativeToWorkstream:be,onAttachTaskToWorkstreamByReference:m.type==="workstream"?ee:void 0,onAttachWorkstreamToInitiativeByReference:m.type==="initiative"?Q:void 0,parentInitiative:m.type==="workstream"?St(m.item):null,onEdit:()=>m.type==="initiative"?U(m.item.id):T(m.item.id),onArchive:()=>m.type==="initiative"?b(m.item.id):D(m.item.id),onUnarchive:()=>m.type==="initiative"?j(m.item.id):te(m.item.id),onAddPlanningContextFile:q,onRemovePlanningContextFile:Se,onUpdatePlanningContextCaption:we}):null})]})),Me&&(O?a.jsx(Tp,{label:lt,onExpand:ue}):a.jsxs("div",{className:`${Ae.paneShell} ${p.appScrollbar} tf-scrollbar ${Ae.detailPane}`.trim(),style:{flex:`0 0 ${Qs}px`,width:`${Qs}px`,minWidth:`${Qs}px`,maxWidth:`${Qs}px`},children:[a.jsxs("div",{className:Ae.paneHeader,children:[a.jsx("span",{className:Ae.paneHeaderLabel,children:lt}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:K,children:a.jsx(jo,{size:16})})]}),a.jsx("div",{className:Ae.paneContent,children:k?.kind==="editor"?a.jsx(Qh,{editor:k.editor,draftTitle:v,draftDescription:A,draftOwner:_,draftInitiativeId:I,assigneeOptions:h,draftInitiativeSummary:g,onChangeDraftTitle:B,onChangeDraftDescription:V,onChangeDraftOwner:L,onChangeDraftInitiativeId:J,onCancel:pe,onSubmit:ge,isSubmitting:$,onAssignInitiativeToWorkstream:be}):k?a.jsx(Jh,{detail:k.detail,currentWorkspaceId:S,assigneeOptions:h,onCreateTaskInWorkstream:P,onOpenTaskById:z,onRemoveTaskFromWorkstream:ie,onAssignInitiativeToWorkstream:be,onAttachTaskToWorkstreamByReference:ee,parentInitiative:St(k.detail.item),onEdit:()=>T(k.detail.item.id),onArchive:()=>D(k.detail.item.id),onUnarchive:()=>te(k.detail.item.id),onAddPlanningContextFile:q,onRemovePlanningContextFile:Se,onUpdatePlanningContextCaption:we}):null})]}))]})})}const BF={"annotated_attachments.workspace_access":{enabled:!0,description:"Annotated Attachment workspace readiness gate.",owner:"taskforce",removalMilestone:"Annotated Attachment GA"},"documents.workspace_access":{enabled:!0,description:"Document Manager/editor workspace readiness gate.",owner:"taskforce",removalMilestone:"Document Manager GA"},"workflows.workspace_access":{enabled:!1,description:"Workflow workspace readiness gate.",owner:"taskforce",removalMilestone:"Workflow workspace GA"},"agents.workspace_access":{enabled:!0,description:"Agents workspace readiness gate.",owner:"taskforce",removalMilestone:"Agents workspace GA"},"initiatives.workspace_access":{enabled:!0,description:"Initiatives workspace readiness gate.",owner:"taskforce",removalMilestone:"Initiatives workspace GA"}},gd="annotated_attachments.workspace_access",yd="documents.workspace_access",fm="workflows.workspace_access",hm="agents.workspace_access",Xh="initiatives.workspace_access",WF=Object.entries(BF).reduce((e,[t,n])=>(e[t]={key:t,enabled:!!n.enabled,description:String(n.description||""),owner:String(n.owner||""),removalMilestone:String(n.removalMilestone||"")},e),{});function FF(e){const t=String(e||"").trim();return t&&WF[t]||null}function OF(e){const t=FF(e);return t?t.enabled?{featureKey:e,allowed:!0,source:"app_gate",code:"OK"}:{featureKey:e,allowed:!1,source:"app_gate",code:"APP_GATE_DISABLED"}:{featureKey:e,allowed:!0,source:"none",code:"OK"}}function rd(e){return OF(e.featureKey)}const $F=["tasks","docs","annotate","workflows","agents"];function UF(e){const t=e?.featureAccess||{},n={tasks:{id:"tasks",label:"Tasks",featureKey:null,enabled:!0,fallbackModuleId:"tasks"},docs:{id:"docs",label:"Documents",featureKey:yd,enabled:t[yd]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:"Image Notes",featureKey:gd,enabled:t[gd]?.allowed??!1,fallbackModuleId:"tasks"},workflows:{id:"workflows",label:"Workflows",featureKey:fm,enabled:t[fm]?.allowed??!1,fallbackModuleId:"tasks"},agents:{id:"agents",label:"Agents",featureKey:hm,enabled:t[hm]?.allowed??!1,fallbackModuleId:"tasks"}};return $F.map(s=>n[s])}function zF(e){switch(e){case"docs":return{mode:e,moduleId:"docs",layoutVariant:"docs-minimal",headerSections:[],filterBar:{kind:"document-filters"},primaryAction:null};case"annotate":return{mode:e,moduleId:"annotate",layoutVariant:"annotated-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};case"workflows":return{mode:e,moduleId:"workflows",layoutVariant:"workflows-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};case"agents":return{mode:e,moduleId:"agents",layoutVariant:"agents-module",headerSections:[],filterBar:{kind:"empty"},primaryAction:null};default:return{mode:"tasks",moduleId:"tasks",layoutVariant:"tasks-default",headerSections:["search","sort","divider-primary","grouping","divider-secondary","task-display-actions"],filterBar:{kind:"task-filters"},primaryAction:"add-task"}}}function eg(e,t){const n=t.find(s=>s.id===e);return n?n.enabled?n.id:n.fallbackModuleId:"tasks"}const HF="_weekLabel_vet2o_1",GF="_sectionTitle_vet2o_6",VF="_calendarHeader_vet2o_11",qF="_monthLabel_vet2o_18",KF="_weekdayGrid_vet2o_23",ZF="_weekdayLabel_vet2o_30",YF="_calendarGrid_vet2o_36",JF="_calendarDay_vet2o_42",QF="_calendarDayDot_vet2o_55",XF="_jumpRow_vet2o_67",eO="_displaySection_vet2o_73",tO="_toggleLabel_vet2o_79",aO="_expiredSummary_vet2o_87",nO="_actionButton_vet2o_95",$n={weekLabel:HF,sectionTitle:GF,calendarHeader:VF,monthLabel:qF,weekdayGrid:KF,weekdayLabel:ZF,calendarGrid:YF,calendarDay:JF,calendarDayDot:QF,jumpRow:XF,displaySection:eO,toggleLabel:tO,expiredSummary:aO,actionButton:nO},tg=["mon","tue","wed","thu","fri","sat","sun"],rO={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function Zc(e){const t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${s}`}function md(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}function Yp(e,t){const n=e.getDay(),s=t==="sunday"?-n:n===0?-6:1-n,o=new Date(e);return o.setHours(0,0,0,0),o.setDate(o.getDate()+s),o}function sO(e,t){return t==="sunday"?{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}[e]:{mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6}[e]}function $y(e,t){const n=new Date(e);return n.setDate(e.getDate()+t),n}function oO(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))),s=n.getUTCDay()||7;n.setUTCDate(n.getUTCDate()+4-s);const o=new Date(Date.UTC(n.getUTCFullYear(),0,1)),l=Math.ceil(((n.getTime()-o.getTime())/864e5+1)/7);return`${n.getUTCFullYear()}-W${String(l).padStart(2,"0")}`}const Jp=320;function iO({open:e,onClose:t,scheduleSelectedDate:n,setScheduleSelectedDate:s,scheduleCalendarMonth:o,setScheduleCalendarMonth:l,scheduleShowWeekends:i,setScheduleShowWeekends:d,scheduleShowBacklog:m,setScheduleShowBacklog:y,scheduleOnlyExpired:k,setScheduleOnlyExpired:S,expiredScheduledCount:h,overdueDueCount:g,expiredLeafCandidates:v,expiredRecoveryCandidates:A,onMoveExpiredToSelectedWeek:_,onMoveExpiredToBacklog:I,scheduleBulkBusy:B,globalWeekStartsOn:V,resolvedLocale:L,todayDateOnly:J,scheduleBaseTasks:me,scheduleWeekStart:ve,scheduleWeekLabel:re}){const x=Fe.useMemo(()=>{const[M,O]=o.split("-"),de=Number(M),ge=Number(O);if(!Number.isInteger(de)||!Number.isInteger(ge)||ge<1||ge>12){const $=md(n)||new Date;return new Date($.getFullYear(),$.getMonth(),1)}return new Date(de,ge-1,1)},[o,n]),K=Fe.useMemo(()=>mm(x,{month:"long",year:"numeric"},L),[x,L]),ue=Fe.useMemo(()=>{const M=Yp(x,V);return Array.from({length:42},(O,de)=>$y(M,de))},[x,V]),pe=Fe.useMemo(()=>{const M=new Map;for(const O of me){const de=O.scheduledDate||"";if(!de)continue;const $=!(O.status==="done"||O.status==="cancelled")&&de<J,_e=M.get(de);_e?(_e.count+=1,$&&(_e.hasExpired=!0)):M.set(de,{count:1,hasExpired:$})}return M},[me,J]),X=Fe.useMemo(()=>V==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[V]);return a.jsxs("aside",{className:`${p.appScrollbar} tf-scrollbar tf-sidebar-shell`,style:{transform:e?"translateX(0)":"translateX(108%)",pointerEvents:e?"auto":"none",transition:"transform 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform",width:`${Jp}px`,minWidth:`${Jp}px`},children:[a.jsxs("div",{className:"tf-sidebar-header",children:[a.jsxs("div",{className:"tf-sidebar-title",children:[a.jsx(Uk,{size:16}),a.jsx("span",{children:"Schedule Controls"})]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:"Hide Schedule Sidebar",children:a.jsx(Jc,{size:16})})]}),a.jsxs("div",{className:$n.weekLabel,children:["Week of ",re]}),a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsxs("div",{className:$n.calendarHeader,children:[a.jsx("button",{className:"tf-control-icon",onClick:()=>{const M=new Date(x);M.setMonth(x.getMonth()-1),l(`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:a.jsx(jo,{size:14})}),a.jsx("div",{className:$n.monthLabel,children:K}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{const M=new Date(x);M.setMonth(x.getMonth()+1),l(`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:a.jsx(Jc,{size:14})})]}),a.jsx("div",{className:$n.weekdayGrid,children:X.map(M=>a.jsx("div",{className:$n.weekdayLabel,children:M},M))}),a.jsx("div",{className:$n.calendarGrid,children:ue.map(M=>{const O=Zc(M),de=M.getMonth()!==x.getMonth(),ge=Yp(M,V),$=Zc(ge)===Zc(ve),_e=O===n,je=O===J,se=O<J,ce=pe.get(O),Re=!!ce,Pe=!!ce?.hasExpired;return a.jsxs("button",{onClick:()=>{s(O),l(`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}`)},className:$n.calendarDay,style:{"--calendar-day-border":_e?"1px solid #2563eb":je?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":_e?"rgba(59,130,246,0.22)":je?"rgba(245,158,11,0.16)":$?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":de?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":_e||je?700:500,"--calendar-day-opacity":se?.42:1},title:`${je?`${O} (Today)`:O}`+(Re?` • ${ce?.count} scheduled`:"")+(Pe?" • includes expired":""),children:[M.getDate(),Re&&a.jsx("span",{className:$n.calendarDayDot,style:{"--calendar-dot-background":Pe?"#ef4444":"#3b82f6","--calendar-dot-opacity":de?.6:.95}})]},O)})}),a.jsx("div",{className:$n.jumpRow,children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{const M=new Date;s(Zc(M)),l(`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),a.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${$n.displaySection}`,children:[a.jsx("div",{className:$n.sectionTitle,children:"Display"}),a.jsxs("label",{className:$n.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:i,onChange:M=>d(M.target.checked)}),"Show weekends"]}),a.jsxs("label",{className:$n.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:m,onChange:M=>y(M.target.checked)}),"Show backlog"]}),a.jsxs("label",{className:$n.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:k,onChange:M=>S(M.target.checked)}),"Only expired/overdue"]})]}),h>0&&a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsx("div",{className:$n.sectionTitle,children:"Expired Tasks"}),a.jsxs("div",{className:$n.expiredSummary,children:[a.jsxs("span",{children:[h," expired"]}),a.jsxs("span",{children:[g," overdue"]})]}),a.jsx("button",{className:`tf-control-icon ${$n.actionButton}`,onClick:_,disabled:B||v.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:B?"Working...":"Schedule to selected week"}),a.jsx("button",{className:`tf-control-icon ${$n.actionButton}`,onClick:I,disabled:B||A.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:B?"Working...":"Unschedule to backlog"})]})]})}function Uy(e,t){return e&&(t==="owner"||t==="admin")}function cO(e,t,n){return Uy(e,t)&&n==="team"}function lO({isOpen:e,workspaceId:t,refreshKeys:n}){const[s,o]=r.useState([]),[l,i]=r.useState(!1),[d,m]=r.useState(null),y=r.useRef(null),k=r.useRef(null);r.useLayoutEffect(()=>{k.current=uO(y.current,k.current)},[s]);const S=r.useCallback(async()=>{const h=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(t)}&limit=15`,{method:"GET",credentials:"include"});if(!h.ok)throw new Error(`Failed to load sync events (${h.status})`);const g=await h.json().catch(()=>({}));return Array.isArray(g?.events)?g.events.filter(v=>v&&typeof v=="object"):[]},[t]);return r.useEffect(()=>{if(!e)return;let h=!1;const g=s.length===0;return g&&i(!0),S().then(v=>{h||(k.current=dO(y.current),o(A=>{const _=A.length===0?v:NW(A,v,15);return PW(A,_)?A:_}),m(null))}).catch(v=>{if(h)return;const A=v instanceof Error&&v.message.trim().length>0?v.message.trim():"Unable to load recent sync events.";m(A),g&&o([])}).finally(()=>{h||g&&i(!1)}),()=>{h=!0}},[e,S,...n]),{syncRecentEvents:s,syncRecentEventsLoading:l,syncRecentEventsError:d,syncEventsListRef:y,loadRecentSyncEvents:S}}function dO(e){return e&&e.scrollTop>8?{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight}:null}function uO(e,t){if(!t||!e)return null;const n=e.scrollHeight-t.scrollHeight;return e.scrollTop=t.scrollTop+Math.max(0,n),null}function mO({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,workspaceSyncPhase:k,referenceMismatchCount:S,syncRecentEvents:h,loadRecentSyncEvents:g,pushNotice:v,resetWorkspaceSyncCursorAndPull:A,workspaceSyncBusy:_}){const[I,B]=r.useState(!1),[V,L]=r.useState(!1),[J,me]=r.useState(!1),ve=r.useCallback(async()=>{try{const K=h.length>0?h:await g(),ue=WW({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:n,workspaceSyncRecommendedAction:s,formattedLastSyncTime:o,formattedLastPullTime:l,formattedLastPushTime:i,workspaceSyncDiagnostics:d,workspaceSyncPendingChanges:m,syncLastError:y,syncStageLabel:Ly(k,I,_),referenceMismatchCount:S,syncRecentEvents:K});await navigator.clipboard.writeText(ue),me(!0),window.setTimeout(()=>{me(!1)},1800),v("Sync details copied to clipboard.","success")}catch{me(!1),v("Failed to copy sync details.","error")}},[e,l,i,o,g,v,S,y,h,t,d,k,m,s,n,_,I]),re=r.useCallback(async()=>{L(!1),B(!0);try{await A()}finally{B(!1)}},[A]),x=r.useCallback(()=>{if(!I){if(_){L(!0);return}re()}},[re,_,I]);return r.useEffect(()=>{V&&(_||I||re())},[re,_,I,V]),{workspaceSyncRepairBusy:I,workspaceSyncRepairQueued:V,workspaceSyncCopied:J,handleCopySyncDetails:ve,handleQueueOrRunRepairSync:x}}function pO({canManageWorkspaceSync:e,workspaceCloudSyncEnabled:t,saveWorkspaceCloudSyncSettings:n}){const[s,o]=r.useState(!1),[l,i]=r.useState(!1),[d,m]=r.useState(!1),[y,k]=r.useState(null),S=r.useCallback(async I=>{if(e){k(null),m(!0);try{const B=await n({enabled:I});B.success||k(B.error||(I?"Failed to enable sync.":"Failed to disable sync."))}finally{m(!1)}}},[e,n]),h=r.useCallback(async I=>{if(I&&!t){i(!0);return}await S(I)},[S,t]),g=r.useCallback(()=>{i(!1)},[]),v=r.useCallback(()=>{i(!1),S(!0)},[S]),A=r.useCallback(()=>{o(!0)},[]),_=r.useCallback(()=>{o(!1)},[]);return{showSyncStatusModal:s,showSyncEnableWarning:l,workspaceSyncToggleBusy:d,workspaceSyncError:y,syncControlBusy:d,openSyncStatusModal:A,closeSyncStatusModal:_,handleWorkspaceSyncToggle:h,cancelSyncEnableWarning:g,confirmSyncEnableWarning:v}}const ag=Fe.lazy(()=>vs(()=>import("./TaskSettings-DM1o9Wla.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings}))),fO=Fe.lazy(()=>vs(()=>import("./AnnotatedAttachmentWorkspace-DHr4rHK9.js"),__vite__mapDeps([12,1,2,3,4,5,13])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),hO=Fe.lazy(()=>vs(()=>import("./DocumentWorkspace-DumBWhvb.js"),__vite__mapDeps([14,1,2,9,3,4,5,15])).then(e=>({default:e.DocumentWorkspaceShell}))),gO=Fe.lazy(()=>vs(()=>import("./WorkflowsModule-CW0crzvD.js"),__vite__mapDeps([16,1,2,3,4,5])).then(e=>({default:e.WorkflowsModule}))),yO=Fe.lazy(()=>vs(()=>import("./AgentsModule-BULqIo8e.js"),__vite__mapDeps([17,1,2,3,4,5])).then(e=>({default:e.AgentsModule})));Fe.lazy(()=>vs(()=>import("./InitiativesModule-3X9UNzHh.js"),__vite__mapDeps([18,1,2,3,4,5])).then(e=>({default:e.InitiativesModule})));const kO=Fe.lazy(()=>vs(()=>import("./PlansPage-C3A3EYaV.js"),__vite__mapDeps([19,1,2,5,3,4,20])).then(e=>({default:e.PlansPage}))),vO="image/png,image/jpeg,image/webp,image/gif",SO=5*1024*1024,wO=e=>e;function bO(e,t){const n=vm(e);if(n)return Xf(n).label.toUpperCase();for(const s of t){const o=String(s||"").trim();if(!o)continue;const l=cf(o);if(l)return Xf(l).label.toUpperCase();let i=o.toLowerCase();try{i=new URL(o.includes("://")?o:`https://${o}`).hostname.toLowerCase()}catch{i=o.toLowerCase()}if(!(i.includes("localhost")||i.includes("127.0.0.1")||i.includes("::1")))return i.toUpperCase()}return"UNKNOWN"}function sd(){return typeof performance<"u"?performance.now():Date.now()}function _O(e){const s=bg(),o=_g(),l=r.useMemo(()=>new URLSearchParams(o.search),[o.search]),i=String(l.get("screen")||"").trim().toLowerCase()==="plans",d=r.useCallback(u=>{const w=new URLSearchParams(o.search);w.set("screen","plans");for(const[N,le]of Object.entries(u||{}))le==null||String(le).trim()===""?w.delete(N):w.set(N,String(le));s(`/?${w.toString()}${o.hash||""}`)},[o.hash,o.search,s]),m=r.useCallback(()=>{const u=new URLSearchParams(o.search);u.delete("screen"),u.delete("gate"),u.delete("checkout"),u.delete("planId"),u.delete("planVersionId"),u.delete("interval");const w=u.toString();s(`${o.pathname==="/"?"/":o.pathname}${w?`?${w}`:""}${o.hash||""}`)},[o.hash,o.pathname,o.search,s]),{activeTab:y,setActiveTab:k,activeCategories:S,groupBy:h,setGroupBy:g,activeWorkspaceModule:v,setActiveWorkspaceModule:A,emptyColumnMode:_,setEmptyColumnMode:I,zenMode:B,setZenMode:V,filterStatus:L,setFilterStatus:J,tasks:me,handleEdit:ve,handleSubmit:re,resetForm:x,handleUpdateTask:K,editingTaskId:ue,loading:pe,error:X,title:M,setTitle:O,description:de,setDescription:ge,checklistItems:$,setChecklistItems:_e,category:je,setCategory:se,type:ce,setType:Re,priority:Pe,setPriority:Ce,complexity:Ee,setComplexity:U,setStatus:T,approach:b,setApproach:j,assignee:D,setAssignee:te,scheduledDate:P,setScheduledDate:H,dueDate:be,setDueDate:z,workstreamInput:ie,setWorkstreamInput:ee,manualComplexityEnabled:Q,checklistDropdownEnabled:q,showTaskCardStatusLabel:Se,formTaxonomies:we,setFormTaxonomies:Te,comments:Me,newCommentText:nt,setNewCommentText:gt,attachments:lt,setAttachments:St,setAttachmentsDirty:Ke,descriptionFocused:Ct,setDescriptionFocused:dt,showMarkdownHelp:Xe,setShowMarkdownHelp:ct,showChecklist:ne,setShowChecklist:st,showComments:Ye,setShowComments:Pt,handleAddComment:kt,handleSetWorkstreamForCurrentTask:It,handleOpenTaskById:Ft,taxonomies:Mt,activeTypes:Be,priorities:et,taxonomyDisplayLabels:Ue,approaches:Qe,copiedId:yt,handleCopyId:ot,handleToggleInProgress:ae,handleToggleComplete:ze,handleToggleReview:bt,handleToggleCancel:Ot,handleArchiveTask:Bt,handleDelete:Oe,handleUnarchive:Lt,handleRestoreDeletedTask:vt,handlePermanentlyDeleteDeletedTask:E,handleEmptyDeletedTasks:c,fetchTasks:Y,searchQuery:ye,setSearchQuery:Ie,filterCategories:He,setFilterCategories:Ve,filterTypes:Ne,setFilterTypes:Vt,filterPriorities:qt,setFilterPriorities:Et,filterAssignees:Tt,setFilterAssignees:Wt,hasInitedFilters:Ht,assigneeOptions:sa,taskScope:Kt,setTaskScope:Ka,sortBy:Fa,setSortBy:Xa,clearFilters:wa,settingsModel:he,configLoaded:it,currentTheme:xe,setCurrentTheme:jt,pathSaved:tt,saveSettings:Gt,keyShortcut:ga,setKeyShortcut:Na,globalWeekStartsOn:ua,locale:ca,jsonBackupEnabled:Dt,setJsonBackupEnabled:aa,mcpHostRoot:Za,setMcpHostRoot:$t,settingsSection:Qn,setSettingsSection:ba,runtimeMode:Qt,workspaceSwitchingEnabled:Lr,cloudAuthConfigured:Ia,authRequiredForApi:en,authBlocked:Ca,isAuthenticated:Jt,authUserId:Ta,authWorkspaceId:la,authUserEmail:vn,authUserDisplayName:pn,authUserAvatarUrl:Xn,authSessionResolved:ma,realtimeSyncEnabled:_r,realtimeSyncFlagSource:Br,workspaceCloudSyncEnabled:Sn,workspaceSyncPhase:Ba,workspaceSyncStatus:Cr,workspaceSyncSummary:wn,workspaceSyncRecommendedAction:Pn,workspaceSyncBusy:tn,workspaceSyncPendingChanges:Aa,saveWorkspaceCloudSyncSettings:Wr,pushNotice:_t,userGlobalSyncStatus:bn,workspaceLastSuccessfulSyncAt:fn,workspaceLastPullAt:_n,workspaceLastPushAt:Oa,workspaceLastErrorAt:Mn,userGlobalSyncError:ya,workspaceLastErrorMessage:$a,retryWorkspaceCloudSync:Cn,resetWorkspaceSyncCursorAndPull:da,getWorkspaceSyncDiagnostics:En,currentWorkspaceId:Xt,currentWorkspaceRole:Ua,availableWorkspaces:_a,switchWorkspace:er,updateCurrentUserProfile:tr,resolveCloudAuthUrl:Pa=wO,logout:na,fetchLoginMethods:pa,unlinkLoginMethod:hn,addPasswordToAccount:an,beginOAuthLogin:fr,beginOAuthLink:hr,availableAuthProviders:ea,projectRoot:Ss,projectName:za,mcpScriptPath:ar,serverHostRoot:Xr,showFolderBrowser:gn,setShowFolderBrowser:zn,folders:Fr,files:An,currentBrowsePath:Ha,fetchFolders:Ar,browserTarget:Ra,setBrowserTarget:ws,handleSelectPath:nn,handleAddPath:xr,handleRemovePath:gr,handleUpdateCategory:Or,handleRemoveCategory:yn,handleSaveCategory:yr,handleUpdateCategoryIcon:xn,handleUpdateCategoryColor:Dn,handleSaveType:nr,handleRemoveType:es,handleUpdateTaxonomies:$r,handleUpdatePriorities:Je,pathValidation:Ut,exportEnvironment:Ma,setExportEnvironment:oa,exportWorkflowsPath:cn,setExportWorkflowsPath:rn,exportResult:bs,exportingResource:_s,availableWorkflows:ts,onExportWorkflows:Ya,fetchWorkflows:Wa,availableEnvironments:Rt,initiativeTemplates:kr,fetchInitiativeTemplates:Hn,createInitiativeFromTemplate:Ln,uiNotice:rr,clearNotice:Cs,taskReturnTrail:Ir,clearReturnToParentTask:Ur,returnToPreviousTask:Fs,tasksScrollRef:Bn,setTasksScrollPos:Wn,commentsEndRef:G,autoSaveState:qe,unsavedModalOpen:At,setUnsavedModalOpen:Nt,pendingNavigation:Ea,handleNavigation:In,currentTask:Tn,currentTaskWorkstream:Mo,currentTaskInitiative:Eo,scheduleWarningPrompt:ao,confirmScheduleWarning:Ga,cancelScheduleWarning:vr}=e,Da=ca||Eg();r.useEffect(()=>{const u=String(za||"").trim();document.title=u?`Taskforce - ${u}`:"Taskforce"},[za]);const R=()=>{Nt(!1),Ea?(y==="add"&&x(),Ea()):(y==="add"&&x(),k("tasks"))},C=async()=>{await re({preventDefault:()=>{}}),Nt(!1),Ea&&Ea()},[Ze,ht]=r.useState(!1),[De,oe]=r.useState(!1),[sr,as]=r.useState(!0),[sn,oi]=r.useState(!1),[or,ir]=r.useState(!0),[ns,nl]=r.useState(Zc(new Date)),[rl,no]=r.useState(()=>{const u=new Date;return`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}`}),[ii,Rn]=r.useState(0),[ro,ci]=r.useState(!1),[li,di]=r.useState(!1),[Tr,Do]=r.useState(!1),[rs,nc]=r.useState(!0),[zr,so]=r.useState(!0),[As,xs]=r.useState(!0),[oo,ss]=r.useState(!1),[ui,ka]=r.useState(!1),[rc,Gn]=r.useState(!1),[ra,io]=r.useState(""),[Hr,co]=r.useState(""),[Rr,sc]=r.useState(new Set),[Is,cr]=r.useState(null),[Os,ln]=r.useState(null),[os,$s]=r.useState(null),[lo,Us]=r.useState(null),[Lo,zs]=r.useState(""),[uo,lr]=r.useState(""),[fa,on]=r.useState(""),[Vn,Gr]=r.useState(""),[mi,Hs]=r.useState(!1),oc=r.useRef({taskId:null,attachments:[]}),sl=r.useRef(new Map),dn=r.useRef(new Map),[mo,Bo]=r.useState(()=>qu.map(u=>u.value)),[po,Wo]=r.useState(()=>Ku.map(u=>u.value)),[Cm,ol]=r.useState(null),[Am,il]=r.useState(null),[qn,is]=r.useState(null),[fo,pi]=r.useState(null),[xm,Id]=r.useState(0),[Fo,Im]=r.useState({}),[Td,Rd]=r.useState(!1),Gs=r.useRef(!1),jd=r.useRef(""),cl=r.useRef(null),Nd=r.useRef(null),ic=r.useRef(new Set);r.useEffect(()=>{oc.current={taskId:ue||null,attachments:lt}},[ue,lt]);const ll=r.useCallback(u=>{const w=ue||null,N=oc.current,le=N.taskId===w?N.attachments:lt,ke=u(le);oc.current={taskId:w,attachments:ke},St(ke),Ke(!0),w&&K(w,{attachments:ke})},[lt,ue,K,St,Ke]),Oo=r.useMemo(()=>{const u={},w=String(Xt||"").trim();return Qt==="cloud"&&w&&w!=="default"&&(u["x-taskforce-workspace-id"]=w),u},[Qt,Xt]),ho=r.useMemo(()=>`${Qt}:${String(Xt||"default").trim()||"default"}`,[Qt,Xt]),cc=r.useMemo(()=>`taskforce:annotate-layout:${ho}`,[ho]),cs=r.useMemo(()=>`taskforce:task-origin-workspace-module:${ho}`,[ho]),fi=r.useMemo(()=>Qt==="cloud"?ma:it,[ma,it,Qt]),$o=r.useRef(!1),hi=r.useRef(!1),Vs=r.useCallback(u=>{const w=String(u||"").trim();if(!(!w||typeof window>"u")){$o.current=!0;try{window.sessionStorage.setItem(cs,w)}catch{}}},[cs]),Sr=r.useCallback(()=>{if($o.current=!1,!(typeof window>"u"))try{window.sessionStorage.removeItem(cs)}catch{}},[cs]);r.useEffect(()=>{cl.current=qn},[qn]),r.useEffect(()=>{Nd.current=fo},[fo]);const go=r.useMemo(()=>({[yd]:rd({featureKey:yd}),[gd]:rd({featureKey:gd}),[fm]:rd({featureKey:fm}),[hm]:rd({featureKey:hm}),[Xh]:rd({featureKey:Xh})}),[Qt]),Ts=r.useMemo(()=>UF({featureAccess:go}),[go]),ia=r.useMemo(()=>eg(v,Ts),[v,Ts]),Uo=go[yd]?.allowed??!1,lc=go[gd]?.allowed??!1,dl="Documents is not available in this build yet.",ul="Annotate is not available in this build yet.";r.useEffect(()=>{const u=w=>{const N=w,le=N.detail?.fsPath,ke=String(N.detail?.assetId||"").trim()||null;if(!(!le&&!ke)){if(N.preventDefault(),!Uo){_t(dl,"error");return}Vs(N.detail?.taskId),ol(le||null),il(ke),A("docs")}};return window.addEventListener("taskforce:open-markdown-document",u),()=>{window.removeEventListener("taskforce:open-markdown-document",u)}},[Uo,dl,_t,Vs,A]),r.useEffect(()=>{ia!==v&&A(ia)},[v,ia,A]),r.useEffect(()=>{ia==="docs"&&Uo||(ol(null),il(null))},[Uo,ia]),r.useEffect(()=>{if(!(typeof window>"u"))try{const u=window.sessionStorage.getItem(cc);if(!u)return;const w=JSON.parse(u);w?.annotatedTarget&&typeof w.annotatedTarget=="object"&&is(w.annotatedTarget),typeof w?.annotatedSessionId=="string"&&pi(w.annotatedSessionId.trim()||null)}catch{}},[cc]),r.useEffect(()=>{if(!hi.current&&!(ia!=="docs"&&ia!=="annotate")&&(hi.current=!0,!($o.current||typeof window>"u")))try{if(!String(window.sessionStorage.getItem(cs)||"").trim())return;window.sessionStorage.removeItem(cs),A("tasks")}catch{}},[ia,A,cs]),r.useEffect(()=>{hi.current=!1,$o.current=!1},[cs]),r.useEffect(()=>{if(jd.current===ho)return;jd.current=ho,Rd(!1);let u=!1;return(async()=>{try{const N=await fetch("/api/taskforce/ui-state?key=layout",{method:"GET",credentials:"include",headers:Oo});if(!N.ok)return;const le=await N.json().catch(()=>({})),ke=le?.state&&typeof le.state=="object"?le.state:null;if(!ke||u)return;if(typeof ke.scheduleShowWeekends=="boolean"&&oe(ke.scheduleShowWeekends),typeof ke.scheduleShowBacklog=="boolean"&&as(ke.scheduleShowBacklog),typeof ke.scheduleOnlyExpired=="boolean"&&oi(ke.scheduleOnlyExpired),typeof ke.scheduleSidebarOpen=="boolean"&&ir(ke.scheduleSidebarOpen),typeof ke.scheduleSelectedDate=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(ke.scheduleSelectedDate)&&nl(ke.scheduleSelectedDate),typeof ke.scheduleCalendarMonth=="string"&&/^\d{4}-\d{2}$/.test(ke.scheduleCalendarMonth)&&no(ke.scheduleCalendarMonth),typeof ke.scheduleScrollLeft=="number"&&Number.isFinite(ke.scheduleScrollLeft)&&ke.scheduleScrollLeft>=0&&Rn(ke.scheduleScrollLeft),typeof ke.showFilters=="boolean"&&ci(ke.showFilters),Array.isArray(ke.documentTypeFilters)&&Bo(ke.documentTypeFilters),Array.isArray(ke.documentAttachmentFilters)&&Wo(ke.documentAttachmentFilters),typeof ke.planningDrawerOpen=="boolean"&&Do(ke.planningDrawerOpen),typeof ke.documentTrayOpen=="boolean"&&nc(ke.documentTrayOpen),typeof ke.imageTrayOpen=="boolean"&&so(ke.imageTrayOpen),typeof ke.agentTrayOpen=="boolean"&&xs(ke.agentTrayOpen),typeof ke.planningTreeCollapsed=="boolean"&&ss(ke.planningTreeCollapsed),typeof ke.planningPrimaryCollapsed=="boolean"&&ka(ke.planningPrimaryCollapsed),typeof ke.planningSecondaryCollapsed=="boolean"&&Gn(ke.planningSecondaryCollapsed),Array.isArray(ke.planningExpandedInitiativeIds)&&sc(new Set(ke.planningExpandedInitiativeIds.map(Zt=>String(Zt||"").trim()).filter(Boolean))),ke.planningDrawerDetail&&typeof ke.planningDrawerDetail=="object"&&(ke.planningDrawerDetail.type==="initiative"||ke.planningDrawerDetail.type==="workstream")&&typeof ke.planningDrawerDetail.id=="string"){const Zt=ke.planningDrawerDetail.id.trim();cr(Zt?{type:ke.planningDrawerDetail.type,id:Zt}:null)}else ke.planningDrawerDetail===null&&cr(null);typeof ke.planningNestedWorkstreamDetailId=="string"?ln(ke.planningNestedWorkstreamDetailId.trim()||null):ke.planningNestedWorkstreamDetailId===null&&ln(null);const pt=ke.annotatedTarget;pt&&typeof pt=="object"&&(cl.current||is(pt)),typeof ke.annotatedSessionId=="string"&&(Nd.current||pi(ke.annotatedSessionId.trim()||null))}catch{}finally{u||Rd(!0)}})(),()=>{u=!0}},[ho,Oo]),r.useEffect(()=>{if(!Td)return;const u=window.setTimeout(async()=>{try{await df({stateKey:"layout",workspaceId:Xt,headers:Oo,patch:{scheduleShowWeekends:De,scheduleShowBacklog:sr,scheduleOnlyExpired:sn,scheduleSidebarOpen:or,scheduleSelectedDate:ns,scheduleCalendarMonth:rl,scheduleScrollLeft:ii,showFilters:ro,documentTypeFilters:mo,documentAttachmentFilters:po,documentTrayOpen:rs,imageTrayOpen:zr,agentTrayOpen:As,planningDrawerOpen:Tr,planningTreeCollapsed:oo,planningPrimaryCollapsed:ui,planningSecondaryCollapsed:rc,planningExpandedInitiativeIds:Array.from(Rr),planningDrawerDetail:Is,planningNestedWorkstreamDetailId:Os,annotatedTarget:qn,annotatedSessionId:fo}})}catch{}},250);return()=>window.clearTimeout(u)},[Td,De,sr,sn,or,ns,rl,ii,ro,mo,po,rs,zr,As,Tr,oo,ui,rc,Rr,Is,Os,qn,fo,Oo]),r.useEffect(()=>{if(!(typeof window>"u"))try{window.sessionStorage.setItem(cc,JSON.stringify({annotatedTarget:qn,annotatedSessionId:fo}))}catch{}},[cc,fo,qn]),r.useEffect(()=>{h==="schedule"&&ir(!0)},[h]);const{showArchive:yo,setShowArchive:ml,fetchArchive:pl,filteredArchive:fl}=e,gi=r.useMemo(()=>fl.map(u=>({...u,isArchived:!0})),[fl]),Fn=r.useMemo(()=>e.archivedTasks.map(u=>({...u,isArchived:!0})),[e.archivedTasks]),Rs=r.useMemo(()=>[...e.searchAgnosticTasks,...Fn],[Fn,e.searchAgnosticTasks]),Pd=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const N=Rs.find(le=>le.id===w);return Qi(N)||""},[Rs]),Md=r.useCallback(u=>{const w=String(u||"").trim();if(!w)return"";const N=String(Fo[w]||"").trim();if(N)return N;for(const le of Rs)for(const ke of le.attachments||[]){if(!ke||typeof ke!="object"||String(ke.assetId||"").trim()!==w)continue;const pt=my({referenceNumber:typeof ke.referenceNumber=="number"?ke.referenceNumber:null,referenceLabel:String(ke.referenceLabel||"").trim()||null});if(pt)return pt}return""},[Rs,Fo]);r.useEffect(()=>{const u=w=>{const N=w,le=Ih(N.detail,Rs);if(le){if(N.preventDefault(),!lc){_t(ul,"error");return}is(le),pi(null),Id(ke=>ke+1),Vs(le.taskId),A("annotate")}};return window.addEventListener("taskforce:open-annotated-attachment",u),()=>{window.removeEventListener("taskforce:open-annotated-attachment",u)}},[Rs,lc,ul,_t,Vs,A]),r.useEffect(()=>{if(!qn)return;const u=Ih(qn,Rs);u&&(u.taskReferenceLabel===qn.taskReferenceLabel&&u.imageReferenceLabel===qn.imageReferenceLabel||is(u))},[Rs,qn]),r.useEffect(()=>{const u=cl.current,w=String(u?.assetId||"").trim();if(!w)return;const N=String(Fo[w]||"").trim();N&&N!==String(u?.imageReferenceLabel||"").trim()&&is(le=>!le||String(le.assetId||"").trim()!==w?le:{...le,imageReferenceLabel:N})},[Fo,qn]),r.useEffect(()=>{if(!fi)return;const w=String(qn?.assetId||"").trim();if(!w||ic.current.has(w)||String(Fo[w]||"").trim())return;let N=!1;ic.current.add(w);const le=String(Xt||"default").trim()||"default",ke=new URLSearchParams({workspaceId:le});return(async()=>{try{const Zt=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(w)}?${ke.toString()}`,{method:"GET",credentials:"include",headers:Oo});if(!Zt.ok)return;const Sa=await Zt.json().catch(()=>({})),gs=String(Sa?.target?.imageReferenceLabel||"").trim();if(!gs||N)return;Im(xa=>xa[w]===gs?xa:{...xa,[w]:gs})}catch{}finally{ic.current.delete(w)}})(),()=>{N=!0}},[fi,Fo,Xt,qn,Oo]);const On=r.useMemo(()=>e.deletedTasks.map(u=>({...u.taskSnapshot,isDeleted:!0,deletedRecordId:u.id})),[e.deletedTasks]),yi=r.useMemo(()=>{const u=new Map;return e.deletedTasks.forEach(w=>{u.set(w.taskSnapshot.id,w)}),u},[e.deletedTasks]),ki=r.useMemo(()=>{const u=On,w=bm(ye),N={categories:S,types:Be,priorities:et,assigneeOptions:e.assigneeOptions,taxonomies:Mt},le=S.every(xa=>He.includes(xa.value)),ke=Be.every(xa=>Ne.includes(xa.value)),pt=new Set(qt.map(xa=>String(xa))),Zt=et.every(xa=>pt.has(String(xa.value))),Sa=new Set(L.map(xa=>String(xa))),gs=Xs.every(xa=>Sa.has(String(xa.value)));return u.filter(xa=>{const rp=om(xa,w,N),bu=le||He.includes(xa.category),sp=ke||Ne.includes(xa.type||Dr),op=Zt||pt.has(String(xa.priority)),_u=gs||Sa.has(String(xa.status)),ip=Tt.length===0||Tt.includes(xa.assignee||"unassigned");return rp&&bu&&sp&&op&&_u&&ip})},[S,Be,On,Tt,He,qt,L,Ne,et,ye]),vi=r.useMemo(()=>[...e.tasks,...Fn,...On],[Fn,On,e.tasks]),dc=r.useMemo(()=>{const u=S.filter(N=>!N.disabled).map(N=>({value:N.value,label:N.label})),w=S.filter(N=>N.disabled&&vi.some(le=>le.category===N.value)).map(N=>({value:N.value,label:`${N.label} (Legacy)`}));return[...u,...w]},[S,vi]),hl=r.useMemo(()=>{const u=Be.filter(N=>N.status!=="retired").map(N=>({value:N.value,label:N.label})),w=Be.filter(N=>N.status==="retired"&&vi.some(le=>(le.type||Dr)===N.value)).map(N=>({value:N.value,label:`${N.label} (Retired)`}));return[...u,...w]},[Be,vi]),qs=r.useMemo(()=>Kt==="archived"?gi:Kt==="deleted"?ki:yo?[...e.filteredTasks,...gi]:e.filteredTasks,[gi,ki,e.filteredTasks,yo,Kt]),uc=r.useMemo(()=>Kt==="open"?e.tasks.filter(u=>!u.isArchived):qs,[qs,e.tasks,Kt]),gl=r.useMemo(()=>new Set(qs.map(u=>u.id)),[qs]),Si=r.useMemo(()=>Kt==="archived"?Fn:Kt==="deleted"?On:yo?[...e.tasks,...Fn]:e.tasks,[Fn,On,e.tasks,yo,Kt]),wi=r.useMemo(()=>{const u=new Map;for(const w of Fn)u.set(w.id,w);for(const w of On)u.set(w.id,w);for(const w of e.tasks)u.set(w.id,w);return Array.from(u.values())},[Fn,On,e.tasks]),mc=r.useMemo(()=>{const u=new Map;return wi.forEach(w=>u.set(w.id,w)),u},[wi]),pc=r.useMemo(()=>{const u=new Map;sa.forEach(le=>{u.set(String(le.value),le.label)});const w=String(Ta||"").trim(),N=String(pn||vn||"").trim();return w&&N&&u.set(w,N),u},[sa,pn,vn,Ta]),wt=r.useMemo(()=>{const u=Kt==="archived"?Fn:Kt==="deleted"?On:e.tasks.filter(ut=>!ut.isArchived),w=Kt==="deleted"?On:Array.from([...e.tasks,...Fn].reduce((ut,Qa)=>ut.set(Qa.id,Qa),new Map).values()),N=(ut,Qa)=>({progressPercent:ut>0?Math.round(Qa/ut*100):0,taskCount:ut,completedTaskCount:Qa}),le=Kt==="open"&&e.planningBootstrapTaskSummaries.length>0&&(e.loadingTasks||e.tasks.length===0),ke=new Map,pt=new Map;le?e.planningBootstrapTaskSummaries.forEach(ut=>{ke.set(ut.workstreamId,ut),pt.set(ut.workstreamId,ut.tasks||[])}):(u.forEach(ut=>{const Qa=String(ut.workstreamId||"").trim();if(!Qa)return;const ur=ke.get(Qa)||{workstreamId:Qa,taskCount:0,completedTaskCount:0,tasks:[]};ur.taskCount+=1,(ut.isArchived||ut.status==="done"||ut.status==="cancelled")&&(ur.completedTaskCount+=1),ke.set(Qa,ur)}),w.forEach(ut=>{const Qa=String(ut.workstreamId||"").trim();if(!Qa)return;const ur=pt.get(Qa)||[];ur.push({id:ut.id,referenceNumber:ut.referenceNumber??null,title:ut.title,status:ut.status||null,isArchived:!!ut.isArchived}),pt.set(Qa,ur)}));const Zt=new Map,Sa=new Map,gs=new Map,xa=new Map,rp=ut=>{const Qa=ke.get(ut.id),ur=pt.get(ut.id)||Qa?.tasks||[],Cu={id:ut.id,referenceNumber:ut.referenceNumber??null,title:ut.title,description:String(ut.description||"").trim()||void 0,ownerId:ut.ownerId?String(ut.ownerId):null,ownerLabel:ut.ownerId?pc.get(String(ut.ownerId))||String(ut.ownerId):null,...N(Qa?.taskCount||0,Qa?.completedTaskCount||0),initiativeId:ut.initiativeId||null,commentCount:Array.isArray(ut.comments)?ut.comments.length:0,attachmentCount:Array.isArray(ut.attachments)?ut.attachments.length:0,attachments:Array.isArray(ut.attachments)?ut.attachments:[],isArchived:!!ut.isArchived,tasks:ur};if(Zt.set(ut.id,ur.map(Uc=>Uc.id)),ut.initiativeId){Sa.set(ut.id,ut.initiativeId);const Uc=xa.get(ut.initiativeId)||[];Uc.push(Cu),xa.set(ut.initiativeId,Uc)}return Cu},bu=e.workstreams.map(rp),sp=bu.filter(ut=>pm(Kt,!!ut.isArchived)),op=e.initiatives.map(ut=>{const Qa=xa.get(ut.id)||[],ur=Qa.filter(ad=>pm(Kt,!!ad.isArchived)),Cu=ur.reduce((ad,cp)=>ad+cp.taskCount,0),Uc=ur.reduce((ad,cp)=>ad+cp.completedTaskCount,0);return{id:ut.id,referenceNumber:ut.referenceNumber??null,title:ut.title,description:String(ut.description||"").trim()||void 0,ownerId:ut.ownerId?String(ut.ownerId):null,ownerLabel:ut.ownerId?pc.get(String(ut.ownerId))||String(ut.ownerId):null,...N(Cu,Uc),workstreamCount:ur.length,workstreams:ur,allWorkstreams:Qa,commentCount:Array.isArray(ut.comments)?ut.comments.length:0,attachmentCount:Array.isArray(ut.attachments)?ut.attachments.length:0,attachments:Array.isArray(ut.attachments)?ut.attachments:[],isArchived:!!ut.isArchived}}),{initiatives:_u,standaloneWorkstreams:ip,initiativeById:Ak,workstreamById:xk}=IW(op,sp,Kt),Ik=bu.filter(ut=>!ut.initiativeId);return _u.forEach(ut=>{gs.set(ut.id,ut.workstreams.flatMap(Qa=>(Qa.tasks||[]).map(ur=>ur.id)))}),{initiatives:_u,standaloneWorkstreams:ip,allStandaloneWorkstreams:Ik,workstreamTaskIds:Zt,workstreamInitiativeIds:Sa,initiativeTaskIds:gs,workstreamById:xk,initiativeById:Ak}},[Fn,pc,On,e.initiatives,e.loadingTasks,e.planningBootstrapTaskSummaries,e.tasks,e.workstreams,Kt]),Ed=r.useMemo(()=>wt.initiatives.map(u=>{const w=Jr(u);return{value:u.id,label:w||u.title}}),[wt.initiatives]),fc=r.useMemo(()=>{const w=(ra?wt.initiativeById.get(ra)?.workstreams||[]:wt.initiatives.flatMap(le=>le.workstreams)).map(le=>{const ke=No(le);return{value:le.id,label:ke||le.title}}),N=ra?[]:wt.standaloneWorkstreams.map(le=>{const ke=No(le);return{value:le.id,label:ke||le.title}});return[...w,...N]},[wt.initiativeById,wt.initiatives,wt.standaloneWorkstreams,ra]),ls=r.useMemo(()=>Hr?new Set(wt.workstreamTaskIds.get(Hr)||[]):ra?new Set(wt.initiativeTaskIds.get(ra)||[]):null,[wt.initiativeTaskIds,wt.workstreamTaskIds,ra,Hr]),zo=r.useMemo(()=>{if(!Is)return null;if(Is.type==="initiative"){const w=wt.initiativeById.get(Is.id);return w?{type:"initiative",item:w}:null}const u=wt.workstreamById.get(Is.id)||wt.standaloneWorkstreams.find(w=>w.id===Is.id);return u?{type:"workstream",item:u}:null},[Is,wt.initiativeById,wt.standaloneWorkstreams,wt.workstreamById]),hc=r.useMemo(()=>{if(!Os)return null;const u=wt.workstreamById.get(Os)||wt.standaloneWorkstreams.find(w=>w.id===Os);return u?{type:"workstream",item:u}:null},[Os,wt.standaloneWorkstreams,wt.workstreamById]),gc=r.useMemo(()=>lo?{kind:"editor",editor:lo}:hc?{kind:"detail",detail:hc}:null,[hc,lo]),Dd=Oy(oo,!!(zo||os),ui,!!gc,rc),yc=r.useMemo(()=>{if(!Vn.trim())return null;const u=wt.initiativeById.get(Vn);return u||yp(wt.initiatives,Vn)},[Vn,wt.initiativeById,wt.initiatives]);r.useEffect(()=>{ra&&!wt.initiativeById.has(ra)&&io(""),Hr&&!wt.workstreamById.has(Hr)&&co("")},[wt.initiativeById,wt.workstreamById,ra,Hr]);const wr=r.useMemo(()=>h==="schedule"?uc:qs,[h,qs,uc]),Ja=r.useMemo(()=>{const u=new Date,w=u.getFullYear(),N=String(u.getMonth()+1).padStart(2,"0"),le=String(u.getDate()).padStart(2,"0");return`${w}-${N}-${le}`},[]),bi=r.useMemo(()=>h!=="schedule"||!sn?wr:wr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const N=!!u.scheduledDate&&u.scheduledDate<Ja,le=!!u.dueDate&&u.dueDate<Ja;return N||le}),[h,sn,wr,Ja]),yl=r.useMemo(()=>!ls||ls.size===0?bi:bi.filter(u=>ls.has(u.id)),[bi,ls]),Ld=r.useMemo(()=>!ls||ls.size===0?Si:Si.filter(u=>ls.has(u.id)),[Si,ls]),ko=r.useMemo(()=>h!=="schedule"?[]:wr.filter(u=>{if(u.status==="done"||u.status==="cancelled")return!1;const N=!!u.scheduledDate&&u.scheduledDate<Ja,le=!!u.dueDate&&u.dueDate<Ja;return N||le}),[h,wr,Ja]),Bd=r.useMemo(()=>h!=="schedule"?0:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Ja).length,[h,wr,Ja]),kl=r.useMemo(()=>h!=="schedule"?0:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.dueDate&&u.dueDate<Ja).length,[h,wr,Ja]),Vr=String(Ta||"").trim(),Wd=r.useMemo(()=>!Vr||Vr==="anonymous"?0:me.filter(u=>u.status==="done"||u.status==="cancelled"?!1:String(u.assignee||"").trim()===Vr).length,[Vr,me]),Fd=r.useMemo(()=>!Vr||Vr==="anonymous"?0:me.filter(u=>u.status==="done"||u.status==="cancelled"||String(u.assignee||"").trim()!==Vr?!1:!!u.dueDate&&u.dueDate<Ja).length,[Vr,me,Ja]),kc=r.useMemo(()=>h!=="schedule"?[]:wr.filter(u=>u.status==="done"||u.status==="cancelled"?!1:!!u.scheduledDate&&u.scheduledDate<Ja),[h,wr,Ja]),_i=ko,[vo,Ci]=r.useState(!1),vc=()=>{In(()=>{Fs()||(y==="add"&&Ir.length>0&&Ur(),di(!1),y==="add"&&x(),k("tasks"))})};r.useEffect(()=>{y!=="add"&&di(!1)},[y]);const Sc=r.useCallback((u,w)=>{if(u.status!==w){if(w==="in-progress"){ae(u);return}if(w==="review"){bt(u);return}if(w==="done"){ze(u);return}if(w==="cancelled"){Ot(u);return}K(u.id,{status:w,completedAt:null})}},[ae,bt,ze,Ot,K]),vl=r.useCallback((u,w)=>{x();const N=CW(u,w,{categories:S,approaches:Qe});N.category&&se(N.category),N.type&&Re(N.type),typeof N.priority=="number"&&Ce(N.priority),typeof N.complexity=="number"&&U(N.complexity),N.approach&&j(N.approach);const le=N.taxonomyApproach;typeof le=="string"&&le.length>0&&Te(ke=>({...ke,approach:le})),N.assignee&&te(N.assignee),N.status&&T(N.status),N.scheduledDate&&H(N.scheduledDate),k("add")},[x,S,Qe,se,Re,Ce,U,T,j,te,H,Te,k]);Fe.useEffect(()=>{L&&!L.includes("done")&&J(u=>[...u,"done"])},[]);const[Od,Ho]=r.useState(!1),[ds,Kn]=r.useState(!1),[So,wo]=r.useState(!1),[Sl,wl]=r.useState(!1),[Tm,wc]=r.useState(!1),[bc,$d]=r.useState(!1),[Ud,bl]=r.useState(""),[_l,Ai]=r.useState(!1),[Rm,zd]=r.useState(!1),[jm,xi]=r.useState("members"),[_c,Cc]=r.useState(null),[Ac,Ii]=r.useState("unknown"),[Hd,Ti]=r.useState(!1),[Nm,jn]=r.useState(null),[us,br]=r.useState(null),[xc,Ic]=r.useState(!1),[Go,Cl]=r.useState([]),[Ri,Vo]=r.useState(null),[ji,Tc]=r.useState(""),[js,Ni]=r.useState("member"),[Pi,Rc]=r.useState("read-write"),[jc,Al]=r.useState(!1),[Gd,qo]=r.useState(null),[Ns,Pm]=r.useState(0),[Vd,qd]=r.useState(!1),[Mm,Em]=r.useState([]),[Dm,Lm]=r.useState(!1),[Kd,Bm]=r.useState(1),[kn,xl]=r.useState(null),[Zd,Nc]=r.useState(!1),[Pc,Il]=r.useState(null),[Yd,Mi]=r.useState(!1),[jr,Nr]=r.useState(null),[Ko,Pr]=r.useState(!1),[Jd,Tl]=r.useState(null),[Ks,Ei]=r.useState("month"),[Rl,Qd]=r.useState(""),[ms,Zo]=r.useState(""),[dr,Yo]=r.useState(null),[jl,Xd]=r.useState(!1),[Wm,Nl]=r.useState(!1),[eu,qr]=r.useState(null),[tu,Kr]=r.useState(null),au=25,nu=r.useRef(null),Di=r.useRef(null),Pl=r.useRef({billing:!1,teamManagement:!1}),Li=r.useRef(null);r.useEffect(()=>{Li.current=kn},[kn]),r.useEffect(()=>{if(!ds)return;const u=w=>{nu.current?.contains(w.target)||Kn(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[ds]);const Fm=Qt==="cloud"&&Lr&&Jt,Jo=Jt&&(Qt==="cloud"||Ia),Ml=Qt==="local"&&Jt,{showSyncStatusModal:El,showSyncEnableWarning:Om,workspaceSyncError:Dl,syncControlBusy:ru,openSyncStatusModal:$m,closeSyncStatusModal:Ll,handleWorkspaceSyncToggle:su,cancelSyncEnableWarning:Um,confirmSyncEnableWarning:zm}=pO({canManageWorkspaceSync:Ml,workspaceCloudSyncEnabled:Sn,saveWorkspaceCloudSyncSettings:Wr}),Bl=r.useMemo(()=>{const u=_a.find(le=>le.id===Xt),w=String(u?.name||"").trim();if(w)return w;if(Qt==="local"){const le=String(za||"").trim();if(le)return le}return String(Xt||"").trim()||"Workspace"},[_a,Xt,za,Qt]),Mc=Uy(Jo,_c),bo=cO(Jo,_c,Ac),Bi=String(pn||"").trim(),Mr=String(Xn||"").trim(),Ps=String(vn||"").trim(),Zs=Bi||Ps,Wl=Zs.length>0,Hm=Ps.length>0,Gm=r.useMemo(()=>wB({workspaceName:Bl,workspaceId:Xt,accountLabel:Zs||Ps,runtimeMode:Qt}),[Ps,Zs,Xt,Bl,Qt]),Wi=(Zs||Ps||"").trim(),Fi=Jt&&ma&&Wi.length>0?Wi.charAt(0).toUpperCase():"",Fl=Mr,Vm=Jt&&ma&&Fl.length>0,Ec=String(ms||Mr).trim(),Dc=String(kn?.planName||kn?.planId||"").trim(),ou=Dc.length>0,Ms=String(kn?.workspaceId||la||Xt||"").trim(),iu=Qt==="cloud"?"CLOUD":"LOCAL",Ol=e.config?.apiBaseUrl||"",qm=r.useMemo(()=>bO(e.config?.cloudEnvironment,[String(e.config?.cloudBaseUrl||""),String(e.config?.cloudAuthBaseUrl||""),String(e.config?.apiBaseUrl||""),String(e.config?.baseUrl||"")]),[e.config?.cloudEnvironment,e.config?.cloudBaseUrl,e.config?.cloudAuthBaseUrl,e.config?.apiBaseUrl,e.config?.baseUrl]),$l=Ia&&!ma;r.useEffect(()=>{Sl&&(Qd(Bi),Zo(Mr),Yo(null),qr(null),Kr(null))},[Mr,Bi,Sl]);const Es=r.useCallback(async u=>{const w=String(u||"").trim();if(!(!w||!Ia))try{await fetch(Pa("/api/taskforce/auth/profile/avatar/discard"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:w})})}catch{}},[Ia,Pa]),cu=r.useCallback(()=>{const u=dr;wl(!1),wc(!1),qr(null),Kr(null),Yo(null),Zo(Mr),u&&Es(u)},[Mr,Es,dr]),lu=r.useCallback(async u=>{if(!u||!Ia)return!1;if(!u.type.startsWith("image/"))return qr("Profile photo must be an image file."),Kr(null),!1;Xd(!0),qr(null),Kr(null);try{const w=await XW(u,{maxBytes:SO});if(w.exceededLimit){const xa=u.type==="image/gif"?"Animated GIF profile photos must be 5 MB or smaller.":"Profile photo must be 5 MB or smaller.";throw new Error(xa)}const N=w.file,le=await fetch(Pa("/api/taskforce/auth/profile/avatar/init"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:N.name,mimeType:N.type,size:N.size})}),ke=await le.json().catch(()=>({}));if(!le.ok||!ke?.success||typeof ke?.draftId!="string"||typeof ke?.relativePath!="string")throw new Error(ke?.error||"Failed to start avatar upload.");if(!(await fetch(Pa("/api/taskforce/auth/profile/avatar/upload"),{method:"POST",headers:{"Content-Type":N.type||"application/octet-stream","x-taskforce-avatar-draft-id":ke.draftId},credentials:"include",body:N})).ok)throw new Error("Failed to upload avatar.");const Zt=await fetch(Pa("/api/taskforce/auth/profile/avatar/finalize"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:ke.draftId,relativePath:ke.relativePath})}),Sa=await Zt.json().catch(()=>({}));if(!Zt.ok||!Sa?.success||typeof Sa?.draftId!="string")throw new Error(Sa?.error||"Failed to finalize avatar upload.");const gs=dr;return Yo(Sa.draftId),Zo(typeof Sa?.avatarUrl=="string"?Sa.avatarUrl:""),Kr(null),gs&&gs!==Sa.draftId&&Es(gs),!0}catch(w){return qr(w instanceof Error?w.message:"Failed to upload profile photo."),!1}finally{Xd(!1)}},[Ia,Es,dr,Pa]),du=r.useCallback(()=>{if(!dr)return;const u=dr;Yo(null),Zo(Mr),Kr(null),qr(null),Es(u)},[Mr,Es,dr]),uu=r.useCallback(()=>{const u=dr;Yo(null),Zo(""),Kr(Mr?"Profile photo will be removed when you save.":null),qr(null),u&&Es(u)},[Mr,Es,dr]),Km=r.useCallback(async()=>{const u=Rl.trim();if(!u){qr("Display name is required."),Kr(null);return}Nl(!0),qr(null),Kr(null);const w=await tr({displayName:u,avatarDraftId:dr,clearAvatar:!dr&&!ms&&!!Mr});if(!w.success){qr(w.error||"Failed to update profile."),Nl(!1);return}Kr("Profile updated."),Yo(null),Zo(""),Nl(!1),wc(!1),wl(!1)},[Mr,dr,ms,Rl,tr]),Zr=r.useCallback(()=>{const u={},w=String(Ms||"").trim();w&&(u["x-taskforce-workspace-id"]=w);const N=_c||Ua;return(N==="owner"||N==="admin"||N==="member"||N==="read-only")&&(u["x-taskforce-workspace-role"]=N),u},[Ua,Ms,_c]),Lc=r.useCallback(u=>{const w=Jt,N=Jo;Di.current=sd(),Pl.current={billing:w,teamManagement:N},zt("account_surface_opened",{surface:u,expectsBilling:w,expectsTeamManagement:N}),!w&&!N&&(zt("account_surface_ready",{surface:u,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),Di.current=null)},[Jo,Jt]),Ds=r.useCallback(u=>{const w=Pl.current;if(w[u]=!1,w.billing||w.teamManagement)return;const N=Di.current;N!==null&&(zt("account_surface_ready",{surface:So?"account_hub":ds?"account_menu":"closed",durationMs:Math.round(sd()-N),teamManagementVisible:bo,billingPlanId:String(kn?.planId||"").trim()||null}),Di.current=null)},[kn?.planId,bo,So,ds]),ps=r.useCallback(async u=>{const w=Pa(zh);if(!Jt)return xl(null),Il(null),Cc(null),Ii("unknown"),Ti(!1),jn(null),Hh(w,{identityKey:Ta}),Ds("billing"),Ds("teamManagement"),null;const N=sd();Nc(!0),Il(null),Ti(Jo),jn(null);try{const le=await OW(w,{identityKey:Ta,force:u?.force===!0}),ke=le?.workspaceRole==="owner"||le?.workspaceRole==="admin"||le?.workspaceRole==="member"||le?.workspaceRole==="read-only"?le.workspaceRole:null,pt=le?.teamPlanMode==="team"||le?.teamPlanMode==="personal"?le.teamPlanMode:"unknown";return xl(le),Cc(ke),Ii(pt),jn(null),zt("account_profile_summary_resolved",{durationMs:Math.round(sd()-N),planId:String(le?.planId||"").trim()||null,gate:String(le?.gate||"").trim()||null,teamManagementAllowed:le?.teamManagementAllowed===!0}),le}catch(le){const ke=le instanceof Error?le.message:"Failed to load account summary.",pt=!!Li.current;return Il(ke),pt?jn(null):(Cc(null),Ii("unknown"),jn(ke)),zt("account_profile_summary_failed",{durationMs:Math.round(sd()-N),error:ke,preservedSummary:pt}),Li.current}finally{Nc(!1),Ti(!1),Ds("billing"),Ds("teamManagement")}},[Ta,Jo,Jt,Ds,Pa]),Zm=r.useCallback(u=>{xl(u);const w=u?.workspaceRole==="owner"||u?.workspaceRole==="admin"||u?.workspaceRole==="member"||u?.workspaceRole==="read-only"?u.workspaceRole:null,N=u?.teamPlanMode==="team"||u?.teamPlanMode==="personal"?u.teamPlanMode:"unknown";Cc(w),Ii(N)},[]),Ul=r.useMemo(()=>Gp(kn).allowReturnToApp,[kn]),zl=r.useCallback(async()=>{const u=new URLSearchParams;u.set("screen","plans"),u.set("interval",Ks);const w=String(kn?.planId||"").trim(),N=String(kn?.planVersionId||"").trim();w&&u.set("planId",w),N&&u.set("planVersionId",N),s(`/?${u.toString()}`)},[kn?.planId,kn?.planVersionId,Ks,s]),Hl=r.useCallback(async()=>{Nr(null),Tl(null),Mi(!0);try{const u=await fetch(Pa("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),w=await u.json().catch(()=>({}));if(!u.ok){Nr(String(w?.error||"Failed to create portal session."));return}const N=String(w?.url||"").trim();if(!N){Nr("Portal session did not return a redirect URL.");return}window.location.assign(N)}catch{Nr("Failed to open billing portal.")}finally{Mi(!1)}},[Pa]),mu=r.useCallback(async()=>{Nr(null),Tl(null),Mi(!0);try{const u=String(kn?.planVersionId||"").trim();if(!u){Nr("No active plan version is linked to this account.");return}const w=await fetch(Pa("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:u,interval:Ks})}),N=await w.json().catch(()=>({}));if(!w.ok){Nr(String(N?.error||"Failed to update subscription interval."));return}Tl("Subscription updated."),Hh(Pa(zh),{identityKey:Ta}),await ps()}catch{Nr("Failed to update subscription interval.")}finally{Mi(!1)}},[kn?.planVersionId,Ta,Ks,ps,Pa]);r.useEffect(()=>{!Jt||!ma||ps()},[ma,Jt,ps]),r.useEffect(()=>{!So&&!ds||ps()},[ps,So,ds]);const Oi=r.useCallback(async()=>{if(Mc){Ic(!0),br(null);try{const u=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:Zr()}),w=await u.json().catch(()=>({}));if(!u.ok){br(w?.error||"Failed to load workspace users.");return}const N=Array.isArray(w?.users)?w.users:[],le={owner:0,admin:1,member:2,"read-only":3},ke=N.map(pt=>({userId:String(pt?.userId||""),email:String(pt?.email||""),displayName:typeof pt?.displayName=="string"?pt.displayName:null,role:pt?.role==="owner"||pt?.role==="admin"||pt?.role==="member"||pt?.role==="read-only"?pt.role:"member",permissionMode:pt?.permissionMode==="read-only"?"read-only":"read-write",status:String(pt?.status||"active"),disabled:pt?.disabled===!0}));ke.sort((pt,Zt)=>{const Sa=(le[pt.role]??99)-(le[Zt.role]??99);return Sa!==0?Sa:(pt.displayName||pt.email).localeCompare(Zt.displayName||Zt.email,void 0,{sensitivity:"base"})}),Cl(ke)}catch{br("Failed to load workspace users.")}finally{Ic(!1)}}},[Mc,Zr]),_o=r.useCallback(async u=>{if(!Mc)return;const w=Math.max(0,Math.floor(u));qd(!0),br(null);try{const N=w*au,le=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${au}&offset=${N}`,{method:"GET",credentials:"include",headers:Zr()}),ke=await le.json().catch(()=>({}));if(!le.ok){br(ke?.error||"Failed to load workspace audit log.");return}const pt=Array.isArray(ke?.events)?ke.events:[];Em(pt.map(Sa=>({id:String(Sa?.id||""),action:String(Sa?.action||""),actorUserId:String(Sa?.actorUserId||""),actorRole:String(Sa?.actorRole||""),createdAt:String(Sa?.createdAt||Sa?.ts||"")}))),Pm(w);const Zt=Math.max(1,Number(ke?.pages||1));Bm(Zt),Lm(w+1<Zt)}catch{br("Failed to load workspace audit log.")}finally{qd(!1)}},[Mc,Zr]),Bc=r.useCallback(async()=>{await Promise.all([Oi(),_o(Ns)])},[Oi,_o,Ns]),Wc=r.useCallback((u="login")=>{const w=`${o.pathname}${o.search}${o.hash}`,N=!w||w==="/login"||!w.startsWith("/")?"/":w;Kn(!1),wo(!1),Ll(),s(`/login?mode=${u}&next=${encodeURIComponent(N)}`)},[Ll,o.hash,o.pathname,o.search,s]),Co=r.useCallback(u=>{Kn(!1),Ai(!1);const w=new URLSearchParams({step:"workspace"});u?.intent==="create-workspace"&&w.set("intent","create-workspace"),s(`/setup?${w.toString()}`,{replace:!0})},[s]),Qo=r.useCallback(async()=>{if(Ko)return;if(Pr(!0),!Jt){try{m()}finally{Pr(!1)}return}const u=Li.current;if(u&&!Gp(u).allowReturnToApp){Pr(!1);return}m(),(async()=>{try{const w=await e.continueAfterCommercialOnboarding();if(!w.success){_t(w.error||"Unable to finish onboarding.","error"),w.destination==="login"&&s("/login",{replace:!0});return}w.destination==="setup"&&Co()}finally{Pr(!1)}})()},[Li,m,Jt,s,Co,Ko,e,_t]),Gl=r.useCallback(()=>{if(i){Qo();return}In(()=>{Sr(),A("tasks"),Do(!1),cr(null),ln(null),$s(null),di(!1),y==="add"&&x(),k("tasks"),(o.pathname!=="/"||o.search)&&s("/")})},[y,Sr,In,Qo,i,o.pathname,o.search,s,x,k,A]),Vl=r.useCallback(async u=>{if(!(!u||bc)){bl(""),$d(!0);try{const w=await er(u);if(!w.success){if(w.code==="WORKSPACE_NOT_FOUND"||w.code==="WORKSPACE_ID_REQUIRED"){Co();return}bl(w.error||"Failed to switch workspace.");return}await Y(!0),Kn(!1)}finally{$d(!1)}}},[er,bc,Y,Co]),Fc=r.useCallback(async()=>{Kn(!1),zd(!0),xi("members"),((await ps())?.teamManagementAllowed??bo)&&(await Oi(),await _o(0))},[bo,ps,_o,Oi]),Ao=r.useCallback(async(u,w)=>{br(null),Vo(u);try{const N=await w(),le=await N.json().catch(()=>({}));if(!N.ok){br(le?.error||"Team management action failed.");return}await Bc()}catch{br("Team management action failed.")}finally{Vo(null)}},[Bc]),ql=r.useCallback(async()=>{const u=ji.trim();if(u){Al(!0),br(null),qo(null);try{const w=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...Zr()},credentials:"include",body:JSON.stringify({workspaceId:Ms,email:u,role:js,permissionMode:js==="member"?Pi:"read-write"})}),N=await w.json().catch(()=>({}));if(!w.ok){br(N?.error||"Failed to send invite.");return}Tc(""),N?.inviteEmailSent===!1?qo(`Invite created, but email delivery failed${N?.inviteEmailError?`: ${String(N.inviteEmailError)}`:"."}`):qo("Invite sent."),await Bc()}catch{br("Failed to send invite.")}finally{Al(!1)}}},[Xt,Bc,Zr,ji,Pi,js]),Kl=r.useMemo(()=>ye.trim().length>0,[ye]),Ym=r.useMemo(()=>Go.filter(u=>u.status==="invited"),[Go]),Zl=r.useMemo(()=>{const u=He.length!==S.length,w=Ne.length!==Be.length,N=qt.length!==et.length,le=L.length!==Xs.length,ke=Tt.length!==sa.length,pt=ra.length>0,Zt=Hr.length>0;return u||w||N||le||ke||pt||Zt},[S.length,Be.length,sa.length,Tt.length,He.length,qt.length,L.length,Ne.length,et.length,ra,Hr]),pu=r.useMemo(()=>mo.length!==qu.length||po.length!==Ku.length,[po.length,mo.length]),fu=ia,Ys=r.useMemo(()=>zF(fu),[fu]),Yl=r.useMemo(()=>{switch(Ys.filterBar.kind){case"task-filters":return Zl;case"document-filters":return pu;default:return!1}},[pu,Zl,Ys.filterBar.kind]),hu=Kl||Zl,Jl=Kt==="archived"?Fn.length:Kt==="deleted"?On.length:me.length,Jm=Kt==="archived"?gi.length:Kt==="deleted"?ki.length:e.filteredTasks.length,Ql=hu?`${Jm}/${Jl}`:`${Jl}`,Qm=hu?`${Kt.charAt(0).toUpperCase()+Kt.slice(1)} tasks matching current filters`:`${Kt.charAt(0).toUpperCase()+Kt.slice(1)} tasks`,Xm=Qt==="local"&&Jt,Xo=r.useCallback(u=>{if(!u)return"Never";const w=new Date(u);return Number.isNaN(w.getTime())?"Never":w.toLocaleString()},[]),Xl=r.useMemo(()=>Xo(fn),[Xo,fn]),gu=r.useMemo(()=>Xo(_n),[Xo,_n]),yu=r.useMemo(()=>Xo(Oa),[Xo,Oa]),ku=Dl||$a||ya||"None",fs=En(),hs=r.useMemo(()=>xW({runtimeMode:Qt,isAuthenticated:Jt,workspaceSyncStatus:Cr,workspaceCloudSyncEnabled:Sn,workspaceSyncSummary:wn,workspaceSyncRecommendedAction:Pn,workspaceSyncError:ku,pushBlockedReason:fs.pushBlockedReason||null,pullBlockedReason:fs.pullBlockedReason||null,retryBlockedReason:fs.retryBlockedReason||null}),[Qt,Jt,Cr,Sn,wn,Pn,ku,fs.pushBlockedReason,fs.pullBlockedReason,fs.retryBlockedReason]),vu=hs.lastError,[ep,f]=r.useState(hs.status),W=r.useMemo(()=>EW(fs),[fs]),{syncRecentEvents:F,syncRecentEventsLoading:Z,syncRecentEventsError:We,syncEventsListRef:Le,loadRecentSyncEvents:Ge}=lO({isOpen:El,workspaceId:Xt,refreshKeys:[Oa,_n,Mn,Cr]}),ha=hs.actionable&&Cr==="syncing"&&Ba==="active"&&Aa===0;r.useEffect(()=>{if(!ha){f(hs.status);return}const u=window.setTimeout(()=>{f(hs.status)},1200);return()=>window.clearTimeout(u)},[hs.status,ha]);const va=r.useMemo(()=>DW({syncRecentEvents:F,syncRecentEventsError:We,syncRecentEventsLoading:Z}),[F,We,Z]),La=r.useMemo(()=>LW(F),[F]),un=r.useMemo(()=>BW(F),[F]),Va=r.useMemo(()=>MW(ep),[ep]),{workspaceSyncRepairBusy:Zn,workspaceSyncRepairQueued:ed,workspaceSyncCopied:Hy,handleCopySyncDetails:Gy,handleQueueOrRunRepairSync:Vy}=mO({currentWorkspaceId:Xt,syncStatusLabel:Va.label,workspaceSyncSummary:hs.summary,workspaceSyncRecommendedAction:hs.recommendedAction,formattedLastSyncTime:Xl,formattedLastPullTime:gu,formattedLastPushTime:yu,workspaceSyncDiagnostics:fs,workspaceSyncPendingChanges:Aa,syncLastError:vu,workspaceSyncPhase:Ba,referenceMismatchCount:La,syncRecentEvents:F,loadRecentSyncEvents:Ge,pushNotice:_t,resetWorkspaceSyncCursorAndPull:da,workspaceSyncBusy:tn}),qy=r.useMemo(()=>Ly(Ba,Zn,tn),[tn,Ba,Zn]),xf=r.useMemo(()=>md(ns)||new Date,[ns]),$i=r.useMemo(()=>Yp(xf,ua),[xf,ua]),xo=r.useMemo(()=>{const u={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return tg.forEach(w=>{const N=sO(w,ua);u[w]=Zc($y($i,N))}),u},[$i,ua]),If=r.useCallback(u=>{const w=md(u);if(!w)return xo.mon;const N=w.getDay();return xo[N===1?"mon":N===2?"tue":N===3?"wed":N===4?"thu":N===5?"fri":N===6?De?"sat":"fri":De?"sun":"fri"]||xo.mon},[xo,De]),Ky=r.useCallback(async()=>{if(!(vo||_i.length===0)){Ci(!0);try{for(const u of _i){const w=u.scheduledDate||u.dueDate||Ja,N=If(w);await K(u.id,{scheduledDate:N,scheduledWeekKey:oO(N),orderInDay:null})}await Y(!0)}finally{Ci(!1)}}},[vo,_i,Ja,If,K,Y]),Zy=r.useCallback(async()=>{if(!(vo||ko.length===0)){Ci(!0);try{for(const u of ko)await K(u.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await Y(!0)}finally{Ci(!1)}}},[vo,ko,K,Y]),Yy=r.useMemo(()=>mm($i,{month:"short",day:"numeric",year:"numeric"},Da),[$i,Da]),Tf=r.useMemo(()=>{const N=(De?ua==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:tg:["mon","tue","wed","thu","fri"]).map(ke=>{const pt=md(xo[ke])||$i,Zt=xo[ke],Sa=ke==="sat"||ke==="sun";return{value:ke,label:`${rO[ke]} ${mm(pt,{month:"short",day:"numeric"},Da)}`,color:Sa?"#1e3a8a":"#3b82f6",icon:"Calendar",date:Zt,isPast:Zt<Ja,isSelected:Zt===ns,isWeekend:Sa}}),le=kc.length>0;return[...sr?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...le?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...N]},[De,sr,xo,$i,kc.length,Ja,ns,ua,Da]),Rf=r.useMemo(()=>{switch(h){case"category":return S;case"type":return(Be||[]).map(u=>({...u,icon:u.icon||sm[u.value]?.icon,color:u.color||sm[u.value]?.color}));case"priority":return et;case"complexity":return[{value:1,label:"Tiny",icon:"Gauge",color:"#10b981"},{value:2,label:"Low",icon:"Gauge",color:"#14b8a6"},{value:3,label:"Medium",icon:"Gauge",color:"#3b82f6"},{value:4,label:"High",icon:"Gauge",color:"#8b5cf6"},{value:5,label:"Epic",icon:"Gauge",color:"#d946ef"}];case"approach":return Qe;case"assignee":return sa.map(u=>({value:u.value,label:u.label,icon:u.icon==="HelpCircle"?"Circle":u.icon,color:u.color}));case"status":return[...Xs.filter(u=>u.value!=="done"&&u.value!=="cancelled"),{value:"completed",label:"Completed",icon:hd("done").icon,color:hd("done").color}];case"schedule":return Tf;default:return S}},[h,S,Be,et,Qe,sa,Tf]),Jy=a.jsxs("div",{className:ft.accountMenuWrap,ref:nu,children:[a.jsx("button",{className:`tf-control-icon ${ft.avatarBtn}`,onClick:()=>{Kn(u=>{const w=!u;return w?Lc("account_menu"):(Di.current=null,Pl.current={billing:!1,teamManagement:!1}),w})},title:Jt?"Account":"Account (Not signed in)","aria-label":Jt?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":ds,children:a.jsx("span",{className:ft.avatarBadge,"aria-hidden":"true",children:Vm?a.jsx("img",{src:Fl,alt:"",className:ft.avatarImage}):Fi||a.jsx(ni,{size:14,className:ft.avatarIcon})})}),ds&&a.jsxs("div",{className:ft.accountMenu,role:"menu","aria-label":"Account menu",children:[a.jsxs("div",{className:ft.accountMenuSection,children:[a.jsx("div",{className:ft.accountMenuSectionLabel,children:"Account"}),a.jsx("div",{className:ft.accountMenuHint,children:$l?"Checking sign-in status...":Jt?a.jsx(a.Fragment,{children:Wl?a.jsx(a.Fragment,{children:a.jsxs("span",{className:ft.accountIdentityBlock,children:[a.jsx("span",{className:ft.accountIdentityEmail,children:Zs}),Hm&&Bi&&a.jsxs("span",{className:ft.accountIdentityMetaLine,children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Email"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:Ps})]}),Zd?a.jsxs("span",{className:ft.accountIdentityMetaLine,children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:"Loading…"})]}):ou?a.jsxs("button",{"aria-label":`Subscription ${Dc}`,className:`${ft.accountIdentityMetaLine} ${ft.accountIdentityMetaAction}`,onClick:()=>{Kn(!1),d()},type:"button",children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:Dc})]}):Pc?a.jsxs("span",{className:ft.accountIdentityMetaLine,children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:"Unavailable"})]}):null,a.jsxs("span",{className:ft.accountIdentityMetaLine,children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Runtime"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:iu})]}),a.jsxs("span",{className:ft.accountIdentityMetaLine,children:[a.jsx("span",{className:ft.accountIdentityMetaLabel,children:"Environment"}),a.jsx("span",{className:ft.accountIdentityMetaValue,children:qm})]})]})}):"Signed in"}):"Not signed in"})]}),Fm&&a.jsxs("div",{className:ft.accountMenuSection,children:[a.jsx("div",{className:ft.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),_a.length===0&&a.jsx("div",{className:ft.accountMenuHint,children:"No workspaces found for this account yet."}),_a.map(u=>a.jsxs("button",{className:`${ft.accountMenuItem} ${u.id===Xt?ft.accountMenuItemActive:""}`,onClick:()=>Vl(u.id),role:"menuitem",disabled:bc||u.id===Xt,title:u.description||u.name,children:[a.jsx(Ro,{size:15}),a.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[a.jsx("span",{children:u.name}),a.jsx("span",{className:ft.accountMenuMeta,children:u.role})]})]},u.id)),a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{bl(""),Ai(!0),Kn(!1)},role:"menuitem",disabled:bc,children:[a.jsx(to,{size:15}),"Create Workspace"]}),Ud&&a.jsx("div",{className:ft.accountMenuError,children:Ud})]}),Hd?a.jsx("div",{className:ft.accountMenuHint,children:"Resolving team management access..."}):bo?a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Fc()},role:"menuitem",children:[a.jsx(zk,{size:15}),"Team Management"]}):Nm?a.jsx("div",{className:ft.accountMenuHint,children:"Team Management unavailable right now."}):null,Jt&&a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Kn(!1),wl(!0)},role:"menuitem",children:[a.jsx(ni,{size:15}),"Edit Profile"]}),a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Kn(!1),d()},role:"menuitem",children:[a.jsx(Np,{size:15}),"Plans"]}),a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Kn(!1),Lc("account_hub"),wo(!0)},role:"menuitem",children:[a.jsx(ni,{size:15}),"Account Hub"]}),a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Kn(!1),Ho(!0)},role:"menuitem",children:[a.jsx(Yi,{size:15}),"Help & Support"]}),a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Kn(!1),Ho(!0)},role:"menuitem",children:[a.jsx(ug,{size:15}),"Contact Support"]}),Qt==="local"&&!Jt&&!$l&&a.jsxs("button",{className:ft.accountMenuItem,onClick:()=>{Wc("login")},role:"menuitem",children:[a.jsx(ni,{size:15}),"Sign In / Register"]}),Jt&&a.jsxs("button",{className:ft.accountMenuItem,onClick:async()=>{Kn(!1),await na(),Qt==="cloud"&&s("/login",{replace:!0})},role:"menuitem",children:[a.jsx(Hk,{size:15}),"Sign Out"]})]})]}),jf=r.useCallback(()=>{I(u=>u==="show"?"collapse":u==="collapse"?"hide":"show")},[I]),Nf=r.useCallback(()=>{x(),A("tasks"),k("add")},[x,k,A]),Qy=r.useCallback(u=>{const w=e.workstreams.find(N=>N.id===u);x(),ee(No(w)||u),A("tasks"),k("add")},[e.workstreams,x,k,A,ee]),Pf=r.useCallback(u=>{Gs.current=!1,Hs(!1),$s(u),ka(!1),Us(null),Gn(!1),zs(""),lr(""),on("");const w=u.entityType==="workstream"&&ra&&wt.initiativeById.get(ra)||null;Gr(w?Jr(w):""),ln(null)},[wt.initiativeById,ra]),Mf=r.useCallback((u,w)=>{Gs.current=!1,Hs(!1),Us(u),Gn(!1),zs(""),lr(""),on("");const N=u.entityType==="workstream"&&((w?wt.initiativeById.get(w):null)||ra&&wt.initiativeById.get(ra))||null;Gr(N?Jr(N):""),ln(null)},[wt.initiativeById,ra]),tp=r.useCallback(()=>{Gs.current=!1,Hs(!1),$s(null),zs(""),lr(""),on(""),Gr("")},[]),Ef=r.useCallback(()=>{Gs.current=!1,Hs(!1),Us(null),zs(""),lr(""),on(""),Gr("")},[]),Xy=r.useCallback(async()=>{const u=lo||os;if(!u||Gs.current)return;Gs.current=!0,Hs(!0);const w=!!lo,N=fa.trim()||null;try{if(u.entityType==="initiative")if(u.mode==="edit")await e.updateInitiative(u.targetId,{title:Lo.trim()||"Untitled Initiative",description:uo.trim()||null,ownerId:N}),cr({type:"initiative",id:u.targetId}),ln(null),_t("Initiative updated","success");else{const le=await e.createInitiative({title:Lo.trim()||"Untitled Initiative",description:uo.trim()||null,ownerId:N});cr({type:"initiative",id:le.id}),ln(null),_t("Initiative created","success")}else{const le=Vn.trim(),ke=le.length===0?null:yp(wt.initiatives,le);if(le.length>0&&!ke){_t("Initiative not found by that reference.","error");return}const pt={title:Lo.trim()||"Untitled Workstream",description:uo.trim()||null,ownerId:N,initiativeId:ke?.id||null};if(u.mode==="edit")await e.updateWorkstream(u.targetId,pt),w?ln(u.targetId):(cr({type:"workstream",id:u.targetId}),ln(null)),_t("Workstream updated","success");else{const Zt=await e.createWorkstream(pt);w?ln(Zt.id):(cr({type:"workstream",id:Zt.id}),ln(null)),_t("Workstream created","success")}}w?Ef():tp()}catch(le){_t(le instanceof Error?le.message:"Failed to save planning item.","error")}finally{Gs.current=!1,Hs(!1)}},[tp,Ef,uo,Vn,fa,Lo,os,lo,wt.initiatives,e,_t]),ek=r.useCallback(u=>{sc(w=>{const N=new Set(w);return N.has(u)?N.delete(u):N.add(u),N})},[]),tk=r.useCallback(u=>{io(w=>w===u?"":u),co("")},[]),ak=r.useCallback((u,w)=>{co(N=>{const le=N===u?"":u;return io(le&&w||""),le})},[]),nk=r.useCallback(u=>{$s(null),Us(null),ka(!1),Gn(!1),cr(u?{type:"initiative",id:u}:null),ln(null)},[]),rk=r.useCallback(u=>{$s(null),Us(null),ka(!1),Gn(!1),cr(u?{type:"workstream",id:u}:null),ln(null)},[]),sk=r.useCallback(u=>{Us(null),Gn(!1),ln(u)},[]),ap=r.useCallback((u,w)=>{if(u==="workstream"&&w){Mf({mode:"create",entityType:"workstream"},w);return}if(Pf({mode:"create",entityType:u}),u==="workstream"){const N=(w?wt.initiativeById.get(w):null)||(ra?wt.initiativeById.get(ra):null)||null;Gr(N?Jr(N):"")}},[Pf,Mf,wt.initiativeById,ra]),Df=r.useCallback((u,w)=>{if(u==="initiative"){const N=wt.initiativeById.get(w);if(!N)return;$s({mode:"edit",entityType:"initiative",targetId:w}),zs(N.title),lr(N.description||""),on(N.ownerId?String(N.ownerId):""),Gr("")}else{const N=wt.workstreamById.get(w)||wt.standaloneWorkstreams.find(ke=>ke.id===w);if(!N)return;$s({mode:"edit",entityType:"workstream",targetId:w}),zs(N.title),lr(N.description||""),on(N.ownerId?String(N.ownerId):"");const le=N.initiativeId&&wt.initiativeById.get(N.initiativeId)||null;Gr(le?Jr(le):"")}ln(null)},[wt.initiativeById,wt.standaloneWorkstreams,wt.workstreamById]),Su=r.useCallback(async(u,w)=>{const N=e.workstreams.find(Zt=>Zt.id===u);if(!N){_t("Workstream not found.","error");return}const le=typeof w=="string"?w.trim():w===null?"":Vn.trim(),ke=le.length===0?null:yp(wt.initiatives,le);if(le.length>0&&!ke){_t("Initiative not found by that reference.","error");return}const pt=ke?.id||null;if((N.initiativeId||null)===pt){_t(pt?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info");return}try{await e.updateWorkstream(u,{initiativeId:pt}),Gr(ke?Jr(ke):""),_t(pt?"Initiative set":"Initiative removed","success")}catch{_t("Failed to set initiative.","error")}},[Vn,wt.initiatives,e,_t]),wu=r.useCallback(async(u,w)=>{const N=mc.get(u);if(!N){_t("Task not found.","error");return}const le=w||null;if(wt.initiativeById.has(u)||wt.workstreamById.has(u)){_t("Only execution tasks can be moved into workstreams.","error");return}if(le&&!wt.workstreamById.has(le)){_t("Workstream not found.","error");return}if((N.workstreamId||null)===le){_t(le?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{const ke=await fetch(`/api/taskforce/task/${u}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({workstreamId:le})});if(!ke.ok){const pt=await ke.json().catch(()=>({}));_t(pt?.error||"Failed to set workstream.","error");return}await ke.json().catch(()=>null),await Y(!0),_t(le?"Workstream set":"Workstream removed","success")}catch{_t("Failed to set workstream.","error")}},[Y,mc,wt.initiativeById,wt.workstreamById,_t]),ok=r.useCallback(async(u,w)=>{const N=w.trim();if(!N){_t("Enter a task reference.","error");return}const le=Rg(N),ke=wi.find(pt=>pt.id===N||Qi(pt)===N||le!==null&&pt.referenceNumber===le);if(!ke){_t("Task not found by that reference.","error");return}await wu(ke.id,u)},[wu,wi,_t]),ik=r.useCallback(async(u,w)=>{const N=w.trim();if(!N){_t("Enter a workstream reference.","error");return}const le=wt.initiativeById.get(u);if(!le){_t("Initiative not found.","error");return}const ke=ay(N),pt=e.workstreams.find(Zt=>Zt.id===N||No(Zt)===N||ke!==null&&Zt.referenceNumber===ke);if(!pt){_t("Workstream not found by that reference.","error");return}await Su(pt.id,Jr(le))},[Su,wt.initiativeById,e.workstreams,_t]),Oc=r.useCallback((u,w)=>{const N=`${u}:${w}`,le=sl.current.get(N);if(le)return le;const ke=u==="initiative"?e.initiatives.find(pt=>pt.id===w):e.workstreams.find(pt=>pt.id===w);return Array.isArray(ke?.attachments)?ke.attachments:[]},[e.initiatives,e.workstreams]),$c=r.useCallback((u,w,N)=>{const le=`${u}:${w}`;sl.current.set(le,N);const pt=(dn.current.get(le)||Promise.resolve()).catch(()=>{}).then(()=>u==="initiative"?e.updateInitiative(w,{attachments:N}):e.updateWorkstream(w,{attachments:N}));dn.current.set(le,pt),pt.catch(Zt=>{_t(Zt instanceof Error?Zt.message:"Failed to update planning context.","error")}).finally(()=>{dn.current.get(le)===pt&&dn.current.delete(le)})},[e,_t]),ck=r.useCallback((u,w,N)=>{const le=Oc(u,w);$c(u,w,[...le,N])},[Oc,$c]),lk=r.useCallback((u,w,N)=>{const le=Oc(u,w);$c(u,w,le.filter((ke,pt)=>pt!==N))},[Oc,$c]),dk=r.useCallback((u,w,N,le)=>{const pt=Oc(u,w).map((Zt,Sa)=>Sa!==N?Zt:typeof Zt=="string"?{path:Zt,caption:le,timestamp:new Date().toISOString()}:{...Zt,caption:le});$c(u,w,pt)},[Oc,$c]),Lf=r.useCallback(u=>{io(u),co("")},[]),Bf=r.useCallback(u=>{co(u),io(u&&wt.workstreamInitiativeIds.get(u)||"")},[wt.workstreamInitiativeIds]),np=r.useCallback(u=>{const w=eg(u,Ts);if(w!==u){const N=Ts.find(le=>le.id===u)?.label||"That module";_t(`${N} is not available in this build yet.`,"error");return}Sr(),A(w)},[Sr,_t,A,Ts]),Wf=r.useCallback(()=>{if(ia==="tasks"&&Tr){Do(!1),cr(null),ln(null),$s(null);return}if(ia!=="tasks"){A("tasks"),Do(!0);return}Do(u=>!u)},[Tr,ia,A]),Ff=r.useCallback(()=>{if(ia!=="docs"){A("docs"),nc(!0);return}nc(u=>!u)},[ia,A]),Of=r.useCallback(()=>{if(ia!=="annotate"){A("annotate"),so(!0);return}so(u=>!u)},[ia,A]),$f=r.useCallback(()=>{if(ia!=="agents"){A("agents"),xs(!0);return}xs(u=>!u)},[ia,A]),uk=r.useCallback(u=>{Sr(),A("tasks"),Ft(u)},[Sr,Ft,A]),mk=r.useCallback(u=>{Sr(),A("tasks"),Ft(u)},[Sr,Ft,A]),pk=r.useCallback((u,w)=>{is(u),pi(w?.sessionId??null),Id(N=>N+1),A("annotate")},[A]),fk=r.useCallback(({target:u,sessionId:w})=>{is(N=>!N&&!u||N&&u&&N.taskId===u.taskId&&N.taskReferenceLabel===u.taskReferenceLabel&&N.assetId===u.assetId&&N.imageReferenceLabel===u.imageReferenceLabel&&N.path===u.path&&N.displayName===u.displayName?N:u),pi(N=>N===w?N:w)},[]),Uf=r.useMemo(()=>[{value:"created",label:$e("standalone.sortCreated")},{value:"updated",label:$e("standalone.sortUpdated")},{value:"priority",label:$e("standalone.sortPriority")},{value:"complexity",label:$e("standalone.sortComplexity")},...oy(Mt,[...e.searchAgnosticTasks,...Fn])],[Fn,e.searchAgnosticTasks,Mt]),zf=r.useMemo(()=>[{value:"status",label:$e("standalone.groupStatus")},{value:"category",label:$e("standalone.groupCategory")},{value:"type",label:$e("standalone.groupType")},{value:"priority",label:$e("standalone.groupPriority")},{value:"complexity",label:$e("standalone.groupComplexity")},{value:"assignee",label:$e("standalone.groupAssignee")},{value:"schedule",label:$e("standalone.groupSchedule")}],[]),Hf=r.useMemo(()=>Ts.filter(u=>u.enabled),[Ts]),Gf=r.useMemo(()=>[{key:"empty-columns",icon:_==="show"?a.jsx(qf,{size:16}):_==="collapse"?a.jsx(Kf,{size:16}):a.jsx(ef,{size:16}),title:$e(_==="show"?"standalone.showEmptyColumns":_==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:jf,active:_!=="show"},{key:"compressed-cards",icon:Ze?a.jsx(Gk,{size:16}):a.jsx(Vk,{size:16}),title:$e(Ze?"standalone.expandCards":"standalone.compressCards"),onClick:()=>ht(!Ze),active:Ze}],[Ze,jf,_]),hk=r.useMemo(()=>[{key:"filter-toggle",icon:a.jsx(pg,{size:16}),title:$e("standalone.toggleFilters"),onClick:()=>ci(!ro),active:ro,className:Yl?p.filterGlow:""}],[Yl,ci,ro]),gk=r.useMemo(()=>{switch(Ys.filterBar.kind){case"task-filters":return a.jsx(s4,{categoryFilterOptions:dc,typeFilterOptions:hl,priorities:et,taxonomyDisplayLabels:Ue,filterCategories:He,setFilterCategories:Ve,filterTypes:Ne,setFilterTypes:Vt,filterPriorities:qt,setFilterPriorities:Et,filterStatus:L,setFilterStatus:J,filterAssignees:Tt,setFilterAssignees:Wt,assigneeOptions:sa,initiativeFilterOptions:Ed,selectedInitiativeId:ra,setSelectedInitiativeId:Lf,workstreamFilterOptions:fc,selectedWorkstreamId:Hr,setSelectedWorkstreamId:Bf,taskScope:Kt,setTaskScope:Ka,showArchive:yo,setShowArchive:ml,fetchArchive:pl,onDeleteAllDeleted:()=>{const u=On.length;u===0||!window.confirm(`Permanently delete ${u} deleted task${u===1?"":"s"}? This cannot be undone.`)||c()},clearFilters:()=>{wa(),io(""),co("")}});case"document-filters":return a.jsx(o4,{typeFilters:mo,setTypeFilters:Bo,attachmentFilters:po,setAttachmentFilters:Wo,clearFilters:()=>{Bo(qu.map(u=>u.value)),Wo(Ku.map(u=>u.value))}});default:return a.jsx(n4,{})}},[sa,dc,wa,On.length,po,mo,Tt,He,qt,L,Ne,Lf,Bf,Ed,et,ra,Hr,Wo,Bo,Wt,Ve,Et,J,Vt,io,co,ml,Ka,yo,Kt,Ue,hl,fc,Ys.filterBar.kind,pl,c]),yk=r.useMemo(()=>[{key:"zen-toggle",icon:a.jsx(qk,{size:16,fill:B?"currentColor":"none"}),title:$e(B?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>V(),active:B}],[B,V]),kk=r.useMemo(()=>({search:a.jsx(t4,{value:ye,placeholder:$e("standalone.searchPlaceholder"),active:Kl,onChange:Ie,onClear:()=>Ie(""),clearTitle:$e("standalone.clearSearchTitle")}),sort:a.jsx(Kh,{label:a.jsxs(a.Fragment,{children:[a.jsx(Kk,{size:12})," ",$e("standalone.sortLabel")]}),value:Fa,options:Uf,onChange:u=>Xa(u),trailingAction:a.jsx("button",{className:`tf-control-icon ${p.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?$e("standalone.sortDirectionDescTitle"):$e("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?a.jsx(ig,{size:14}):a.jsx(cg,{size:14})})}),"divider-primary":a.jsx(Zh,{}),grouping:a.jsx(Kh,{label:a.jsxs(a.Fragment,{children:[a.jsx(Np,{size:12})," ",$e("standalone.groupLabel")]}),value:h,options:zf,onChange:u=>g(u)}),"divider-secondary":a.jsx(Zh,{}),"task-display-actions":a.jsx(_p,{actions:Gf})}),[h,zf,np,Kl,e,ye,g,Ie,Xa,Fa,Uf,Gf,Ys.moduleId]),vk=r.useMemo(()=>({"add-task":a.jsx(a4,{icon:a.jsx(to,{size:16}),label:$e("standalone.addTask"),onClick:Nf}),"add-document":null}),[Nf]),td=r.useMemo(()=>{const u={tasks:a.jsx(ev,{size:18}),docs:a.jsx(Pp,{size:18}),annotate:a.jsx(Xk,{size:18}),workflows:a.jsx(Zf,{size:18}),agents:a.jsx(Zu,{size:18})},w=ta.workspaceToolButtonDisabled,N=ia==="docs"?a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${rs?ta.workspaceToolButtonActive:""}`.trim(),onClick:Ff,title:rs?"Collapse document tray":"Document tray","aria-label":rs?"Collapse document tray":"Document tray",children:rs?a.jsx(jo,{size:18}):a.jsx(Ro,{size:18})}):ia==="annotate"?a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${zr?ta.workspaceToolButtonActive:""}`.trim(),onClick:Of,title:zr?"Collapse image tray":"Image tray","aria-label":zr?"Collapse image tray":"Image tray",children:zr?a.jsx(jo,{size:18}):a.jsx(Ro,{size:18})}):ia==="agents"?a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${As?ta.workspaceToolButtonActive:""}`.trim(),onClick:$f,title:As?"Collapse agent tray":"MCP settings tray","aria-label":As?"Collapse agent tray":"MCP settings tray",children:As?a.jsx(jo,{size:18}):a.jsx(Jk,{size:18})}):ia==="workflows"?a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${w}`.trim(),title:"Workflow tray coming soon","aria-label":"Workflow tray coming soon",disabled:!0,children:a.jsx(Zf,{size:18})}):a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${ia==="tasks"&&Tr?ta.workspaceToolButtonActive:""}`.trim(),onClick:Wf,title:ia==="tasks"&&Tr?"Collapse planning trays":"Planning","aria-label":ia==="tasks"&&Tr?"Collapse planning trays":"Planning",children:ia==="tasks"&&Tr?a.jsx(jo,{size:18}):a.jsx(Qk,{size:18})});return a.jsxs("aside",{className:ta.workspaceToolRail,"aria-label":"Workspace tools",children:[a.jsxs("div",{className:ta.workspaceToolRailMain,children:[N,a.jsx("div",{className:ta.workspaceToolRailDivider}),Hf.map(le=>a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${ia===le.id?ta.workspaceToolButtonActive:""}`.trim(),onClick:()=>np(le.id),title:le.label,"aria-label":le.label,children:u[le.id]},le.id))]}),a.jsxs("div",{className:ta.workspaceToolRailBottom,children:[a.jsx("div",{className:ta.workspaceToolRailDivider}),a.jsx("button",{type:"button",className:`${ta.workspaceToolButton} ${y==="settings"?ta.workspaceToolButtonActive:""}`.trim(),onClick:()=>{ba("general"),k("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:a.jsx(Xp,{size:18})})]})]})},[y,As,rs,$f,Ff,Of,np,Wf,zr,Tr,ia,ba,k,Hf]),[Vf,Sk]=r.useState(null),wk=r.useCallback(u=>{Sk(u)},[]),bk=a.jsx(LF,{open:Tr,leftOffset:56,initiatives:wt.initiatives,standaloneWorkstreams:wt.standaloneWorkstreams,allStandaloneWorkstreams:wt.allStandaloneWorkstreams,activeInitiativeId:ra,activeWorkstreamId:Hr,expandedInitiativeIds:Rr,detail:zo,editor:os,secondaryPane:gc,currentWorkspaceId:Xt,assigneeOptions:sa.map(u=>({value:String(u.value),label:u.label,kind:u.kind,username:u.username??null,archivedAt:u.archivedAt??null})),draftInitiativeSummary:yc,draftTitle:Lo,draftDescription:uo,draftOwner:fa,draftInitiativeId:Vn,onChangeDraftTitle:zs,onChangeDraftDescription:lr,onChangeDraftOwner:on,onChangeDraftInitiativeId:Gr,onCollapseTreePane:()=>ss(!0),onExpandTreePane:()=>ss(!1),onCollapsePrimaryPane:()=>ka(!0),onExpandPrimaryPane:()=>ka(!1),onCollapseSecondaryPane:()=>Gn(!0),onExpandSecondaryPane:()=>Gn(!1),onBackFromSecondary:()=>{Gs.current=!1,Hs(!1),Us(null),ln(null)},treeCollapsed:oo,primaryCollapsed:ui,secondaryCollapsed:rc,onCancelEditor:tp,onSubmitEditor:Xy,isSubmittingEditor:mi,onCreateInitiative:()=>ap("initiative"),onCreateWorkstream:()=>ap("workstream"),onCreateTaskInWorkstream:Qy,onCreateWorkstreamInInitiative:u=>ap("workstream",u),onAssignInitiativeToWorkstream:Su,onOpenTaskById:Ft,onRemoveTaskFromWorkstream:u=>{wu(u,null)},onAttachTaskToWorkstreamByReference:ok,onAttachWorkstreamToInitiativeByReference:ik,onAddPlanningContextFile:ck,onRemovePlanningContextFile:lk,onUpdatePlanningContextCaption:dk,onToggleInitiative:ek,onSelectInitiative:tk,onSelectWorkstream:ak,onOpenInitiativeDetails:nk,onOpenWorkstreamDetails:rk,onOpenNestedWorkstreamDetails:sk,onEditInitiative:u=>Df("initiative",u),onEditWorkstream:u=>Df("workstream",u),onArchiveInitiative:u=>{e.archiveInitiative(u).then(()=>{_t("Initiative archived","success")}).catch(w=>{_t(w instanceof Error?w.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:u=>{e.unarchiveInitiative(u).then(()=>{_t("Initiative unarchived","success")}).catch(w=>{_t(w instanceof Error?w.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:u=>{e.archiveWorkstream(u).then(()=>{_t("Workstream archived","success")}).catch(w=>{_t(w instanceof Error?w.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:u=>{e.unarchiveWorkstream(u).then(()=>{_t("Workstream unarchived","success")}).catch(w=>{_t(w instanceof Error?w.message:"Failed to unarchive workstream.","error")})}}),_k=Ys.headerSections.map(u=>{const w=kk[u];return w?a.jsx(Fe.Fragment,{children:w},u):null}).filter(Boolean),Ck=Ys.primaryAction?vk[Ys.primaryAction]:null;return a.jsxs("div",{className:`${ta.standaloneWrapper} ${B?p.zenModeEnabled:""}`,"data-theme":xe,children:[a.jsx(e4,{projectName:za,currentWorkspaceId:Xt,runtimeMode:Qt,theme:xe,onBrandClick:Gl,meta:a.jsxs(a.Fragment,{children:[a.jsx("span",{className:p.taskCountBadge,title:Qm,children:Ql}),Vr&&Vr!=="anonymous"&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:p.taskCountBadge,title:"Tasks assigned to me",children:[a.jsx(ni,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),Wd]}),a.jsxs("span",{className:`${p.taskCountBadge} ${Fd>0?p.taskCountBadgeAlert:""}`.trim(),title:"Tasks overdue",children:[a.jsx(Zk,{size:13,className:p.taskCountBadgeIcon,"aria-hidden":"true"}),Fd]})]}),Xm&&a.jsx("button",{className:"tf-control-icon",onClick:$m,title:`Sync manager: ${Va.label} | Last success: ${Xl}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${Va.border}`,background:Va.background,color:Va.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Va.icon==="off"?a.jsx(Yk,{size:16}):a.jsx(fg,{size:16})})]}),actions:a.jsxs(a.Fragment,{children:[i&&a.jsxs(a.Fragment,{children:[Jt&&kn?.stripeCustomerId&&a.jsx("button",{className:"tf-control-icon",onClick:()=>{Hl()},title:"Manage billing",disabled:Yd,children:"Manage billing"}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{if(Ul){Qo();return}m()},title:Ul?"Continue to Taskforce":"Back",disabled:Ko,children:Ul?"Take Me to Taskforce":"Back"})]}),!i&&a.jsxs(a.Fragment,{children:[_k,Ck]}),a.jsx(_p,{actions:yk}),!i&&a.jsx(_p,{actions:hk}),Jy]})}),a.jsx(Ay,{notice:rr,onDismiss:Cs}),Ca&&a.jsx("div",{className:fe.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),!i&&ro&&gk,i?a.jsx("div",{className:`${ta.standalonePage} ${ta.standaloneContent} ${p.appScrollbar} tf-scrollbar`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable",background:"var(--surface-page)"},children:a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(kO,{...e,currentTheme:xe,projectName:za,currentWorkspaceId:Xt,authUserId:Ta,apiBaseUrl:Ol,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:Pa,embedded:!0,shellOwnsScroll:!0,onAccountProfileSummaryChange:Zm,onContinueToTaskforce:Qo,continueBusy:Ko})})}):ia==="docs"&&Uo?a.jsxs("div",{className:`${ta.standalonePage} ${ta.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(hO,{tasks:me,runtimeMode:Qt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:mo,attachmentFilters:po,onTypeFiltersChange:Bo,onAttachmentFiltersChange:Wo,documentTrayOpen:rs,onCloseDocumentTray:()=>nc(!1),requestedDocPath:Cm,requestedDocAssetId:Am,onRequestedDocHandled:()=>{ol(null),il(null)},onBackToTask:mk,enableTaskGeneration:!0})})]}):ia==="annotate"&&lc?a.jsxs("div",{className:`${ta.standalonePage} ${ta.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(fO,{runtimeMode:Qt,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:Xt,sessionLoadReady:fi,requestedTarget:qn,requestedSessionId:fo,requestedOpenVersion:xm,imageTrayOpen:zr,onCloseImageTray:()=>so(!1),resolveTaskReferenceLabel:Pd,resolveImageReferenceLabel:Md,onOpenTarget:pk,onContextChange:fk,onBackToTask:uk})})]}):ia==="workflows"?a.jsxs("div",{className:`${ta.standalonePage} ${ta.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(gO,{availableWorkflows:ts,availableEnvironments:Rt,exportEnvironment:Ma,exportWorkflowsPath:e.exportWorkflowsPath,exportingResource:_s,exportResult:bs,onExportEnvironmentChange:e.setExportEnvironment,onExportWorkflows:Ya,onRefreshWorkflows:Wa,onFetchWorkflowTemplate:e.fetchWorkflowTemplate,onFetchWorkflowOverrideNames:e.fetchWorkflowOverrideNames,onSaveWorkflowTemplateDraft:e.saveWorkflowTemplateDraft,onResetWorkflowTemplateDraft:e.resetWorkflowTemplateDraft})})]}):ia==="agents"?a.jsxs("div",{className:`${ta.standalonePage} ${ta.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[td,a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(yO,{workspaceId:Xt,cloudAuthConfigured:Ia,authSessionResolved:ma,isAuthenticated:Jt,cloudAiProfileSeatUsage:kn?.aiProfileSeatUsage??null,agentTrayOpen:As,onCloseAgentTray:()=>xs(!1),mcpSettingsNode:a.jsx(ag,{settingsModel:{...he,initialSection:"mcp",onOpenCloudAuth:Wc},renderMode:"mcp-only"})})})]}):a.jsxs("div",{className:`${ta.standalonePage} ${ta.standaloneContent} `,style:{position:"relative",opacity:e.loadingTasks?.7:1,transition:"opacity 0.2s ease, padding 220ms cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",flex:1,minHeight:0,paddingLeft:Tr?`${56+Dd+6}px`:"62px",paddingRight:h==="schedule"&&or?`${Jp}px`:0},children:[td,a.jsx("div",{ref:wk,style:{position:"absolute",inset:0,zIndex:35,pointerEvents:"none"}}),a.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.loadingTasks&&bi.length>0&&a.jsx("div",{className:p.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:a.jsx(pr,{size:14,className:p.spinner})}),a.jsx(wW,{tasks:yl,allTasks:Ld,columns:Rf,groupBy:h,scheduleDates:xo,searchQuery:ye,filterCategories:He,filterTypes:Ne,filterPriorities:qt,filterStatus:L,filterAssignees:Tt,filtersReady:Ht,assigneeOptions:sa,scheduleFilteredTaskIds:Array.from(gl),copiedId:yt,taxonomies:Mt,types:Be,priorities:et,onUpdateTask:K,onTaskClick:u=>ve(u),onOpenTaskById:Ft,onCopyId:ot,onToggleInProgress:ae,onToggleReview:bt,onToggleComplete:ze,onToggleCancel:Ot,onSetStatus:Sc,onArchiveTask:Bt,onAddTaskToColumn:vl,showTaskCardStatusLabel:Se,onScheduleDaySelected:u=>{nl(u);const w=md(u);w&&no(`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}`)},persistedScrollLeft:h==="schedule"?ii:void 0,onScrollLeftChange:u=>{h==="schedule"&&Rn(u)},emptyColumnMode:_,categories:S,compressed:Ze,readOnlyMode:Kt==="deleted"?"deleted":Kt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:Fa,sortOrder:e.sortOrder,planningDropTargets:Vf?Zi.createPortal(bk,Vf):null,onAssignTaskToWorkstream:wu,onAssignWorkstreamToInitiative:Su,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:u=>{if(Kt==="deleted"){const w=yi.get(u);if(!w)return;vt(w.id);return}Lt(u)},onDelete:u=>{if(Kt==="deleted"){const w=yi.get(u);if(!w||!window.confirm("Permanently delete this task? This cannot be undone."))return;E(w.id);return}Oe(u)}},`${h}-${Rf.map(u=>String(u.value)).join("|")}-${xo.mon}`),h==="schedule"&&!or&&a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{cr(null),ir(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:a.jsx(jo,{size:16})})]}),h==="schedule"&&a.jsx(iO,{open:or,onClose:()=>ir(!1),scheduleSelectedDate:ns,setScheduleSelectedDate:nl,scheduleCalendarMonth:rl,setScheduleCalendarMonth:no,scheduleShowWeekends:De,setScheduleShowWeekends:oe,scheduleShowBacklog:sr,setScheduleShowBacklog:as,scheduleOnlyExpired:sn,setScheduleOnlyExpired:oi,expiredScheduledCount:Bd,overdueDueCount:kl,expiredLeafCandidates:_i,expiredRecoveryCandidates:ko,onMoveExpiredToSelectedWeek:Ky,onMoveExpiredToBacklog:Zy,scheduleBulkBusy:vo,globalWeekStartsOn:ua,resolvedLocale:Da,todayDateOnly:Ja,scheduleBaseTasks:uc,scheduleWeekStart:$i,scheduleWeekLabel:Yy})]}),a.jsxs(Ws,{isOpen:y==="add",onClose:vc,title:ue?Tn?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:li?"full":"xl",theme:xe,headerActions:a.jsx("button",{className:"tf-control-icon",onClick:()=>di(u=>!u),title:li?"Exit full screen":"Enter full screen","aria-label":li?"Exit full screen":"Enter full screen",children:li?a.jsx(Kf,{size:18}):a.jsx(qf,{size:18})}),draggable:!li,closeOnOverlayClick:!1,children:[a.jsx(Cy,{editingTaskId:ue,loading:pe,autoSaveState:qe,title:M,currentTask:Tn,currentTaskWorkstream:Mo,currentTaskInitiative:Eo,workstreamInput:ie,onWorkstreamInputChange:ee,onSetWorkstreamForCurrentTask:It,handleSubmit:re,resetForm:x,handleCopyId:ot,copiedId:yt,tasks:me,handleToggleInProgress:ae,handleToggleReview:bt,handleToggleComplete:ze,handleToggleCancel:Ot,handleSetStatus:Sc,handleArchiveTask:Bt,handleUnarchiveTask:u=>{if(Tn?.isDeleted){const w=yi.get(u);if(!w)return;vt(w.id);return}Lt(u)},handleRestoreDeletedTask:Tn?.deletedRecordId?u=>{vt(u)}:void 0,handlePermanentlyDeleteDeletedTask:Tn?.deletedRecordId?u=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(E(u),x(),k("tasks"))}:void 0}),a.jsx(_y,{editingTaskId:ue,error:X,title:M,description:de,checklistItems:$,category:je,type:ce,priority:Pe,complexity:Ee,manualComplexityEnabled:Q,approach:b,assignee:D,scheduledDate:P,dueDate:be,workstreamInput:ie,formTaxonomies:we,onTaxonomyChange:(u,w)=>Te(N=>({...N,[u]:w})),taxonomies:Mt,comments:Me,newCommentText:nt,contextFiles:lt,currentWorkspaceId:Xt,apiBaseUrl:Ol,descriptionFocused:Ct,showMarkdownHelp:Xe,showChecklist:ne,checklistEnabled:q,showComments:Ye,categories:S,types:Be,priorities:et,taxonomyDisplayLabels:Ue,assigneeOptions:sa,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:yt,onTitleChange:O,onDescriptionChange:ge,onChecklistItemsChange:_e,onCategoryChange:se,onTypeChange:Re,onPriorityChange:Ce,onComplexityChange:U,onApproachChange:u=>{j(u),Te(w=>({...w,approach:u}))},onAssigneeChange:te,onScheduledDateChange:H,onDueDateChange:z,onWorkstreamInputChange:ee,onNewCommentTextChange:gt,onDescriptionFocusedChange:dt,onShowMarkdownHelpChange:ct,onShowChecklistChange:st,onShowCommentsChange:Pt,onOpenSettings:u=>{ba(u),k("settings")},onSubmit:re,commentsEndRef:G,onAddComment:()=>kt(nt),onOpenTaskById:Ft,onAddContextFile:u=>{ll(w=>[...w,u])},onRemoveContextFile:async u=>{ll(w=>w.filter((N,le)=>le!==u))},onUpdateContextCaption:(u,w)=>{ll(N=>N.map((le,ke)=>ke!==u?le:typeof le=="string"?{path:le,caption:w,timestamp:new Date().toISOString()}:{...le,caption:w}))},onCopyId:ot,onToggleInProgress:ae,onToggleReview:bt,onToggleComplete:ze,onToggleCancel:Ot,onSetStatus:Sc,onArchiveTask:Bt,onUnarchive:u=>{if(Tn?.isDeleted){const w=yi.get(u);if(!w)return;vt(w.id);return}Lt(u)},currentTask:Tn})]}),a.jsx(Ws,{isOpen:y==="settings",onClose:vc,title:"Settings",size:"xl",theme:xe,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:a.jsx(r.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(pr,{size:20,className:p.spinner})}),children:a.jsx(ag,{settingsModel:{...he,onOpenCloudAuth:Wc},onSectionChange:ba})})}),a.jsx(_B,{prompt:ao,theme:xe,onClose:vr,onConfirm:Ga}),a.jsx(CB,{isOpen:Om,theme:xe,onClose:Um,onConfirm:zm}),a.jsx(bB,{isOpen:Od,theme:xe,onClose:()=>Ho(!1),supportMailtoHref:Gm,onOpenSettings:()=>{Ho(!1),k("settings"),ba("general")},onOpenAccountHub:()=>{Ho(!1),Lc("account_hub"),wo(!0)}}),a.jsx(SB,{isOpen:Sl,theme:xe,onClose:cu,onSave:()=>{Km()},displayName:Rl,email:Ps,avatarDisplayUrl:Ec,accountBadgeInitial:Fi,saveBusy:Wm,avatarBusy:jl,saveError:eu,saveNotice:tu,onDisplayNameChange:Qd,onOpenAvatarManager:()=>{qr(null),Kr(null),wc(!0)}}),a.jsx(fB,{isOpen:Tm,theme:xe,title:"Edit Profile Photo",currentImageUrl:Ec,fallbackInitial:Fi,accept:vO,busy:jl,hasPendingImage:!!dr,canRemove:!!Ec,error:eu,notice:tu,onClose:()=>wc(!1),onApplyImage:lu,onRemoveImage:uu,onDiscardPendingImage:du}),a.jsx(qL,{isOpen:So,theme:xe,runtimeMode:Qt,authRequiredForApi:en,isAuthenticated:Jt,hasAuthIdentity:Wl,authIdentityLabel:Zs,billingLoading:Zd,billingError:Pc,billingActionError:jr,billingNotice:Jd,billingActionBusy:Yd,billingIntervalChoice:Ks,accountProfileSummary:kn,currentWorkspaceId:Xt,canOpenTeamManagement:bo,canManageWorkspaceSync:Ml,workspaceCloudSyncEnabled:Sn,syncStatusLabel:Va.label,workspaceSyncError:Dl,syncControlBusy:ru,cloudAuthEnabled:Ia,availableAuthProviders:ea,onFetchLoginMethods:pa,onUnlinkLoginMethod:hn,onAddPassword:an,onLinkProvider:u=>hr(u),onClose:()=>wo(!1),onOpenWorkspaceAudit:()=>{wo(!1),Fc(),xi("audit")},onBillingIntervalChange:Ei,onRefreshBilling:()=>{ps()},onUpdateInterval:()=>{mu()},onManageBilling:()=>{Hl()},onStartCheckout:()=>{zl()},onToggleWorkspaceSync:u=>{su(u)},onOpenHelp:()=>{wo(!1),Ho(!0)}}),a.jsx(fW,{isOpen:Rm,theme:xe,teamPlanMode:Ac,teamMgmtError:us,teamManagementTab:jm,teamUsersLoading:xc,teamUsers:Go,teamActionBusyUserId:Ri,teamInviteFeedback:Gd,teamInviteEmail:ji,teamInviteRole:js,teamInvitePermissionMode:Pi,teamInviteBusy:jc,pendingInvites:Ym,teamAuditLoading:Vd,teamAuditEvents:Mm,teamAuditPage:Ns,teamAuditPages:Kd,teamAuditHasMore:Dm,onClose:()=>zd(!1),onOpenMembersTab:()=>{xi("members"),Oi()},onOpenInvitesTab:()=>xi("invites"),onOpenAuditTab:()=>{xi("audit"),_o(Ns)},onMemberRoleChange:(u,w)=>{Ao(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...Zr()},credentials:"include",body:JSON.stringify({workspaceId:Ms,role:w})}))},onMemberPermissionChange:(u,w)=>{Ao(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...Zr()},credentials:"include",body:JSON.stringify({workspaceId:Ms,mode:w})}))},onToggleMemberDisabled:(u,w)=>{Ao(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...Zr()},credentials:"include",body:JSON.stringify({workspaceId:Ms,disabled:w})}))},onRevokeInvite:u=>{Ao(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...Zr()},credentials:"include",body:JSON.stringify({workspaceId:Ms})}))},onRemoveMember:u=>{Ao(u,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(u)}?workspaceId=${encodeURIComponent(Ms)}`,{method:"DELETE",headers:Zr(),credentials:"include"}))},onInviteEmailChange:Tc,onInviteRoleChange:Ni,onInvitePermissionModeChange:Rc,onSubmitInvite:()=>{ql()},onLoadAuditPrevious:()=>{_o(Ns-1)},onLoadAuditNext:()=>{_o(Ns+1)}}),a.jsx(WL,{isOpen:_l,theme:xe,onClose:()=>Ai(!1),onConfirm:()=>Co({intent:"create-workspace"})}),a.jsx(pW,{isOpen:El,theme:xe,currentWorkspaceLabel:Bl,syncStatusMeta:Va,workspaceCloudSyncEnabled:Sn,syncControlBusy:ru,canManageWorkspaceSync:Ml,workspaceSyncSummary:hs.summary,workspaceSyncRecommendedAction:hs.recommendedAction,workspaceSyncRepairBusy:Zn,referenceMismatchCount:La,syncStageLabel:qy,workspaceSyncPendingChanges:Aa,formattedLastSyncTime:Xl,formattedLastPullTime:gu,formattedLastPushTime:yu,syncLastError:vu,workspaceSyncDiagnostics:fs,activeReferenceMismatchSummaries:un,syncDiagnosticsSummary:W,syncEventRows:va,syncEventsListRef:Le,workspaceSyncRepairQueued:ed,workspaceSyncBusy:tn,workspaceSyncCopied:Hy,runtimeMode:Qt,isAuthenticated:Jt,onClose:Ll,onToggleWorkspaceSync:u=>{su(u)},onRepairSync:Vy,onCopyReport:()=>{Gy()},onOpenLogin:()=>{Wc("login")},onRetrySync:()=>{Cn()}}),At&&Zi.createPortal(a.jsx("div",{className:`${xt.overlay} ${xt.unsavedOverlay}`,style:{zIndex:2e3},children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${xt.modal} ${xt.unsavedModal}`,"data-theme":xe,children:[a.jsx("div",{className:`tf-modal-header ${xt.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${xt.unsavedTitle}`,children:[a.jsx(vd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${xt.form} ${xt.unsavedContent}`,children:a.jsx("p",{className:xt.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${xt.formActions} ${xt.unsavedActions}`,children:[a.jsx("button",{className:p.cancelBtn,onClick:()=>Nt(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:p.destructiveBtn,onClick:R,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:p.submitBtn,onClick:C,disabled:pe,title:"Save changes and leave",children:[pe?a.jsx(pr,{size:16,className:p.spinner}):a.jsx(dg,{size:16}),"Save"]})]})]})}),document.body),gn&&Zi.createPortal(a.jsx("div",{className:ja.overlay,children:a.jsxs("div",{className:ja.browser,children:[a.jsxs("div",{className:ja.header,children:[a.jsxs("div",{className:ja.pathInfo,children:[a.jsx(Ro,{size:14}),a.jsx("span",{children:Ha||"Project Root"})]}),a.jsxs("div",{className:ja.actions,children:[Ha&&a.jsx("button",{className:p.helpLink,onClick:()=>{const u=Ha.split("/").filter(Boolean);u.pop(),Ar(u.length?u.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:p.helpLink,onClick:()=>zn(!1),children:"Close"})]})]}),a.jsxs("div",{className:ja.list,children:[Ra&&typeof Ra=="object"&&a.jsxs("div",{className:`${ja.item} ${ja.itemFile} ${ja.itemCurrent}`,onClick:()=>nn(Ha),children:[a.jsx(eo,{size:14})," Select Current: ./",Ha||"(root)"]}),Fr.map(u=>a.jsxs("div",{className:ja.item,onClick:()=>Ar(Ha+u+"/"),children:[a.jsx(Ro,{size:14})," ",u,"/"]},u)),An.map(u=>a.jsxs("div",{className:`${ja.item} ${ja.itemFile}`,onClick:()=>nn(Ha+u),children:[a.jsx(Pp,{size:14})," ",u]},u)),Fr.length===0&&An.length===0&&a.jsx("div",{className:`${ja.item} ${ja.empty}`,children:"No items found"})]})]})}),document.body)]})}function CO(e){const t=e.setupState,n=e.runtimeMode,s=e.isAuthenticated,o=!!(t&&n==="cloud"&&s&&t.globalSetupState==="missing"),l=!!(t&&n==="local"&&t.globalSetupState==="missing"),i=!!(t&&n==="cloud"&&s&&t.workspaceSetupState==="missing"),d=!!(t&&n==="local"&&t.workspaceSetupState==="missing"),m=!!(t&&(t.forceSetup||t.forceGlobalSetup||t.forceWorkspaceSetup||o||i||l||d));if(!m)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const y=!!(t&&(t.forceSetup||t.forceGlobalSetup||o||l)),k=!!(t&&(t.forceSetup||t.forceWorkspaceSetup||i||d)),S=!!(y&&t?.globalSetupState==="missing"),h=!!(k&&t?.workspaceSetupState==="missing"),g=!!(y&&t?.globalSetupState==="unreadable"),v=!!(k&&t?.workspaceSetupState==="unreadable"),A=g||v;return{setupGateActive:m,needsGlobalSetup:S,needsWorkspaceSetup:h,hasSetupReadError:A,phase:A?"setup-read-error":S?"needs-global-setup":h?"needs-workspace-setup":"ready"}}const Rp="/taskforce/assets/taskforce-BxLPokNB.png";function ng(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function jp(e){return(Array.isArray(e)?e:[]).map(t=>String(t.label||t.value||"").trim()).filter(Boolean).join(", ")}function rg(e={}){const t=new URLSearchParams;t.set("screen","plans");for(const[n,s]of Object.entries(e)){const o=String(s||"").trim();o&&t.set(n,o)}return`/?${t.toString()}`}function sg({config:e={},initialTaskId:t,onTaskCountChange:n,onHeaderMouseDown:s,isDragging:o,onClose:l,mode:i="standalone"}){const d=_g(),m=r.useMemo(()=>new URLSearchParams(d.search),[d.search]),y=String(m.get("planId")||"").trim(),k=String(m.get("planVersionId")||"").trim(),S=String(m.get("interval")||"").trim(),h=d.pathname==="/pricing",g=d.pathname==="/plans",v=d.pathname==="/"&&String(m.get("screen")||"").trim().toLowerCase()==="plans",A=rg({gate:"plan_selection_required"}),_=bg(),[I,B]=r.useState(""),[V,L]=r.useState(""),[J,me]=r.useState(""),[ve,re]=r.useState(""),[x,K]=r.useState("login"),[ue,pe]=r.useState(""),[X,M]=r.useState(!1),[O,de]=r.useState(null),[ge,$]=r.useState(null),[_e,je]=r.useState(null),[se,ce]=r.useState(!1),[Re,Pe]=r.useState(""),[Ce,Ee]=r.useState(""),[U,T]=r.useState(null),[b,j]=r.useState(null),[D,te]=r.useState("unknown"),[P,H]=r.useState(!1),[be,z]=r.useState([]),[ie,ee]=r.useState(null),[Q,q]=r.useState(null),[Se,we]=r.useState(null),[Te,Me]=r.useState(!1),[nt,gt]=r.useState(0),[lt,St]=r.useState(0),[Ke,Ct]=r.useState(()=>Date.now()),[dt,Xe]=r.useState("core"),[ct,ne]=r.useState(!1),[st,Ye]=r.useState(null),[Pt,kt]=r.useState(null),[It,Ft]=r.useState(""),[Mt,Be]=r.useState(""),[et,Ue]=r.useState("local"),[Qe,yt]=r.useState("details"),[ot,ae]=r.useState([]),[ze,bt]=r.useState(""),[Ot,Bt]=r.useState(!1),[Oe,Lt]=r.useState(null),[vt,E]=r.useState(!1),[c,Y]=r.useState(null),[ye,Ie]=r.useState(!1),He=r.useRef(!1),Ve=r.useMemo(()=>ry(),[]),[Ne,Vt]=r.useState(Ve),[qt,Et]=r.useState(()=>Ve.find(G=>G.isDefaultStarter)?.id||Ve[0]?.id||""),[Tt,Wt]=r.useState(()=>ng(Ve.find(G=>G.isDefaultStarter)||Ve[0]||null)),[Ht,sa]=r.useState(!1),[Kt,Ka]=r.useState(null),[Fa,Xa]=r.useState(!1),[wa,he]=r.useState(null),[it,xe]=r.useState(!1),jt=Bb({config:e,initialTaskId:t,onTaskCountChange:n,onClose:l}),{runtimeMode:tt,workspaceSwitchingEnabled:Gt,currentWorkspaceId:ga,cloudAuthConfigured:Na,authRequiredForApi:ua,authBlocked:ca,isAuthenticated:Dt,hasBetaAccess:aa,authSessionResolved:Za,setupState:$t,runtimeCapabilities:Qn,refreshSetupContext:ba,retryBootstrapChecks:Qt,createWorkspace:Lr,saveWorkspaceProfile:Ia,fetchWorkspaces:en,applyWorkspaceSyncStateSnapshot:Ca,workspaceCloudSyncEnabled:Jt,workspaceSyncPhase:Ta,workspaceSyncSetupIntent:la,workspaceSyncSummary:vn,workspaceSyncRecommendedAction:pn,workspaceSyncBusy:Xn,workspaceLastErrorMessage:ma,retryWorkspaceCloudSync:_r,settingsModel:Br,fetchTasks:Sn,bootstrapState:Ba,loginWithCredentials:Cr,beginOAuthLogin:wn,availableAuthProviders:Pn,registerWithCredentials:tn,requestEmailVerification:Aa,confirmEmailVerification:Wr,requestPasswordReset:_t,confirmPasswordReset:bn,inspectInviteAcceptance:fn,acceptInviteWithToken:_n,joinInviteWithToken:Oa,authUserEmail:Mn,currentTheme:ya,logout:$a}=jt,Cn=r.useCallback(async(G,qe)=>{const At=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:G,stateKey:"workspace-sync",patch:qe})}),Nt=await At.json().catch(()=>({}));if(!At.ok||Nt?.success===!1)throw new Error(Nt?.error||`Failed to configure workspace sync (${At.status})`);return Nt},[]),da=r.useMemo(()=>Ne.find(G=>G.id===qt)||Ne.find(G=>G.isDefaultStarter)||Ne[0]||null,[qt,Ne]);Ig(ya);const En=Zp,Xt=r.useMemo(()=>{const G=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return G?G.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),Ua=tt==="cloud"||Qn?.runtimeMode==="cloud",_a=!Ua&&Na&&!!Xt,er=typeof window<"u"&&/^app\./i.test(window.location.hostname),tr=tt==="cloud"&&ua,Pa=tt==="cloud"&&ca,na=d.pathname==="/login",pa=d.pathname==="/setup",hn=d.pathname==="/coming-soon",an="/setup?step=workspace&source=cloud&postAuth=select-cloud-workspace",fr=!Ua&&et==="cloud",hr=fr&&_a,ea=r.useMemo(()=>{if(c)return c;if(la!=="attach-cloud-import")return null;const G=String(ga||"").trim();if(!G||G.toLowerCase()==="default")return null;const qe=ot.find(At=>At.id===G);return{workspaceId:G,name:qe?.name||G}},[ot,ga,c,la]),Ss=!!(ea&&ga===ea.workspaceId),za=!!(ea&&Ss&&Ta==="error"),ar=!!(ea&&Ss&&Jt&&Ta==="active"&&!Xn),Xr=r.useMemo(()=>{if(!ea)return[];const G=ct?"In progress":"Complete",qe=za?"Needs attention":Xn||Ta==="attach-cloud"?"In progress":Ta==="active"?"Complete":"Waiting",At=ye?"In progress":ar?"Ready":"Waiting";return[`Connect workspace: ${G}`,`Import cloud data: ${qe}`,`Open local workspace: ${At}`]},[ea,ct,za,Xn,Ta,ye,ar]),gn=er?(!Dt||ca)&&!h&&!g&&!v:(tr&&!Dt||Pa)&&!h&&!g&&!v,zn=tt==="cloud"&&Dt&&!aa&&!h&&!g&&!v,Fr=tt==="cloud"&&Dt&&Za&&wa?.canAccessApp===!1&&wa?.canAccessPlans!==!1&&!h&&!g&&!v,An=tt==="cloud"&&Dt&&(!Za||!it),Ha=Na,Ar=r.useMemo(()=>{switch(x){case"register":return"Create Account | Taskforce";case"verify":return"Verify Email | Taskforce";case"forgot":return"Reset Password | Taskforce";case"reset":return"Set New Password | Taskforce";case"invite":return"Accept Invite | Taskforce";default:return"Sign In | Taskforce"}},[x]),Ra=r.useMemo(()=>String(new URLSearchParams(d.search).get("step")||"").trim().toLowerCase(),[d.search]),ws=r.useMemo(()=>String(new URLSearchParams(d.search).get("intent")||"").trim().toLowerCase(),[d.search]),nn=pa&&Ra==="workspace"&&ws==="create-workspace",xr=i!=="widget"&&Ba.authPending&&!na&&!pa&&!h&&!g&&!v&&(tt==="cloud"||er),gr=r.useMemo(()=>CO({setupState:$t?{globalSetupState:$t.globalSetupState,workspaceSetupState:$t.workspaceSetupState,runtimeMode:$t.runtimeMode,workspaceId:$t.workspaceId,mode:$t.mode,forceSetup:$t.forceSetup,forceGlobalSetup:$t.forceGlobalSetup,forceWorkspaceSetup:$t.forceWorkspaceSetup}:null,runtimeMode:tt,isAuthenticated:Dt}),[$t,tt,Dt]),Or=gr.setupGateActive,yn=gr.needsGlobalSetup,yr=gr.needsWorkspaceSetup,xn=gr.hasSetupReadError,Dn=i!=="widget"&&Ba.auth.resolved&&!gn&&!zn&&!h&&!g&&!v&&!na&&Ba.appPending&&(pa||tt==="cloud"||er),nr=tt==="cloud"&&se&&!v,es=Ba.subtitle,$r=nn||pa&&!!ea||pa&&Or&&(xn||yn||yr),Je=r.useMemo(()=>xr?"auth-bootstrap":nr||Dn?"app-bootstrap":na?"login":gn&&!na?"login-redirect":hn&&zn?"coming-soon":$r?"guided-setup":"app",[hn,na,zn,gn,nr,xr,Dn,$r]),Ut=r.useCallback((G,qe,At)=>{const Nt=String(G||"").trim().toLowerCase(),Ea=String(qe||"").trim().toLowerCase();return!!(!Nt||Nt==="system default workspace"||Ea&&Nt===Ea)},[]);r.useEffect(()=>{const G=$t?.mode==="operations"?"operations":"core";Xe(G)},[$t?.mode]),r.useEffect(()=>{if(tt!=="cloud"||!Dt){he(null),xe(!1);return}if(!Za){he(null),xe(!1);return}he(null),xe(!1);let G=!1;return(async()=>{try{const qe=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),At=await qe.json().catch(()=>({}));if(G)return;if(!qe.ok){he(null),xe(!0);return}const Nt=String(At?.gate||"").trim().toLowerCase();if(Nt!=="ok"&&Nt!=="plan_selection_required"&&Nt!=="checkout_pending"&&Nt!=="misconfigured"&&Nt!=="missing_entitlement"){he(null),xe(!0);return}he({gate:Nt,canAccessApp:At?.canAccessApp===!0,canAccessPlans:At?.canAccessPlans!==!1,message:typeof At?.message=="string"?At.message:null}),xe(!0)}catch{G||(he(null),xe(!0))}})(),()=>{G=!0}},[Za,Dt,tt,d.pathname,d.search]),r.useEffect(()=>{if(nn){Ft(""),Be("");return}if(!$t)return;const G=String($t.workspace?.name||"").trim(),qe=String($t.suggestedWorkspaceName||"").trim(),At=Ut(G,$t.workspaceId,$t.workspace?.description)?qe:G;Ft(At||qe||G),Be(String($t.workspace?.description||""))},[$t?.workspace?.name,$t?.workspace?.description,$t?.suggestedWorkspaceName,$t?.workspaceId,nn,Ut]),r.useEffect(()=>{if(!pa||Ra!=="workspace")return;if(yt("details"),ea&&_a){Ue("cloud"),E(!1);return}if(String(new URLSearchParams(d.search).get("source")||"").trim().toLowerCase()==="cloud"&&_a){Ue("cloud"),E(!1);return}Ue("local")},[ea,_a,pa,d.search,Ra]);const Ma=r.useCallback(async()=>{if(!_a||!Dt){ae([]),bt("");return}Bt(!0),Lt(null);try{const G=await fetch(`${Xt}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),qe=await G.json().catch(()=>({}));if(!G.ok||qe?.success===!1){ae([]),bt(""),Lt(qe?.error||`Failed to load cloud projects (${G.status})`);return}const At=Array.isArray(qe?.workspaces)?qe.workspaces.map(Nt=>({id:String(Nt?.id||"").trim(),name:String(Nt?.name||Nt?.id||"").trim(),description:typeof Nt?.description=="string"?Nt.description:null})).filter(Nt=>Nt.id.length>0):[];ae(At),bt(Nt=>Nt&&At.some(Ea=>Ea.id===Nt)?Nt:At[0]?.id||"")}catch{ae([]),bt(""),Lt("Failed to load cloud projects.")}finally{Bt(!1)}},[_a,Dt,Xt]);r.useEffect(()=>{et==="cloud"&&Ma()},[Ma,et]),r.useEffect(()=>{if(!pa||Ra!=="workspace"||et==="cloud")return;let G=!1;return sa(!0),Ka(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async qe=>{if(!qe.ok)throw new Error(`Failed to load setup libraries (${qe.status})`);const At=await qe.json().catch(()=>({})),Nt=Array.isArray(At?.packs)?At.packs:[];G||Nt.length===0||(Vt(Nt),Et(Ea=>Nt.some(In=>In.id===Ea)?Ea:Nt.find(In=>In.isDefaultStarter)?.id||Nt[0]?.id||""))}).catch(qe=>{G||(Vt(Ve),Ka(qe instanceof Error?qe.message:"Failed to load setup libraries."))}).finally(()=>{G||sa(!1)}),()=>{G=!0}},[Ve,pa,Ra,et]),r.useEffect(()=>{Wt(ng(da))},[qt,da]),r.useEffect(()=>{et==="cloud"&&yt("details")},[et]),r.useEffect(()=>{hr||(Y(null),Ie(!1),He.current=!1)},[hr]),r.useEffect(()=>{!za||!ea||(kt(null),Ye(ma||`Failed to import "${ea.name}" from cloud. Retry import to continue.`))},[ea,za,ma]),r.useEffect(()=>{if(!ar||!ea||He.current)return;let G=!1;return He.current=!0,Ie(!0),Ye(null),kt(`Workspace import complete. Opening ${ea.name}...`),(async()=>{try{if(await ba(),await Promise.all([en(),Sn(!0)]),G)return;await Cn(ea.workspaceId,{setupIntent:null}),Ca({enabled:Jt,phase:Ta,setupIntent:null}),Y(null),_("/",{replace:!0})}catch{if(G)return;kt(null),Ye(`Imported "${ea.name}" but failed to finish opening it.`),Ie(!1),He.current=!1}})(),()=>{G=!0}},[ea,Ca,Sn,en,ar,_,Cn,ba]);const oa=r.useMemo(()=>{const G=new URLSearchParams(d.search).get("next")||"/";return!G.startsWith("/")||G==="/login"?"/":G},[d.search]),cn=r.useMemo(()=>{try{const G=new URL(oa,"https://taskforce.local");return G.pathname==="/setup"&&G.searchParams.get("step")==="workspace"&&G.searchParams.get("source")==="cloud"&&G.searchParams.get("postAuth")==="select-cloud-workspace"}catch{return!1}},[oa]),rn=r.useCallback(()=>cn?an:"/setup?step=workspace",[cn]),bs=S==="year"?"year":"month",_s=r.useCallback(G=>!!(G?.planSelectionRequired||G?.checkoutPending||G?.commercialState==="pending_plan_selection"||G?.commercialState==="checkout_pending"),[]),ts=r.useCallback(G=>G?.planSelectionRequired||G?.commercialState==="pending_plan_selection"?A:G?.checkoutPending||G?.commercialState==="checkout_pending"?rg({gate:"checkout_pending",checkout:k?"start":null,planId:y||null,planVersionId:k||null,interval:k?bs:null}):oa,[oa,A,bs,y,k]),Ya=r.useMemo(()=>{const G=String(new URLSearchParams(d.search).get("mode")||"").trim().toLowerCase();return G==="register"?Ha?"register":"login":G==="verify"||G==="forgot"||G==="reset"||G==="invite"?G:"login"},[Ha,d.search]),Wa=r.useMemo(()=>String(new URLSearchParams(d.search).get("token")||"").trim(),[d.search]),Rt=r.useCallback(G=>{const qe=new URLSearchParams(d.search),At=G==="register"&&!Ha?"login":G;At==="login"?qe.delete("mode"):qe.set("mode",At);const Nt=qe.toString();_(`/login${Nt?`?${Nt}`:""}`,{replace:!0})},[Ha,d.search,_]);r.useEffect(()=>{na&&(K(Ya),Ya==="verify"&&Wa&&pe(Wa),Ya==="reset"&&Wa&&Pe(Wa),Ya==="invite"&&Wa&&Ee(Wa))},[na,Ya,Wa]),r.useEffect(()=>{x!=="verify"&&(na&&Ya==="verify"||(M(!1),de(null),$(null)))},[x,na,Ya]),r.useEffect(()=>{x!=="register"&&re("")},[x]),r.useEffect(()=>{if(!_e||!Dt||!_e.commercialOnboardingGate&&(!Za||An))return;const G=!_e.commercialOnboardingGate&&_e.workspaceSetupRequired?rn():_e.path;`${d.pathname}${d.search}${d.hash||""}`!==G&&_(G,{replace:!0})},[Za,An,Dt,d.hash,d.pathname,d.search,_,_e,rn]),r.useEffect(()=>{if(!se||!Za)return;if(!Dt){ce(!1),je(null);return}if(it&&wa?.canAccessApp===!0){B(""),L(""),me(""),re(""),je(null),ce(!1);return}const G=_e?.commercialOnboardingGate?_e.path:A;`${d.pathname}${d.search}${d.hash||""}`!==G&&_(G,{replace:!0})},[wa?.canAccessApp,it,Za,se,Dt,d.hash,d.pathname,d.search,_,_e,A]),r.useEffect(()=>{if(!_e||!Dt)return;const G=!_e.commercialOnboardingGate&&_e.workspaceSetupRequired?rn():_e.path;`${d.pathname}${d.search}${d.hash||""}`===G&&(_e.commercialOnboardingGate||(B(""),L(""),me(""),re(""),je(null)))},[d.hash,d.pathname,d.search,Dt,_e,rn,tt]),r.useEffect(()=>{na&&(document.title=Ar)},[Ar,na]),r.useEffect(()=>{if(!na||x!=="invite"||!Ce.trim())return;let G=!0;return(async()=>{const qe=await fn(Ce);if(G)if(qe.success){T(qe.email||null),j(qe.workspaceId||null),H(qe.passwordRequired===!0);const At=(qe.availableMethods||[]).filter(In=>In==="google"||In==="github"||In==="apple");z(qe.inviteeState==="pending_setup"?At:[]);const Nt=!!(Dt&&Mn&&qe.email&&Mn.trim().toLowerCase()===qe.email.trim().toLowerCase()),Ea=qe.passwordRequired===!0?"new_user":Nt?"existing_user_ready":"existing_user_signed_out";te(Ea),ee(Ea==="new_user"?"Create your account password to join this workspace.":Ea==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),q(null),we(null)}else T(null),j(null),te("invalid"),H(!1),z([]),q(Ir(qe)),we(qe.code||qe.state||null)})(),()=>{G=!1}},[na,x,Ce,fn,Dt,Mn]),r.useEffect(()=>{x==="invite"&&D==="existing_user_signed_out"&&U&&B(G=>G.trim()?G:U)},[x,D,U]),r.useEffect(()=>{if(!(nt>Date.now()||lt>Date.now()))return;const qe=window.setInterval(()=>Ct(Date.now()),1e3);return()=>window.clearInterval(qe)},[nt,lt]);const kr=Math.max(0,Math.ceil((nt-Ke)/1e3)),Hn=Math.max(0,Math.ceil((lt-Ke)/1e3)),Ln=kr>0,rr=Hn>0,Cs=r.useMemo(()=>Iy(),[]),Ir=G=>{const qe=G.error||"Request failed.",At=G.code||G.state;return At?`[${At}] ${qe}`:qe},Ur=G=>G?.deliveryAttempted===!1?G?.intro||"If that account exists and still needs verification, we sent an email.":G?.emailSent===!1?`Verification email failed to send. ${G?.emailError||"Try Resend Verification again."}`:"Verification email resent.",Fs=G=>G?.deliveryAttempted===!1?"If that account exists, we sent password reset instructions.":G?.emailSent===!1?`Password reset email failed to send. ${G?.emailError||"Try again in a minute."}`:"Password reset instructions sent.";r.useEffect(()=>{if(i==="widget"||na&&Te)return;const G=tt==="cloud"&&Dt&&it&&wa?.canAccessApp===!1&&wa?.canAccessPlans!==!1;if(Ba.workspace.pending&&!G)return;if(zn){hn||_("/coming-soon",{replace:!0});return}if(hn&&!zn){_("/",{replace:!0});return}if(gn){if(!na){const At=`${d.pathname}${d.search}${d.hash}`;_(`/login?next=${encodeURIComponent(At||"/")}`,{replace:!0});return}return}else{const At=na&&x==="invite"&&Ce.trim().length>0;if(na&&Dt&&!At&&(!!_e||Ba.workspace.pending||x==="register"||x==="verify"||!Ba.config.loaded||An))return;na&&Dt&&!At&&_(oa,{replace:!0})}if(!(na&&!Dt||_e&&Dt||na&&Dt&&(x==="register"||x==="verify"||x==="invite"&&Ce.trim().length>0))&&!se&&!v){if(Fr){if(!v){const At=encodeURIComponent(String(wa?.gate||"plan_selection_required"));_(`/?screen=plans&gate=${At}`,{replace:!0})}return}if(ea){pa&&Ra==="workspace"&&new URLSearchParams(d.search).get("source")==="cloud"||_(an,{replace:!0});return}if(!(v&&An)&&!(v&&tt==="cloud"&&it&&wa?.canAccessApp===!1&&wa?.canAccessPlans!==!1)){if(Or){if(xn){(!pa||Ra!=="error")&&_("/setup?step=error",{replace:!0});return}if(yn){(!pa||Ra!=="global")&&_("/setup?step=global",{replace:!0});return}if(yr){(!pa||Ra!=="workspace")&&_(rn(),{replace:!0});return}pa&&_("/",{replace:!0});return}pa&&$t&&!nn&&_("/",{replace:!0})}}},[i,gn,zn,Fr,na,pa,hn,g,v,wa,wa?.gate,it,x,se,An,Or,$t,xn,nn,ea,yn,yr,Ra,Ba,tt,Te,Dt,it,Ce,d.pathname,d.search,d.hash,_,oa,_e,an]),r.useEffect(()=>{if(i==="widget"||tt!=="local"||!Ba.config.loaded||na||pa)return;const G=String(ga||"").trim().toLowerCase();(!G||G==="default")&&_("/setup?step=workspace",{replace:!0})},[i,tt,Ba.config.loaded,na,pa,ga,_]);const Bn=r.useCallback(async()=>{Xa(!0);try{await Qt()}finally{Xa(!1)}},[Qt]),Wn=r.useCallback(async()=>{await $a(),_("/login",{replace:!0})},[$a,_]);if(i==="widget")return a.jsx(sD,{...jt,onHeaderMouseDown:s,isDragging:o,onClose:l});if(h){const G=new URLSearchParams(d.search);return G.set("screen","plans"),a.jsx(Jf,{to:`/?${G.toString()}${d.hash||""}`,replace:!0})}if(g){const G=new URLSearchParams(d.search);return G.set("screen","plans"),a.jsx(Jf,{to:`/?${G.toString()}${d.hash||""}`,replace:!0})}if(Je==="auth-bootstrap")return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"Checking your session..."})]})})});if(Je==="app-bootstrap")return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:es}),Ba.stalled&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.loginError,children:Ba.error||"Startup checks timed out."}),a.jsx("button",{className:p.submitBtn,disabled:Fa,onClick:Bn,children:Fa?"Retrying...":"Retry checks"}),Ua&&a.jsx("button",{className:p.cancelBtn,disabled:Fa,onClick:Wn,children:"Go to sign-in"})]})]})})});if(Je==="login")return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Rp})`},children:a.jsxs("div",{className:fe.loginCard,children:[!Ua&&!gn&&a.jsx("button",{className:fe.loginCloseBtn,"aria-label":"Close sign in","data-testid":"auth-close-button",onClick:()=>_(oa,{replace:!0}),children:"×"}),a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsxs("h1",{className:fe.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:fe.loginTitleAccent,children:"HQ"})]})]}),a.jsxs("p",{className:fe.loginSubtitle,children:[x==="login"&&"Sign in with your account credentials.",x==="register"&&"Create your Taskforce account.",x==="verify"&&"Enter your verification token.",x==="forgot"&&"Request a password reset link.",x==="reset"&&"Set a new password using your reset token.",x==="invite"&&(D==="existing_user_ready"?`You've been invited to join ${b||"this workspace"}.`:D==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(x==="login"||x==="register"||x==="verify"||x==="forgot"||x==="invite"&&D==="existing_user_signed_out")&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Email"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"email",value:I,placeholder:"Email",autoComplete:"email","data-testid":"auth-email-input",onChange:G=>B(G.target.value)})]}),x==="register"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Display name"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:V,placeholder:"Display name",autoComplete:"nickname","data-testid":"auth-display-name-input",onChange:G=>L(G.target.value)})]}),(x==="login"||x==="register"||x==="reset"||x==="invite"&&(P||D==="existing_user_signed_out"))&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:x==="reset"?"New password":x==="invite"&&P?"Create password":"Password"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"password",value:J,placeholder:x==="reset"?"New password":x==="invite"&&P?"Create password":"Password",autoComplete:x==="register"||x==="reset"||x==="invite"&&P?"new-password":"current-password","data-testid":"auth-password-input",onChange:G=>me(G.target.value)})]}),(x==="register"||x==="invite"&&P)&&a.jsx(a.Fragment,{children:a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Confirm password"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"password",value:ve,placeholder:"Confirm password",autoComplete:"new-password","data-testid":"auth-confirm-password-input",onChange:G=>re(G.target.value)})]})}),(x==="register"||x==="invite"&&P)&&a.jsx("p",{className:fe.loginSubtitle,children:Cs.join(" ")}),x==="verify"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Verification token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:ue,placeholder:"Verification token",autoComplete:"one-time-code","data-testid":"auth-verification-token-input",onChange:G=>pe(G.target.value)})]}),x==="reset"&&a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Reset token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:Re,placeholder:"Reset token",autoComplete:"one-time-code","data-testid":"auth-reset-token-input",onChange:G=>Pe(G.target.value)})]}),x==="invite"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:fe.loginField,children:[a.jsx("span",{className:fe.loginFieldLabel,children:"Invite token"}),a.jsx("input",{className:`${p.input} ${fe.loginInput}`,type:"text",value:Ce,placeholder:"Invite token","data-testid":"auth-invite-token-input",onChange:G=>Ee(G.target.value)})]}),U&&a.jsxs("p",{className:fe.loginSubtitle,children:["Invite for: ",a.jsx("strong",{children:U}),b?` · Workspace: ${b}`:""]})]}),ie&&a.jsx("p",{className:fe.loginSubtitle,children:ie}),Q&&a.jsx("p",{className:fe.loginError,children:Q}),x==="login"&&Se==="EMAIL_NOT_VERIFIED"&&I.trim()&&a.jsx("button",{className:fe.authModeLink,disabled:Te||Ln,onClick:async()=>{Me(!0),ee(null);const G=await Aa(I);G.success?(gt(Date.now()+3e4),Rt("verify"),G.verificationToken&&pe(G.verificationToken),ee(Ur(G)),q(null),we(null)):q(Ir(G)),Me(!1)},children:Ln?`Resend in ${kr}s`:"Resend Verification Email"}),a.jsx("div",{className:fe.authPrimaryActions,role:"group","aria-label":"Primary authentication action",children:a.jsx("button",{className:`${p.submitBtn} ${fe.loginPrimaryBtn}`,disabled:Te||x==="forgot"&&rr,"data-testid":"auth-submit-button",onClick:async()=>{if(Me(!0),ee(null),q(null),we(null),x==="register"&&!V.trim()){q("Display name is required."),Me(!1);return}if(x==="register"){const qe=Ty(J,{email:I,displayName:V});if(!qe.ok){q(qe.message||"Password does not meet the password policy."),we(qe.code||null),Me(!1);return}if(J!==ve){q("Passwords do not match."),we("PASSWORD_CONFIRMATION_MISMATCH"),Me(!1);return}}let G={success:!1};if(x==="login"?G=await Cr(I,J):x==="register"?G=await tn(I,J,{displayName:V,planId:y||void 0,planVersionId:k||void 0,interval:S||void 0}):x==="verify"?G=await Wr(ue):x==="forgot"?G=await _t(I):x==="reset"?G=await bn(Re,J):x==="invite"&&(D==="existing_user_signed_out"?G=await Cr(I,J):G=P?await _n(Ce,J):await Oa(Ce)),G.success)if(x==="register"){const qe=ts(G),At=_s(G);G.verificationRequired?(M(!!G.workspaceSetupRequired),de(At?String(G.commercialState||"").trim()||(G.planSelectionRequired?"pending_plan_selection":"checkout_pending"):null),$(qe),G.verificationToken&&pe(G.verificationToken),gt(Date.now()+3e4),Rt("verify"),ee(G.emailSent===!1?`Account created, but verification email failed to send. ${G.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(ce(At),je({path:qe,workspaceSetupRequired:!!G.workspaceSetupRequired,commercialOnboardingGate:At}))}else if(x==="verify"){await Qt();const qe=O==="pending_plan_selection"||O==="checkout_pending";ce(qe),je({path:ge||oa,workspaceSetupRequired:X,commercialOnboardingGate:qe})}else if(x==="forgot"){const qe=G.deliveryAttempted===!0&&G.emailSent===!1;G.resetToken&&Pe(G.resetToken),ee(Fs(G)),qe||(St(Date.now()+3e4),Rt("reset"))}else if(x==="reset")Rt("login"),ee("Password updated. Sign in with your new password.");else if(x==="invite"){if(D==="existing_user_signed_out"){const qe=String(U||"").trim().toLowerCase(),At=I.trim().toLowerCase();if(qe&&At===qe){K("invite"),te("existing_user_ready"),me(""),re(""),ee("Signed in. Review the invite details to continue."),q(null),we(null),Me(!1);return}qe&&B(U||""),te("existing_user_signed_out"),me(""),re(""),ee(qe?`Signed in, but this invite is for ${U}. Sign in with that account to continue.`:"Signed in, but this invite requires the invited account. Sign in with that account to continue."),q("Sign in with the invited account to join this workspace."),we("INVITE_ACCOUNT_MISMATCH"),Me(!1);return}if(G.workspaceSetupRequired){_(rn(),{replace:!0}),Me(!1);return}_(oa,{replace:!0})}else if(x==="login"){if(Ce.trim()){K("invite"),me(""),re(""),ee("Signed in. Review the invite details to continue."),Me(!1);return}if(G.workspaceSetupRequired){_(rn(),{replace:!0}),Me(!1);return}B(""),L(""),me(""),re(""),_(oa,{replace:!0})}else B(""),L(""),me(""),re(""),_(oa,{replace:!0});else{if(x==="register"&&(G.code==="SIGNUP_PLAN_NOT_ENABLED"||G.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||G.code==="SIGNUP_PLAN_VERSION_REQUIRED")){_(A,{replace:!0}),Me(!1);return}if(q(Ir(G)),we(G.code||null),x==="login"&&(G.code==="WORKSPACE_NOT_FOUND"||G.code==="WORKSPACE_ID_REQUIRED")){_("/setup?step=workspace",{replace:!0}),Me(!1);return}if(x==="login"&&G.code==="EMAIL_NOT_VERIFIED"&&I.trim()){const qe=await Aa(I);qe.success&&(gt(Date.now()+3e4),Rt("verify"),qe.verificationToken&&pe(qe.verificationToken),ee(Ur({...qe,intro:"If that account exists and still needs verification, we sent an email."})),q(null),we(null))}x==="register"&&G.code==="EMAIL_ALREADY_EXISTS_UNVERIFIED"&&I.trim()&&(gt(Date.now()+3e4),Rt("verify"),G.verificationToken&&pe(G.verificationToken),ee(G.emailSent===!1?`This email already has an unverified account, but verification email delivery failed. ${G.emailError||"Try Resend Verification again."}`:"This email already has an unverified account. Check your email for verification instructions."),q(null),we(null))}Me(!1)},children:Te?"Working...":x==="login"?"Sign In":x==="register"?"Create Account":x==="verify"?"Verify Email":x==="forgot"?rr?`Retry in ${Hn}s`:"Send Reset Link":x==="reset"?"Reset Password":D==="existing_user_signed_out"?"Sign In to Continue":P?"Create Account and Join":"Join Workspace"})}),(x==="login"||x==="register")&&Pn.length>0&&a.jsxs("div",{className:fe.oauthProviders,children:[a.jsx("div",{className:fe.oauthDivider,children:a.jsx("span",{children:"or continue with"})}),a.jsxs("div",{className:fe.oauthButtons,children:[Pn.includes("google")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("google",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Google",children:"Google"}),Pn.includes("github")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("github",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with GitHub",children:"GitHub"}),Pn.includes("apple")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("apple",d.pathname!=="/login"?d.pathname:"/"),"aria-label":"Continue with Apple",children:"Apple"})]})]}),x==="invite"&&D==="new_user"&&be.length>0&&a.jsxs("div",{className:fe.oauthProviders,children:[a.jsx("div",{className:fe.oauthDivider,children:a.jsx("span",{children:"or join with"})}),a.jsxs("div",{className:fe.oauthButtons,children:[be.includes("google")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("google","/",Ce),"aria-label":"Join with Google",children:"Google"}),be.includes("github")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("github","/",Ce),"aria-label":"Join with GitHub",children:"GitHub"}),be.includes("apple")&&a.jsx("button",{type:"button",className:fe.oauthButton,disabled:Te,onClick:()=>wn("apple","/",Ce),"aria-label":"Join with Apple",children:"Apple"})]})]}),x==="register"&&a.jsxs("p",{className:fe.registerConsent,children:["By creating an account, you agree to the"," ",a.jsx("a",{className:fe.registerConsentLink,href:"https://taskforcehq.com/legal/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",a.jsx("a",{className:fe.registerConsentLink,href:"https://taskforcehq.com/legal/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),a.jsxs("div",{className:fe.authSecondaryActions,role:"group","aria-label":"Authentication navigation",children:[Ha&&(x==="login"||x==="register")&&a.jsxs("p",{className:fe.authModeSwitch,children:[x==="login"?"Need an account?":"Already have an account?"," ",a.jsx("button",{className:fe.authModeSwitchLink,disabled:Te,"data-testid":"auth-switch-mode-button",onClick:()=>{q(null),we(null),ee(null),Rt(x==="login"?"register":"login")},children:x==="login"?"Register":"Sign In"})]}),a.jsxs("div",{className:fe.authModeLinks,children:[(x==="login"||x==="register")&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:fe.authModeLink,disabled:Te||rr,"data-testid":"auth-forgot-password-button",onClick:()=>{q(null),we(null),ee(null),Rt("forgot")},children:rr?`Forgot Password (${Hn}s)`:"Forgot Password"}),a.jsx("button",{className:fe.authModeLink,disabled:Te||Ln,"data-testid":"auth-resend-verification-button",onClick:()=>{q(null),we(null),ee(null),Rt("verify")},children:Ln?`Resend Verification (${kr}s)`:"Resend Verification"}),a.jsx("button",{className:fe.authModeLink,disabled:Te,"data-testid":"auth-accept-invite-button",onClick:()=>{q(null),we(null),ee(null),Rt("invite")},children:"Accept Invite"})]}),x!=="login"&&x!=="register"&&a.jsxs(a.Fragment,{children:[x==="verify"&&a.jsx("button",{className:fe.authModeLink,disabled:Te||Ln||!I.trim(),"data-testid":"auth-resend-verification-button",onClick:async()=>{Me(!0),ee(null),q(null),we(null);const G=await Aa(I);G.success?(gt(Date.now()+3e4),G.verificationToken&&pe(G.verificationToken),ee(Ur(G))):q(Ir(G)),Me(!1)},children:Ln?`Resend Verification (${kr}s)`:"Resend Verification"}),a.jsx("button",{className:fe.authModeLink,disabled:Te,"data-testid":"auth-return-sign-in-button",onClick:()=>{q(null),we(null),ee(null),Rt("login")},children:x==="verify"?"Back to Sign In":"Sign In"}),Ha&&x!=="verify"&&a.jsx("button",{className:fe.authModeLink,disabled:Te,"data-testid":"auth-return-register-button",onClick:()=>{q(null),we(null),ee(null),Rt("register")},children:"Register"}),x==="reset"&&a.jsx("button",{className:fe.authModeLink,disabled:Te||rr,"data-testid":"auth-return-forgot-password-button",onClick:()=>{q(null),we(null),ee(null),Rt("forgot")},children:rr?`Forgot Password (${Hn}s)`:"Forgot Password"})]})]})]})]})})});if(Je==="login-redirect")return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(Je==="coming-soon")return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Rp})`},children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsx("h1",{className:fe.loginTitle,children:"Beta Access"})]}),a.jsx("p",{className:fe.loginSubtitle,children:"You are signed in, but your account does not have beta access yet."}),a.jsx("p",{className:fe.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),a.jsx("button",{className:p.cancelBtn,onClick:async()=>{await jt.logout(),_("/login",{replace:!0})},children:"Sign Out"})]})})});if(Je==="guided-setup"){const G=!nn&&(xn||Ra==="error"),qe=!nn&&!G&&(yn||Ra==="global"),At=$e(G?"setup.headingCheckFailed":qe?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),Nt=G?$e("setup.subtitleUnreadable"):qe?$e("setup.subtitleGlobalRequired"):null,Ea="Workspace",In=Ua||et!=="cloud",Tn=In&&Qe==="details",Mo=In&&Qe==="library",Eo=!Ua&&_a&&Tn&&!ea,ao=Qn?.runtimeMode==="cloud"?fg:tv,Ga=da?jp(da.categories):"",vr=da?jp(da.types):"",Da=da?jp(da.priorities):"",R=ct?$e("setup.saving"):fr?ea?za?"Retry Import":"Importing Workspace...":"Connect Workspace":Tn?"Continue":Mo?"Create Workspace":"Connect Workspace";return a.jsx("div",{className:ta.standaloneWrapper,"data-theme":ya,children:a.jsx("div",{className:fe.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${Rp})`},children:a.jsxs("div",{className:fe.loginCard,children:[a.jsxs("div",{className:fe.setupHeaderRow,children:[a.jsxs("div",{className:fe.authBrandRow,children:[a.jsx("img",{src:En,alt:"Taskforce",className:fe.loginLogo}),a.jsxs("h1",{className:fe.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:fe.loginTitleAccent,children:"HQ"})]})]}),Qn&&a.jsx("span",{className:fe.runtimeIconBadge,title:Qn.runtimeMode==="cloud"?"Cloud runtime":"Local runtime","aria-label":Qn.runtimeMode==="cloud"?"Cloud runtime":"Local runtime",children:Fe.createElement(ao,{size:16,"aria-hidden":!0})})]}),a.jsx("p",{className:fe.loginSubtitle,children:a.jsx("strong",{children:At})}),Nt?a.jsx("p",{className:fe.loginSubtitle,children:Nt}):null,Pt&&a.jsx("p",{className:fe.loginSubtitle,children:Pt}),st&&a.jsx("p",{className:fe.loginError,children:st}),qe&&a.jsxs("div",{className:fe.optionGrid,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:dt==="core",onChange:()=>Xe("core"),disabled:ct}),a.jsx("span",{children:$e("setup.coreModeOption",{workspaceLabel:Ea})})]}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:dt==="operations",onChange:()=>Xe("operations"),disabled:ct}),a.jsx("span",{children:$e("setup.operationsModeOption")})]})]}),!G&&!qe&&a.jsxs("div",{className:fe.optionGrid,children:[Eo&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:et==="local",onChange:()=>Ue("local"),disabled:ct}),a.jsxs("span",{children:["Create new local ",Ea.toLowerCase()]})]}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:et==="cloud",onChange:()=>Ue("cloud"),disabled:ct}),a.jsxs("span",{children:["Sync existing cloud ",Ea.toLowerCase()]})]})]}),fr?a.jsxs("div",{className:fe.optionGroup,children:[!ea&&!_a&&a.jsx("p",{className:fe.loginError,children:"Cloud workspace sync is unavailable right now. Switch back to local setup or refresh runtime configuration."}),!ea&&_a&&!Dt&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.inlineHint,children:"Sign in to choose one of your cloud projects."}),a.jsxs("div",{className:fe.actionRowEnd,children:[a.jsx("button",{className:p.cancelBtn,disabled:ct,onClick:()=>{_(`/login?mode=login&next=${encodeURIComponent(an)}`,{replace:!0})},children:"Sign In"}),Ha&&a.jsx("button",{className:p.submitBtn,disabled:ct,onClick:()=>{_(`/login?mode=register&next=${encodeURIComponent(an)}`,{replace:!0})},children:"Register"})]})]}),!ea&&_a&&Dt&&a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:p.input,value:ze,onChange:C=>bt(C.target.value),disabled:ct||Ot||ot.length===0,children:[ot.length===0&&a.jsx("option",{value:"",children:Ot?"Loading cloud projects...":"No cloud projects found"}),ot.map(C=>a.jsxs("option",{value:C.id,children:[C.name," (",C.id,")"]},C.id))]}),a.jsx("div",{className:fe.actionRowEnd,children:a.jsx("button",{className:p.cancelBtn,disabled:ct||Ot,onClick:()=>{Ma()},children:"Refresh Cloud Projects"})}),Oe&&a.jsx("p",{className:fe.loginError,children:Oe})]}),ea&&a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:fe.inlineHint,children:['Importing "',ea.name,'" from cloud into local.']}),a.jsx("div",{className:fe.optionGroup,children:Xr.map(C=>a.jsx("p",{className:fe.inlineHint,children:C},C))}),a.jsx("p",{className:fe.inlineHint,children:ye?"Finishing setup and opening your workspace.":vn||"Pulling tasks, taxonomies, and settings into local."}),!ye&&pn&&a.jsx("p",{className:fe.inlineHint,children:pn})]})]}):a.jsxs(a.Fragment,{children:[Tn&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:fe.loginSubtitle,children:"Workspace name"}),a.jsx("input",{className:p.input,type:"text",value:It,placeholder:"Workspace name",onChange:C=>Ft(C.target.value),disabled:ct}),a.jsx("p",{className:fe.loginSubtitle,children:"Workspace description"}),a.jsx("textarea",{className:p.textarea,value:Mt,placeholder:"Workspace description (optional)",onChange:C=>Be(C.target.value),disabled:ct,rows:4})]}),Mo&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsx("p",{className:fe.loginSubtitle,children:"What are you working on?"}),a.jsxs("select",{className:p.input,value:qt,onChange:C=>Et(C.target.value),disabled:ct||Ht||Ne.length===0,children:[Ne.length===0&&a.jsx("option",{value:"",children:Ht?"Loading setup options...":"No setup options available"}),Ne.map(C=>a.jsx("option",{value:C.id,children:C.label},C.id))]}),da?a.jsx(a.Fragment,{children:da.description?a.jsx("p",{className:fe.inlineHint,children:da.description}):null}):null,a.jsxs("div",{className:fe.optionGroup,children:[a.jsx("p",{className:fe.loginSubtitle,children:"Apply Setup Sections"}),a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Tt.categories,onChange:()=>Wt(C=>({...C,categories:!C.categories})),disabled:ct||!da?.categories.length}),a.jsx("span",{children:"Categories"})]}),Ga?a.jsx("p",{className:fe.inlineHint,children:Ga}):null,a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Tt.types,onChange:()=>Wt(C=>({...C,types:!C.types})),disabled:ct||!da?.types.length}),a.jsx("span",{children:"Task Types"})]}),vr?a.jsx("p",{className:fe.inlineHint,children:vr}):null,a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:Tt.priorities,onChange:()=>Wt(C=>({...C,priorities:!C.priorities})),disabled:ct||!da?.priorities.length}),a.jsx("span",{children:"Priorities"})]}),Da?a.jsx("p",{className:fe.inlineHint,children:Da}):null]}),Ht?a.jsx("p",{className:fe.inlineHint,children:"Loading setup options…"}):null,Kt?a.jsx("p",{className:fe.loginError,children:Kt}):null]}),!Ua&&_a&&Dt&&Tn&&a.jsxs("div",{className:fe.optionGroup,children:[a.jsxs("label",{className:`${fe.authModeLink} ${fe.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:vt,onChange:C=>E(C.target.checked),disabled:ct}),a.jsx("span",{children:"Sync to cloud after setup"})]}),a.jsx("p",{className:fe.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),a.jsxs("div",{className:fe.authModeLinks,children:[Mo?a.jsx("button",{className:p.cancelBtn,onClick:()=>{Ye(null),kt(null),yt("details")},children:"Back"}):nn?a.jsx("button",{className:p.cancelBtn,onClick:()=>{Ye(null),kt(null),_("/",{replace:!0})},children:"Cancel"}):tt==="cloud"?a.jsx("button",{className:p.cancelBtn,onClick:async()=>{await jt.logout(),_("/login",{replace:!0})},children:$e("setup.signOut")}):null,qe?a.jsx("button",{className:p.submitBtn,disabled:ct||hr&&!!ea&&!za,onClick:async()=>{ne(!0),kt(null),Ye(null);try{const C=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:dt}})}),Ze=await C.json().catch(()=>({}));!C.ok||Ze?.success===!1?Ye(Ze?.error||$e("setup.saveFailedWithStatus",{status:C.status})):(kt($e("setup.globalSetupSaved")),await ba())}catch{Ye($e("setup.saveFailed"))}finally{ne(!1)}},children:$e(ct?"setup.saving":"setup.saveGlobalSetup")}):G?a.jsx("button",{className:p.submitBtn,disabled:ct,onClick:ba,children:$e("setup.retrySetupCheck")}):a.jsx("button",{className:p.submitBtn,disabled:ct||hr&&!ea&&!Dt,onClick:async()=>{if(hr&&ea){if(!za)return;ne(!0),kt(`Retrying import for ${ea.name}...`),Ye(null);try{await _r()}catch{kt(null),Ye(`Failed to retry import for "${ea.name}".`)}finally{ne(!1)}return}if(fr){if(!_a){Ye("Cloud workspace sync is unavailable right now."),ne(!1);return}if(!Dt){Ye("Sign in is required before syncing a cloud project."),ne(!1);return}const C=ot.find(De=>De.id===ze);if(!C){Ye("Select a cloud project to sync."),ne(!1);return}const Ze=await Ia({workspaceId:C.id,name:C.name||C.id,description:C.description||void 0});if(!Ze.success){Ye(Ze.error||$e("setup.saveWorkspaceFailed")),ne(!1);return}const ht=String(Ze.workspaceId||C.id||"").trim();if(!ht){Ye("Failed to resolve workspace id for sync setup."),ne(!1);return}try{await Cn(ht,{version:2,enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null})}catch(De){Ye(De instanceof Error?De.message:"Failed to configure workspace sync."),ne(!1);return}Ca({enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null}),await ba(),Y({workspaceId:ht,name:C.name||C.id}),Ie(!1),kt(`Importing ${C.name||C.id} from cloud...`),ne(!1);return}if(Tn){if(!It.trim()){Ye("Workspace name is required before continuing.");return}Ye(null),kt(null),yt("library");return}ne(!0),kt(null),Ye(null);{const C=nn||$t?.workspaceSetupState==="missing",Ze=nn||Gt&&C,ht=Ze?await Lr(It,Mt||void 0):null,De=Ze?null:await Ia({workspaceId:C?void 0:$t?.workspaceId,name:It,description:Mt}),oe=ht||De;if(!oe?.success)Ye(oe?.error||$e("setup.saveWorkspaceFailed"));else{const sr=String(ht?.workspace?.id||De?.workspaceId||$t?.workspaceId||"").trim();if(!sr){Ye("Failed to resolve workspace id for setup."),ne(!1);return}if(et==="local"&&!!da&&(Tt.categories||Tt.types||Tt.priorities)&&da){const ns=await Br.onApplySystemTaxonomyPack({pack:da,sections:Tt,remapExistingValuesToDefault:!0,workspaceIdOverride:sr});if(!ns?.success){Ye(ns?.error||"Failed to apply setup library."),ne(!1);return}}const sn=!!(!Ua&&vt&&_a&&Dt),or=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:sr,stateKey:"workspace-sync",patch:{version:2,enabled:sn,phase:sn?"provision-local":"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),ir=await or.json().catch(()=>({}));if(!or.ok||ir?.success===!1){Ye(ir?.error||`Failed to configure workspace sync (${or.status})`),ne(!1);return}Ca({enabled:sn,phase:sn?"provision-local":"idle",setupIntent:null,pullCursor:null}),kt(sn?`${Ea} setup saved. Cloud sync enabled.`:$e("setup.workspaceSetupSaved",{workspaceLabel:Ea})),nn&&(await ba(),await Sn(!0),_("/",{replace:!0}))}}ne(!1)},children:R})]})]})})})}return a.jsx(_O,{...jt,onHeaderMouseDown:s,isDragging:o,onClose:l})}function AO(e){return pv()?a.jsx(sg,{...e}):a.jsx(fv,{children:a.jsx(sg,{...e})})}const zy={},og="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=og,console.info(`[Taskforce] Build marker: ${og}`));function xO(){if(typeof window<"u"){const t=window.location.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1")return}return lf(zy).apiBaseUrl||void 0}function IO(e){const t=lf(zy),n=t.cloudAuthBaseUrl;if(n)if(typeof window<"u"){const s=window.location.hostname.toLowerCase(),o=s==="localhost"||s==="127.0.0.1"||s==="::1",l="".trim().toLowerCase()==="true";if(!o&&!l)try{const i=new URL(n,window.location.origin);if(i.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${i.origin}`);else return n}catch{}else return n}else return n;if(t.baseUrl)return t.baseUrl;if(e)return e}function TO(){const e=xO(),t=IO(e);return a.jsx(hv,{children:a.jsx(AO,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:t}})})}Tk.createRoot(document.getElementById("root")).render(a.jsx(Fe.StrictMode,{children:a.jsx(TO,{})}));export{P1 as $,HO as A,fB as B,J1 as C,Yc as D,vB as E,zO as F,XW as G,zL as H,ec as I,cf as J,Gp as K,zh as L,Ws as M,Hh as N,OW as O,GO as P,e4 as Q,cy as R,yy as S,ld as T,mm as U,iy as V,KO as W,qO as X,lm as Y,NF as Z,N1 as _,ym as a,x1 as a0,UO as a1,km as a2,Dr as b,eS as c,xv as d,zt as e,LO as f,Gu as g,D1 as h,ub as i,VO as j,L1 as k,ry as l,at as m,vS as n,qu as o,qg as p,Ku as q,Nn as r,Kg as s,p as t,FO as u,BO as v,OO as w,WO as x,$O as y,MS as z};
|