Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
refactor: extract event handler (#7908)
Nathan.fooo6e850ab8b2c8
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dartindex a9b82392dc..7c1e3aafd0 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart@@ -500,7 +500,6 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {}await _streamManager.prepareStreams();-await _streamManager.sendRegenerateRequest(answerMessageId,diff --git a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dartindex a92bb19295..3128d86a28 100644--- a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart@@ -30,421 +30,39 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {(event, emit) async {await event.when(initial: () async {- _listener.start(- onProfileUpdated: (result) {- if (!isClosed) {- result.fold(- (newProfile) =>- add(UserWorkspaceEvent.updateUserProfile(newProfile)),- (error) => Log.error("Failed to get user profile: $error"),- );- }- },- onUserWorkspaceListUpdated: (workspaces) =>- add(UserWorkspaceEvent.updateWorkspaces(workspaces)),- onUserWorkspaceUpdated: (workspace) {- if (!isClosed) {- // If currentWorkspace is updated, eg. Icon or Name, we should notify- // the UI to render the updated information.- final currentWorkspace = state.currentWorkspace;- if (currentWorkspace?.workspaceId == workspace.workspaceId) {- add(UserWorkspaceEvent.updateCurrentWorkspace(workspace));- }- }- },- );-- final result = await _fetchWorkspaces(- initialWorkspaceId: initialWorkspaceId,- );- final currentWorkspace = result.$1;- final workspaces = result.$2;- final isCollabWorkspaceOn =- userProfile.userAuthType == AuthTypePB.Server &&- FeatureFlag.collaborativeWorkspace.isOn;- Log.info(- 'init workspace, current workspace: ${currentWorkspace?.workspaceId}, '- 'workspaces: ${workspaces.map((e) => e.workspaceId)}, isCollabWorkspaceOn: $isCollabWorkspaceOn',- );- if (currentWorkspace != null && result.$3 == true) {- Log.info('init open workspace: ${currentWorkspace.workspaceId}');- await _userService.openWorkspace(- currentWorkspace.workspaceId,- currentWorkspace.workspaceType,- );- }-- emit(- state.copyWith(- currentWorkspace: currentWorkspace,- workspaces: workspaces,- isCollabWorkspaceOn: isCollabWorkspaceOn,- actionResult: null,- ),- );+ _setupListeners();+ await _initializeWorkspaces(emit);},fetchWorkspaces: (initialWorkspaceId) async {- final result = await _fetchWorkspaces(- initialWorkspaceId: initialWorkspaceId,- );-- final currentWorkspace = result.$1;- final workspaces = result.$2;- Log.info(- 'fetch workspaces: current workspace: ${currentWorkspace?.workspaceId}, workspaces: ${workspaces.map((e) => e.workspaceId)}',- );-- emit(- state.copyWith(- workspaces: workspaces,- ),- );-- // try to open the workspace if the current workspace is not the same- if (currentWorkspace != null &&- currentWorkspace.workspaceId !=- state.currentWorkspace?.workspaceId) {- Log.info(- 'fetch workspaces: try to open workspace: ${currentWorkspace.workspaceId}',- );- add(- OpenWorkspace(- currentWorkspace.workspaceId,- currentWorkspace.workspaceType,- ),- );- }+ await _handleFetchWorkspaces(emit, initialWorkspaceId);},createWorkspace: (name, workspaceType) async {- emit(- state.copyWith(- actionResult: const UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.create,- isLoading: true,- result: null,- ),- ),- );- final result = await _userService.createUserWorkspace(- name,- workspaceType,- );- final workspaces = result.fold(- (s) => [...state.workspaces, s],- (e) => state.workspaces,- );- emit(- state.copyWith(- workspaces: workspaces,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.create,- isLoading: false,- result: result,- ),- ),- );- // open the created workspace by default- result- ..onSuccess((s) {- Log.info('create workspace success: $s');- add(- OpenWorkspace(- s.workspaceId,- s.workspaceType,- ),- );- })- ..onFailure((f) {- Log.error('create workspace error: $f');- });+ await _handleCreateWorkspace(emit, name, workspaceType);},deleteWorkspace: (workspaceId) async {- Log.info('try to delete workspace: $workspaceId');- emit(- state.copyWith(- actionResult: const UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.delete,- isLoading: true,- result: null,- ),- ),- );- final remoteWorkspaces = await _fetchWorkspaces().then(- (value) => value.$2,- );- if (state.workspaces.length <= 1 || remoteWorkspaces.length <= 1) {- // do not allow to delete the last workspace, otherwise the user- // cannot do create workspace again- Log.error('cannot delete the only workspace');- final result = FlowyResult.failure(- FlowyError(- code: ErrorCode.Internal,- msg: LocaleKeys.workspace_cannotDeleteTheOnlyWorkspace.tr(),- ),- );- return emit(- state.copyWith(- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.delete,- result: result,- isLoading: false,- ),- ),- );- }-- final result = await _userService.deleteWorkspaceById(workspaceId);- // fetch the workspaces again to check if the current workspace is deleted- final workspacesResult = await _fetchWorkspaces();- final workspaces = workspacesResult.$2;- final containsDeletedWorkspace = workspaces.any(- (e) => e.workspaceId == workspaceId,- );- result- ..onSuccess((_) {- Log.info('delete workspace success: $workspaceId');- final firstWorkspace = workspaces.firstOrNull;- // if the current workspace is deleted, open the first workspace- assert(- firstWorkspace != null,- 'the first workspace must not be null',- );- if (state.currentWorkspace?.workspaceId == workspaceId &&- firstWorkspace != null) {- Log.info(- 'delete workspace: open the first workspace: ${firstWorkspace.workspaceId}',- );- add(- OpenWorkspace(- firstWorkspace.workspaceId,- firstWorkspace.workspaceType,- ),- );- }- })- ..onFailure((f) {- Log.error('delete workspace error: $f');- // if the workspace is deleted but return an error, we need to- // open the first workspace- if (!containsDeletedWorkspace) {- add(- OpenWorkspace(- workspaces.first.workspaceId,- workspaces.first.workspaceType,- ),- );- }- });- emit(- state.copyWith(- workspaces: workspaces,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.delete,- result: result,- isLoading: false,- ),- ),- );+ await _handleDeleteWorkspace(emit, workspaceId);},openWorkspace: (workspaceId, workspaceType) async {- emit(- state.copyWith(- actionResult: const UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.open,- isLoading: true,- result: null,- ),- ),- );- final result = await _userService.openWorkspace(- workspaceId,- workspaceType,- );- final currentWorkspace = result.fold(- (s) => state.workspaces.firstWhereOrNull(- (e) => e.workspaceId == workspaceId,- ),- (e) => state.currentWorkspace,- );-- result- ..onSuccess((s) {- Log.info(- 'open workspace success: $workspaceId, current workspace: ${currentWorkspace?.toProto3Json()}',- );- })- ..onFailure((f) {- Log.error('open workspace error: $f');- });-- emit(- state.copyWith(- currentWorkspace: currentWorkspace,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.open,- isLoading: false,- result: result,- ),- ),- );- getIt<ReminderBloc>().add(ReminderEvent.started());+ await _handleOpenWorkspace(emit, workspaceId, workspaceType);},renameWorkspace: (workspaceId, name) async {- final result =- await _userService.renameWorkspace(workspaceId, name);- final workspaces = result.fold(- (s) => state.workspaces.map(- (e) {- if (e.workspaceId == workspaceId) {- e.freeze();- return e.rebuild((p0) {- p0.name = name;- });- }- return e;- },- ).toList(),- (f) => state.workspaces,- );- final currentWorkspace = workspaces.firstWhere(- (e) => e.workspaceId == state.currentWorkspace?.workspaceId,- );-- Log.info(- 'rename workspace: $workspaceId, name: $name',- );-- result.onFailure((f) {- Log.error('rename workspace error: $f');- });-- emit(- state.copyWith(- workspaces: workspaces,- currentWorkspace: currentWorkspace,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.rename,- isLoading: false,- result: result,- ),- ),- );+ await _handleRenameWorkspace(emit, workspaceId, name);},updateWorkspaceIcon: (workspaceId, icon) async {- final workspace = state.workspaces.firstWhere(- (e) => e.workspaceId == workspaceId,- );- if (icon == workspace.icon) {- Log.info('ignore same icon update');- return;- }-- final result = await _userService.updateWorkspaceIcon(- workspaceId,- icon,- );- final workspaces = result.fold(- (s) => state.workspaces.map(- (e) {- if (e.workspaceId == workspaceId) {- e.freeze();- return e.rebuild((p0) {- p0.icon = icon;- });- }- return e;- },- ).toList(),- (f) => state.workspaces,- );- final currentWorkspace = workspaces.firstWhere(- (e) => e.workspaceId == state.currentWorkspace?.workspaceId,- );-- Log.info(- 'update workspace icon: $workspaceId, icon: $icon',- );-- result.onFailure((f) {- Log.error('update workspace icon error: $f');- });-- emit(- state.copyWith(- workspaces: workspaces,- currentWorkspace: currentWorkspace,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.updateIcon,- isLoading: false,- result: result,- ),- ),- );+ await _handleUpdateWorkspaceIcon(emit, workspaceId, icon);},leaveWorkspace: (workspaceId) async {- final result = await _userService.leaveWorkspace(workspaceId);- final workspaces = result.fold(- (s) => state.workspaces- .where((e) => e.workspaceId != workspaceId)- .toList(),- (e) => state.workspaces,- );- result- ..onSuccess((_) {- Log.info('leave workspace success: $workspaceId');- // if leaving the current workspace, open the first workspace- if (state.currentWorkspace?.workspaceId == workspaceId) {- add(- OpenWorkspace(- workspaces.first.workspaceId,- workspaces.first.workspaceType,- ),- );- }- })- ..onFailure((f) {- Log.error('leave workspace error: $f');- });- emit(- state.copyWith(- workspaces: workspaces,- actionResult: UserWorkspaceActionResult(- actionType: UserWorkspaceActionType.leave,- isLoading: false,- result: result,- ),- ),- );+ await _handleLeaveWorkspace(emit, workspaceId);},updateWorkspaces: (workspaces) async {emit(state.copyWith(- workspaces: workspaces.items- ..sort(- (a, b) =>- a.createdAtTimestamp.compareTo(b.createdAtTimestamp),- ),+ workspaces: _sortWorkspaces(workspaces.items),),);},updateCurrentWorkspace: (workspace) async {- final workspaces = [...state.workspaces];- final index = workspaces- .indexWhere((e) => e.workspaceId == workspace.workspaceId);- if (index != -1) {- workspaces[index] = workspace;- }-- emit(- state.copyWith(- currentWorkspace: workspace,- workspaces: workspaces- ..sort(- (a, b) =>- a.createdAtTimestamp.compareTo(b.createdAtTimestamp),- ),- ),- );+ _handleUpdateCurrentWorkspace(emit, workspace);},updateUserProfile: (newUserProfile) {emit(@@ -458,22 +76,479 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {);}+ final UserBackendService _userService;+ final UserListener _listener;+ final String? initialWorkspaceId;+@overrideFuture<void> close() {_listener.stop();return super.close();}- final UserBackendService _userService;- final UserListener _listener;- final String? initialWorkspaceId;+ void _setupListeners() {+ _listener.start(+ onProfileUpdated: (result) {+ if (!isClosed) {+ result.fold(+ (newProfile) =>+ add(UserWorkspaceEvent.updateUserProfile(newProfile)),+ (error) => Log.error("Failed to get user profile: $error"),+ );+ }+ },+ onUserWorkspaceListUpdated: (workspaces) =>+ add(UserWorkspaceEvent.updateWorkspaces(workspaces)),+ onUserWorkspaceUpdated: (workspace) {+ if (!isClosed) {+ final currentWorkspace = state.currentWorkspace;+ if (currentWorkspace?.workspaceId == workspace.workspaceId) {+ add(UserWorkspaceEvent.updateCurrentWorkspace(workspace));+ }+ }+ },+ );+ }- Future<- (- UserWorkspacePB? currentWorkspace,- List<UserWorkspacePB> workspaces,- bool shouldOpenWorkspace,- )> _fetchWorkspaces({String? initialWorkspaceId}) async {+ Future<void> _initializeWorkspaces(Emitter<UserWorkspaceState> emit) async {+ final result = await _fetchWorkspaces(+ initialWorkspaceId: initialWorkspaceId,+ );+ final currentWorkspace = result.$1;+ final workspaces = result.$2;+ final isCollabWorkspaceOn =+ state.userProfile.userAuthType == AuthTypePB.Server &&+ FeatureFlag.collaborativeWorkspace.isOn;++ Log.info(+ 'init workspace, current workspace: ${currentWorkspace?.workspaceId}, '+ 'workspaces: ${workspaces.map((e) => e.workspaceId)}, isCollabWorkspaceOn: $isCollabWorkspaceOn',+ );++ if (currentWorkspace != null && result.$3 == true) {+ Log.info('init open workspace: ${currentWorkspace.workspaceId}');+ await _userService.openWorkspace(+ currentWorkspace.workspaceId,+ currentWorkspace.workspaceType,+ );+ }++ emit(+ state.copyWith(+ currentWorkspace: currentWorkspace,+ workspaces: workspaces,+ isCollabWorkspaceOn: isCollabWorkspaceOn,+ actionResult: null,+ ),+ );+ }++ Future<void> _handleFetchWorkspaces(+ Emitter<UserWorkspaceState> emit,+ String? initialWorkspaceId,+ ) async {+ final result = await _fetchWorkspaces(+ initialWorkspaceId: initialWorkspaceId,+ );++ final currentWorkspace = result.$1;+ final workspaces = result.$2;+ Log.info(+ 'fetch workspaces: current workspace: ${currentWorkspace?.workspaceId}, workspaces: ${workspaces.map((e) => e.workspaceId)}',+ );++ emit(+ state.copyWith(+ workspaces: workspaces,+ ),+ );++ if (currentWorkspace != null &&+ currentWorkspace.workspaceId != state.currentWorkspace?.workspaceId) {+ Log.info(+ 'fetch workspaces: try to open workspace: ${currentWorkspace.workspaceId}',+ );+ add(+ OpenWorkspace(+ currentWorkspace.workspaceId,+ currentWorkspace.workspaceType,+ ),+ );+ }+ }++ Future<void> _handleCreateWorkspace(+ Emitter<UserWorkspaceState> emit,+ String name,+ WorkspaceTypePB workspaceType,+ ) async {+ emit(+ state.copyWith(+ actionResult: const UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.create,+ isLoading: true,+ result: null,+ ),+ ),+ );++ final result = await _userService.createUserWorkspace(+ name,+ workspaceType,+ );++ final workspaces = result.fold(+ (s) => [...state.workspaces, s],+ (e) => state.workspaces,+ );++ emit(+ state.copyWith(+ workspaces: _sortWorkspaces(workspaces),+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.create,+ isLoading: false,+ result: result,+ ),+ ),+ );++ result+ ..onSuccess((s) {+ Log.info('create workspace success: $s');+ add(+ OpenWorkspace(+ s.workspaceId,+ s.workspaceType,+ ),+ );+ })+ ..onFailure((f) {+ Log.error('create workspace error: $f');+ });+ }++ Future<void> _handleDeleteWorkspace(+ Emitter<UserWorkspaceState> emit,+ String workspaceId,+ ) async {+ Log.info('try to delete workspace: $workspaceId');+ emit(+ state.copyWith(+ actionResult: const UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.delete,+ isLoading: true,+ result: null,+ ),+ ),+ );++ final remoteWorkspaces = await _fetchWorkspaces().then(+ (value) => value.$2,+ );++ if (state.workspaces.length <= 1 || remoteWorkspaces.length <= 1) {+ final result = FlowyResult.failure(+ FlowyError(+ code: ErrorCode.Internal,+ msg: LocaleKeys.workspace_cannotDeleteTheOnlyWorkspace.tr(),+ ),+ );+ return emit(+ state.copyWith(+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.delete,+ result: result,+ isLoading: false,+ ),+ ),+ );+ }++ final result = await _userService.deleteWorkspaceById(workspaceId);+ final workspacesResult = await _fetchWorkspaces();+ final workspaces = workspacesResult.$2;+ final containsDeletedWorkspace =+ _findWorkspaceById(workspaceId, workspaces) != null;++ result+ ..onSuccess((_) {+ Log.info('delete workspace success: $workspaceId');+ final firstWorkspace = workspaces.firstOrNull;+ assert(+ firstWorkspace != null,+ 'the first workspace must not be null',+ );+ if (state.currentWorkspace?.workspaceId == workspaceId &&+ firstWorkspace != null) {+ Log.info(+ 'delete workspace: open the first workspace: ${firstWorkspace.workspaceId}',+ );+ add(+ OpenWorkspace(+ firstWorkspace.workspaceId,+ firstWorkspace.workspaceType,+ ),+ );+ }+ })+ ..onFailure((f) {+ Log.error('delete workspace error: $f');+ if (!containsDeletedWorkspace && workspaces.isNotEmpty) {+ add(+ OpenWorkspace(+ workspaces.first.workspaceId,+ workspaces.first.workspaceType,+ ),+ );+ }+ });++ emit(+ state.copyWith(+ workspaces: workspaces,+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.delete,+ result: result,+ isLoading: false,+ ),+ ),+ );+ }++ Future<void> _handleOpenWorkspace(+ Emitter<UserWorkspaceState> emit,+ String workspaceId,+ WorkspaceTypePB workspaceType,+ ) async {+ emit(+ state.copyWith(+ actionResult: const UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.open,+ isLoading: true,+ result: null,+ ),+ ),+ );++ final result = await _userService.openWorkspace(+ workspaceId,+ workspaceType,+ );++ final currentWorkspace = result.fold(+ (s) => _findWorkspaceById(workspaceId),+ (e) => state.currentWorkspace,+ );++ result+ ..onSuccess((s) {+ Log.info(+ 'open workspace success: $workspaceId, current workspace: ${currentWorkspace?.toProto3Json()}',+ );+ })+ ..onFailure((f) {+ Log.error('open workspace error: $f');+ });++ emit(+ state.copyWith(+ currentWorkspace: currentWorkspace,+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.open,+ isLoading: false,+ result: result,+ ),+ ),+ );++ getIt<ReminderBloc>().add(ReminderEvent.started());+ }++ Future<void> _handleRenameWorkspace(+ Emitter<UserWorkspaceState> emit,+ String workspaceId,+ String name,+ ) async {+ final result = await _userService.renameWorkspace(workspaceId, name);++ final workspaces = result.fold(+ (s) => _updateWorkspaceInList(workspaceId, (workspace) {+ workspace.freeze();+ return workspace.rebuild((p0) {+ p0.name = name;+ });+ }),+ (f) => state.workspaces,+ );++ final currentWorkspace = _findWorkspaceById(+ state.currentWorkspace?.workspaceId ?? '',+ workspaces,+ );++ Log.info('rename workspace: $workspaceId, name: $name');++ result.onFailure((f) {+ Log.error('rename workspace error: $f');+ });++ emit(+ state.copyWith(+ workspaces: workspaces,+ currentWorkspace: currentWorkspace,+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.rename,+ isLoading: false,+ result: result,+ ),+ ),+ );+ }++ Future<void> _handleUpdateWorkspaceIcon(+ Emitter<UserWorkspaceState> emit,+ String workspaceId,+ String icon,+ ) async {+ final workspace = _findWorkspaceById(workspaceId);+ if (workspace == null) {+ Log.error('workspace not found: $workspaceId');+ return;+ }++ if (icon == workspace.icon) {+ Log.info('ignore same icon update');+ return;+ }++ final result = await _userService.updateWorkspaceIcon(+ workspaceId,+ icon,+ );++ final workspaces = result.fold(+ (s) => _updateWorkspaceInList(workspaceId, (workspace) {+ workspace.freeze();+ return workspace.rebuild((p0) {+ p0.icon = icon;+ });+ }),+ (f) => state.workspaces,+ );++ final currentWorkspace = _findWorkspaceById(+ state.currentWorkspace?.workspaceId ?? '',+ workspaces,+ );++ Log.info('update workspace icon: $workspaceId, icon: $icon');++ result.onFailure((f) {+ Log.error('update workspace icon error: $f');+ });++ emit(+ state.copyWith(+ workspaces: workspaces,+ currentWorkspace: currentWorkspace,+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.updateIcon,+ isLoading: false,+ result: result,+ ),+ ),+ );+ }++ Future<void> _handleLeaveWorkspace(+ Emitter<UserWorkspaceState> emit,+ String workspaceId,+ ) async {+ final result = await _userService.leaveWorkspace(workspaceId);++ final workspaces = result.fold(+ (s) =>+ state.workspaces.where((e) => e.workspaceId != workspaceId).toList(),+ (e) => state.workspaces,+ );++ result+ ..onSuccess((_) {+ Log.info('leave workspace success: $workspaceId');+ if (state.currentWorkspace?.workspaceId == workspaceId &&+ workspaces.isNotEmpty) {+ add(+ OpenWorkspace(+ workspaces.first.workspaceId,+ workspaces.first.workspaceType,+ ),+ );+ }+ })+ ..onFailure((f) {+ Log.error('leave workspace error: $f');+ });++ emit(+ state.copyWith(+ workspaces: _sortWorkspaces(workspaces),+ actionResult: UserWorkspaceActionResult(+ actionType: UserWorkspaceActionType.leave,+ isLoading: false,+ result: result,+ ),+ ),+ );+ }++ void _handleUpdateCurrentWorkspace(+ Emitter<UserWorkspaceState> emit,+ UserWorkspacePB workspace,+ ) {+ final workspaces = _updateWorkspaceInList(+ workspace.workspaceId,+ (_) => workspace,+ );++ emit(+ state.copyWith(+ currentWorkspace: workspace,+ workspaces: _sortWorkspaces(workspaces),+ ),+ );+ }++ // Helper methods+ List<UserWorkspacePB> _sortWorkspaces(List<UserWorkspacePB> workspaces) {+ final sorted = [...workspaces];+ sorted.sort((a, b) => a.createdAtTimestamp.compareTo(b.createdAtTimestamp));+ return sorted;+ }++ UserWorkspacePB? _findWorkspaceById(+ String id, [+ List<UserWorkspacePB>? workspacesList,+ ]) {+ final workspaces = workspacesList ?? state.workspaces;+ return workspaces.firstWhereOrNull((e) => e.workspaceId == id);+ }++ List<UserWorkspacePB> _updateWorkspaceInList(+ String workspaceId,+ UserWorkspacePB Function(UserWorkspacePB workspace) updater,+ ) {+ final workspaces = [...state.workspaces];+ final index = workspaces.indexWhere((e) => e.workspaceId == workspaceId);+ if (index != -1) {+ workspaces[index] = updater(workspaces[index]);+ }+ return workspaces;+ }++ Future<(UserWorkspacePB?, List<UserWorkspacePB>, bool)> _fetchWorkspaces({+ String? initialWorkspaceId,+ }) async {try {final currentWorkspaceResult =await UserBackendService.getCurrentWorkspace();@@ -481,22 +556,25 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {(s) => s,(e) => null,);- // if the initialWorkspaceId is not provided, use the current workspace idfinal currentWorkspaceId = initialWorkspaceId ?? currentWorkspace?.id;final workspaces = await _userService.getWorkspaces().getOrThrow();+if (workspaces.isEmpty && currentWorkspace != null) {workspaces.add(convertWorkspacePBToUserWorkspace(currentWorkspace));}- final currentWorkspaceInList = workspaces- .firstWhereOrNull((e) => e.workspaceId == currentWorkspaceId) ??++ final currentWorkspaceInList = _findWorkspaceById(+ currentWorkspaceId ?? '',+ workspaces,+ ) ??workspaces.firstOrNull;- final sortedWorkspaces = workspaces- ..sort(- (a, b) => a.createdAtTimestamp.compareTo(b.createdAtTimestamp),- );++ final sortedWorkspaces = _sortWorkspaces(workspaces);+Log.info('fetch workspaces: current workspace: ${currentWorkspaceInList?.workspaceId}, sorted workspaces: ${sortedWorkspaces.map((e) => '${e.name}: ${e.workspaceId}')}',);+return (currentWorkspaceInList,sortedWorkspaces,