import 'package:cutdex/shared/widgets/error_notification_host.dart'; import '../../integrations/platform/device_experience.dart'; import 'touch_project_navigation.dart'; import '../media/media_panel.dart'; import 'package:cutdex_ui/icons.dart'; import 'package:cutdex_ui/theme.dart'; import 'dart:async'; import 'package:cutdex/l10n/l10n.dart'; import 'package:flutter/material.dart'; import '../../shared/widgets/listenable_selector.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../integrations/platform/editor_window_chrome.dart'; import 'package:cutdex_native/cutdex_native.dart'; import '../../shared/layout/workspace_layout_metrics.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../workspace/projects.dart'; import '../../workspace/workspace_mode.dart'; import '../../workspace/project_state.dart'; import '../../integrations/agent/conversation_repository.dart' show ConversationMetadata; import '../../integrations/agent/agent_settings.dart'; import '../../integrations/agent/agent_models.dart'; import 'widgets/name_dialog.dart'; import 'conversation_sidebar.dart'; import 'chat_header.dart'; import 'sidebar_category_tabs.dart'; import 'sidebar_navigation_controller.dart'; typedef ProjectRenamer = Future Function(RecentProject project); class ProjectSidebar extends ConsumerStatefulWidget { const ProjectSidebar({ super.key, required this.agent, this.navigationOnly = false, this.chatOnly = false, this.chatPanelActions = const [], this.resourcesSelected = false, this.onResourcesSelected, this.librarySelected = false, this.externalWindowFrame = false, this.experience = DeviceExperience.desktop, this.onNavigationComplete, required this.mode, required this.onModeChanged, required this.navigationWidth, required this.navigationCollapsed, required this.agentHeaderLeading, required this.editorHidden, required this.onExpandEditor, required this.state, required this.selectedProjectId, required this.integratedTitlebar, required this.onCreateProject, required this.onSelectProject, required this.onRenameProject, required this.headerControls, }); final Widget agent; final bool navigationOnly; final bool chatOnly; final List chatPanelActions; final bool resourcesSelected; final ValueChanged? onResourcesSelected; final bool librarySelected; final bool externalWindowFrame; final DeviceExperience experience; final VoidCallback? onNavigationComplete; final ProjectState state; final String? selectedProjectId; final WorkspaceMode mode; final ValueChanged onModeChanged; final double navigationWidth; final bool navigationCollapsed; final Widget agentHeaderLeading; final bool editorHidden; final VoidCallback? onExpandEditor; final bool integratedTitlebar; final VoidCallback? onCreateProject; final ValueChanged? onSelectProject; final ProjectRenamer onRenameProject; final Widget headerControls; @override ConsumerState createState() => _ProjectSidebarState(); } class _ProjectSidebarState extends ConsumerState { ProjectState get _projectState => ref.read(projectsProvider).value ?? widget.state; SidebarNavigationContext _navigationContext(ProjectState state) => (projectId: state.activeProject?.id, timelineId: state.visibleTimelineId); late final _navigation = SidebarNavigationController( _navigationContext(_projectState), ); bool _resourcesVisited = false; bool get _touch => widget.experience != DeviceExperience.desktop; bool _projectHeaderHovered = false; String? _hoveredProjectId; final _cutProjectsMenu = MenuController(); final Set _expandedConversationProjects = {}; final Set _collapsedProjects = {}; bool _showTrash = false; late final ValueNotifier _projectSelection; final _groupWidgets = {}; @override void initState() { super.initState(); _resourcesVisited = widget.resourcesSelected; _projectSelection = ValueNotifier(widget.selectedProjectId); } @override void didUpdateWidget(covariant ProjectSidebar oldWidget) { super.didUpdateWidget(oldWidget); _resourcesVisited |= widget.resourcesSelected; _projectSelection.value = widget.selectedProjectId; final ids = widget.state.recent.map((project) => project.id).toSet(); _groupWidgets.removeWhere((id, _) => !ids.contains(id)); _navigation.update(_navigationContext(_projectState)); if (oldWidget.mode != widget.mode || oldWidget.resourcesSelected != widget.resourcesSelected || oldWidget.librarySelected != widget.librarySelected) { _navigation.cancel(); } } @override void dispose() { _navigation.dispose(); _projectSelection.dispose(); super.dispose(); } ConversationSidebar get _conversations => ref.read(conversationSidebarProvider.notifier); ConversationSnapshot get _snapshot { final snapshot = ref.read(conversationSidebarProvider).value; return snapshot?.projectId == widget.state.activeProject?.id ? snapshot ?? const ConversationSnapshot() : const ConversationSnapshot(); } Map> get _conversationsByProject => ref.read(conversationSidebarProvider).value?.groups ?? const {}; List get _trashed => _snapshot.trashed; String? get _conversationError => (ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed) ? context.l10n.agentSessionRestoreFailed : null; void _finishNavigation() { final scaffold = Scaffold.maybeOf(context); if (scaffold?.isDrawerOpen ?? false) { scaffold!.closeDrawer(); } else { widget.onNavigationComplete?.call(); } } void _selectProjectFromNavigation(RecentProject project) { _navigation.cancel(); widget.onSelectProject?.call(project); if (widget.navigationOnly) _finishNavigation(); } void _newConversation() { _navigation.cancel(); _conversations.newConversation(); } Future _newConversationForProject(RecentProject project) async { _cutProjectsMenu.close(); if (ref.read(projectsProvider).value?.projectBusy == true || !project.availability.canOpen) { return; } final navigation = _navigation.begin(project.id); bool isCurrent() => mounted && navigation(); try { if (_projectState.activeProject?.id != project.id) { final opened = await ref .read(projectsProvider.notifier) .open(project.path, expectedId: project.id, isCurrent: isCurrent); if (!opened || !isCurrent()) return; } if (!isCurrent() || _projectState.activeProject?.id != project.id) return; _newConversation(); widget.onModeChanged(WorkspaceMode.agent); _finishNavigation(); } finally { _navigation.finish(navigation); } } Future _selectConversation(ConversationMetadata item) async { _cutProjectsMenu.close(); if (ref.read(projectsProvider).value?.projectBusy == true) return; final navigation = _navigation.begin( item.projectId, timelineId: item.timelineId, ); bool isCurrent() => mounted && navigation(); try { await _conversations.rememberSelection(item); if (!isCurrent()) return; final currentProject = _projectState.activeProject?.id; if (currentProject != item.projectId) { final project = _projectState.recent .where((entry) => entry.id == item.projectId) .firstOrNull; if (project == null || !project.availability.canOpen) return; var opened = await ref .read(projectsProvider.notifier) .open( project.path, expectedId: project.id, timelineId: item.timelineId, isCurrent: isCurrent, ); if (!isCurrent()) return; if (!opened) { _navigation.useProjectDefault(navigation); opened = await ref .read(projectsProvider.notifier) .open(project.path, expectedId: project.id, isCurrent: isCurrent); } if (!opened) return; } else if (_projectState.timeline?.id != item.timelineId && _projectState.timelines.any( (timeline) => timeline.id == item.timelineId, )) { final opened = await ref .read(projectsProvider.notifier) .openTimeline(item.projectId, item.timelineId); if (!opened) return; } if (!isCurrent() || _projectState.activeProject?.id != item.projectId) { return; } _conversations.activate(item); widget.onModeChanged(WorkspaceMode.agent); _finishNavigation(); } finally { _navigation.finish(navigation); } } Future _renameConversation(ConversationMetadata item) async { final name = await askName( context, title: context.l10n.renameConversationTitle, label: context.l10n.name, description: context.l10n.renameConversationDescription, initialValue: item.title, submitLabel: context.l10n.save, ); if (name == null || !mounted) return; await _conversations.rename(item, name); } Future _trashConversation(ConversationMetadata item) => _conversations.trash(item); Future _restoreConversation(ConversationMetadata item) => _conversations.restore(item); Future _relinkProvider(ConversationMetadata item) async { final settings = await ref.read(agentSettingsProvider.future); if (!mounted) return; final candidates = settings.providers.where( (provider) => provider.enabled && AgentApiType.values.any((type) => type.name == provider.apiType) && provider.models.any((model) => model.id == item.modelId), ); final selected = await showAppDialog( context: context, builder: (dialogContext) => AppDialog( title: context.l10n.agentRelinkProvider, child: Column( mainAxisSize: MainAxisSize.min, children: [ if (candidates.isEmpty) Text(context.l10n.agentProviderRequired), for (final provider in candidates) AppDialogOption( label: provider.name, onPressed: () => Navigator.pop(dialogContext, provider.id), ), ], ), ), ); if (selected == null || !mounted) return; await _conversations.updateMetadata(item.copyWith(providerId: selected)); } Future _removeProject(RecentProject project) async { final index = widget.state.recent.indexWhere( (item) => item.id == project.id, ); final removed = await ref .read(projectsProvider.notifier) .removeRecentProject(project.id); if (!removed || !mounted) return; ErrorNotificationHost.of(context).showMessage( content: Text(context.l10n.projectRemoved), actionLabel: context.l10n.undo, onAction: () => ref .read(projectsProvider.notifier) .restoreRecentProject(project, index), ); } Future _deleteForever(ConversationMetadata item) async { if (!await _confirmDelete(item: item) || !mounted) return; try { await _conversations.delete(item); } catch (_) { if (mounted) { ErrorNotificationHost.of( context, ).show(ErrorNotification(content: Text(context.l10n.operationFailed))); } } } Future _emptyTrash() async { if (!await _confirmDelete() || !mounted) return; await _conversations.emptyTrash(); } Future _confirmDelete({ConversationMetadata? item}) async => await showAppDialog( context: context, builder: (dialogContext) => AppDialog( title: context.l10n.agentDeleteForever, actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext, false), child: Text(context.l10n.cancel), ), FilledButton( style: FilledButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.error, foregroundColor: Theme.of(context).colorScheme.onError, ), onPressed: () => Navigator.pop(dialogContext, true), child: Text(context.l10n.agentDeleteForever), ), ], child: Text( item == null ? context.l10n.agentEmptyTrashConfirmation : context.l10n.agentDeleteConfirmation(item.title), ), ), ) == true; List _conversationActions(ConversationMetadata item) => [ AppMenuItem( label: context.l10n.rename, onPressed: () => _renameConversation(item), ), AppMenuItem( label: context.l10n.agentMoveToTrash, onPressed: () => _trashConversation(item), ), AppMenuItem( label: context.l10n.agentRelinkProvider, onPressed: () => _relinkProvider(item), ), const AppMenuSeparator(), AppMenuItem( label: '${context.l10n.agentDeleteForever}…', destructive: true, onPressed: () => _deleteForever(item), ), ]; Widget _conversationRow( ConversationMetadata item, { VoidCallback? onSelected, bool inMenu = false, }) => Consumer( builder: (context, ref, _) { final active = ref.watch( projectsProvider.select( (value) => value.value?.activeProject?.id == item.projectId, ), ); final selected = ref.watch( conversationSelectionProvider(item.projectId) .select((value) => value.selectedId == item.id), ) && active; if (inMenu) { return AppContextMenu( itemsBuilder: (_) => _conversationActions(item), child: AppMenuItem( key: ValueKey('sidebar-conversation-${item.id}'), label: item.title, selectOption: true, selected: selected, onPressed: onSelected ?? () => _selectConversation(item), ), ); } if (_touch) { return TouchConversationTile( id: item.id, title: item.title, selected: selected, onSelect: onSelected ?? () => _selectConversation(item), actions: (_) => _conversationActions(item), ); } return Padding( padding: AppSidebarMetrics.rowPadding, child: AppContextMenu( itemsBuilder: (_) => _conversationActions(item), child: Material( color: selected ? AppSidebarColors.of(context).hover : Colors.transparent, borderRadius: BorderRadius.circular( AppTheme.isDesktop(context) ? AppRadius.large : AppSidebarMetrics.radius, ), child: InkWell( key: ValueKey('sidebar-conversation-${item.id}'), hoverColor: selected ? Colors.transparent : AppSidebarColors.of(context).hover, splashColor: Colors.transparent, highlightColor: Colors.transparent, borderRadius: BorderRadius.circular( AppTheme.isDesktop(context) ? AppRadius.large : AppSidebarMetrics.radius, ), onTap: onSelected ?? () => _selectConversation(item), child: SizedBox( height: AppTheme.isDesktop(context) ? AppDesktopMetrics.sidebarRow : AppSidebarMetrics.rowHeight, child: Stack( fit: StackFit.expand, children: [ if (selected && AppTheme.isDesktop(context)) PositionedDirectional( start: AppSidebarMetrics.cellPadding, top: 8, bottom: 8, width: 2, child: IgnorePointer( child: DecoratedBox( key: ValueKey( 'sidebar-conversation-selection-${item.id}', ), decoration: BoxDecoration( color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.circular(1), ), ), ), ), Align( alignment: AlignmentDirectional.centerStart, child: Padding( padding: const EdgeInsetsDirectional.only( start: AppSidebarMetrics.textInset, end: AppSidebarMetrics.cellPadding, ), child: Text( item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppSidebarTypography.style( context, fontSize: AppTheme.isDesktop(context) ? 13 : AppSidebarMetrics.conversationFontSize, height: AppTheme.isDesktop(context) ? 20 / 13 : AppSidebarMetrics.conversationLineHeight, ), ), ), ), ], ), ), ), ), ), ); }, ); Widget _projectGroup(RecentProject project) { final configuration = ( project, _touch, Localizations.localeOf(context), Theme.of(context), _expandedConversationProjects.contains(project.id), _collapsedProjects.contains(project.id), _hoveredProjectId == project.id, widget.state.projectBusy, ); final cached = _groupWidgets[project.id]; if (cached?.$1 == configuration) return cached!.$2; final group = Consumer( key: ValueKey('sidebar-project-binding-${project.id}'), builder: (context, ref, _) { ref.watch( conversationSidebarProvider.select( (value) => value.value?.groups[project.id], ), ); return _buildProjectGroup(project); }, ); _groupWidgets[project.id] = (configuration, group); return group; } Widget _buildProjectGroup(RecentProject project) { final conversations = _conversationsByProject[project.id] ?? const []; final expanded = _expandedConversationProjects.contains(project.id); final collapsed = _collapsedProjects.contains(project.id); final visible = collapsed ? const [] : expanded ? conversations : conversations.take(5); return Column( key: ValueKey('sidebar-project-group-${project.id}'), crossAxisAlignment: CrossAxisAlignment.stretch, children: [ MouseRegion( onEnter: (_) => setState(() => _hoveredProjectId = project.id), onExit: (_) { if (_hoveredProjectId == project.id) { setState(() => _hoveredProjectId = null); } }, child: ListenableSelector( listenable: _projectSelection, select: () => _projectSelection.value == project.id, builder: (context, selected) => _touch ? TouchProjectTile( project: project, selected: selected, expanded: !collapsed, availabilityLabel: _availabilityLabel( context, project.availability, ), onSelect: () => _selectProjectFromNavigation(project), onToggle: () => setState(() { if (collapsed) { _collapsedProjects.remove(project.id); } else { _collapsedProjects.add(project.id); } }), onNewConversation: widget.state.projectBusy || !project.availability.canOpen ? null : () => _newConversationForProject(project), onRename: project.availability.canOpen ? () => widget.onRenameProject(project) : null, onRemove: widget.state.projectBusy ? null : () => _removeProject(project), ) : Padding( padding: AppSidebarMetrics.rowPadding, child: _ProjectTile( project: project, active: selected, availabilityLabel: _availabilityLabel( context, project.availability, ), onSelect: () { _cutProjectsMenu.close(); _selectProjectFromNavigation(project); }, onRename: () => widget.onRenameProject(project), onRemove: widget.state.projectBusy ? null : () => _removeProject(project), expanded: !collapsed, onToggleExpanded: () => setState(() { if (collapsed) { _collapsedProjects.remove(project.id); } else { _collapsedProjects.add(project.id); } }), sidebarStyle: true, hovered: _hoveredProjectId == project.id, onNewConversation: () => _newConversationForProject(project), ), ), ), ), for (final item in visible) ...[ const SizedBox(height: AppSidebarMetrics.rowGap), _conversationRow(item), ], if (!collapsed && _conversationsByProject.containsKey(project.id) && conversations.isEmpty) Padding( key: ValueKey('sidebar-project-empty-${project.id}'), padding: const EdgeInsetsDirectional.fromSTEB( AppSidebarMetrics.outerPadding + AppSidebarMetrics.textInset, 4, AppSidebarMetrics.outerPadding + AppSidebarMetrics.cellPadding, 4, ), child: Text( context.l10n.agentNoConversations, style: AppSidebarTypography.style( context, fontSize: AppSidebarMetrics.hintFontSize, height: AppSidebarMetrics.lineHeight, color: AppSidebarColors.of(context).tertiary, ), ), ), if (!collapsed && conversations.length > 5) Padding( padding: const EdgeInsetsDirectional.only( start: AppSidebarMetrics.outerPadding + AppSidebarMetrics.textInset - AppSidebarMetrics.cellPadding, ), child: Align( alignment: AlignmentDirectional.centerStart, child: TextButton( style: TextButton.styleFrom( minimumSize: const Size(0, AppSidebarMetrics.rowHeight), padding: const EdgeInsets.symmetric( horizontal: AppSidebarMetrics.cellPadding, ), ), onPressed: () => setState(() { if (expanded) { _expandedConversationProjects.remove(project.id); } else { _expandedConversationProjects.add(project.id); } }), child: Text( expanded ? context.l10n.showFewerConversations : context.l10n.showMoreConversations, style: Theme.of(context).textTheme.bodySmall ?.copyWith(color: AppSidebarColors.of(context).secondary), ), ), ), ), ], ); } @override Widget build(BuildContext context) { _navigation.update(_navigationContext(_projectState)); ref.listen( projectsProvider.select( (value) => value.value == null ? null : _navigationContext(value.requireValue), ), (_, next) { if (next != null) _navigation.update(next); }, ); if (widget.chatOnly) { final snapshot = ref.watch(conversationSidebarProvider).value; final projectId = widget.state.activeProject?.id; final conversations = snapshot?.groups[projectId] ?? const []; final selectedId = ref.watch( conversationSelectionProvider(projectId) .select((value) => value.selectedId), ); final selected = conversations .where((item) => item.id == selectedId) .firstOrNull; return Material( key: const Key('project-chat-sidebar'), color: Theme.of(context).colorScheme.surface, child: Column( children: [ ChatHeader( key: ValueKey(('chat-header', projectId)), title: selected?.title ?? context.l10n.agentUntitledConversation, busy: widget.state.projectBusy, onNew: _newConversation, panelActions: widget.chatPanelActions, actions: selected == null ? const [] : _conversationActions(selected), historyBuilder: (menuContext, close) => ChatHistoryMenu( entries: [ for (final item in conversations) (id: item.id, title: item.title), ], selectedId: selectedId, error: _conversationError, onSelect: (id) { close(); _selectConversation( conversations.firstWhere((item) => item.id == id), ); }, itemBuilder: (_, id, onSelect) => _conversationRow( conversations.firstWhere((item) => item.id == id), onSelected: onSelect, inMenu: true, ), footer: _trashed.isEmpty ? null : Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Divider(), Padding( padding: ChatHistoryMenu.sectionPadding, child: Text( context.l10n.agentTrash, key: const Key('project-chat-trash-title'), style: Theme.of(context).textTheme.bodySmall, ), ), for (final item in _trashed) Padding( padding: const EdgeInsets.symmetric( horizontal: ChatHistoryMenu.contentInset, ), child: SizedBox( height: 28, child: Row( children: [ Expanded( child: Text( item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppTheme.toolbarTextStyle( context, ), ), ), for (final restore in [true, false]) IconButton( tooltip: restore ? context.l10n.agentRestore : context.l10n.agentDeleteForever, style: IconButton.styleFrom( fixedSize: const Size.square(24), minimumSize: const Size.square(24), maximumSize: const Size.square(24), padding: EdgeInsets.zero, iconSize: 14, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () => restore ? _restoreConversation(item) : _deleteForever(item), icon: Icon( restore ? AppIcons.undo : AppIcons.delete, ), ), ], ), ), ), ], ), ), ), const Divider(height: 1), Expanded(child: widget.agent), ], ), ); } final compact = MediaQuery.sizeOf(context).height < 520; final headerHeight = widget.externalWindowFrame ? 0.0 : widget.navigationOnly ? 48.0 : widget.integratedTitlebar ? AppControlSize.panelHeader : AppControlSize.headerButton; final modeTop = headerHeight; final legacyModeHeader = SizedBox( key: Key( !_touch && widget.navigationOnly ? 'sidebar-window-header' : 'project-content-header', ), height: modeTop + (_touch ? AppSidebarMetrics.modeHeight : 0) + (widget.externalWindowFrame ? 0 : AppSidebarMetrics.sectionGap), child: Stack( children: [ Positioned( top: 0, left: 0, right: 0, height: headerHeight, child: SizedBox( key: const Key('projects-window-header'), child: WindowHeaderPadding( child: Row( children: [ if (widget.integratedTitlebar) SizedBox( key: const Key('native-window-controls-space'), width: EditorWindowChrome.leadingWidth, height: AppControlSize.panelHeader, ) else const SizedBox(width: AppSpacing.small), widget.headerControls, ], ), ), ), ), if (_touch) Positioned( top: modeTop, left: AppSidebarMetrics.outerPadding, right: AppSidebarMetrics.outerPadding, height: AppSidebarMetrics.modeHeight, child: Align( alignment: AlignmentDirectional.topStart, child: AppPopover( width: AppMenuMetrics.modeMenuWidth, child: Column( mainAxisSize: MainAxisSize.min, children: [ for (final mode in WorkspaceMode.values) AppMenuItem( key: ValueKey('sidebar-mode-${mode.name}'), label: mode == WorkspaceMode.agent ? context.l10n.workspaceAgent : context.l10n.workspaceCut, selected: widget.mode == mode, description: mode == WorkspaceMode.agent ? context.l10n.agentLayoutDescription : context.l10n.editingLayoutDescription, onPressed: () { widget.onModeChanged(mode); if (widget.navigationOnly) _finishNavigation(); }, ), ], ), builder: (context, toggle) => TextButton( key: const Key('sidebar-mode-trigger'), onPressed: toggle, style: ButtonStyle( foregroundColor: sidebarActionButtonStyle(context) .foregroundColor, padding: const WidgetStatePropertyAll( EdgeInsets.symmetric(horizontal: 8), ), minimumSize: const WidgetStatePropertyAll( Size(0, AppSidebarMetrics.modeHeight), ), alignment: AlignmentDirectional.centerStart, backgroundColor: WidgetStateProperty.resolveWith( (states) => states.contains(WidgetState.hovered) || states.contains(WidgetState.focused) || states.contains(WidgetState.pressed) ? AppSidebarColors.of(context).hover : Colors.transparent, ), overlayColor: const WidgetStatePropertyAll( Colors.transparent, ), shape: WidgetStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: Text( widget.mode == WorkspaceMode.agent ? context.l10n.workspaceAgent : context.l10n.workspaceCut, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppSidebarTypography.style( context, fontSize: AppSidebarMetrics.titleFontSize, height: AppSidebarMetrics.titleLineHeight, weight: FontWeight.w600, ), ), ), const SizedBox(width: AppSpacing.small), const Icon( AppIcons.expandMore, size: AppSidebarMetrics.iconSize, ), ], ), ), ), ), ), ], ), ); final sectionHeader = !_touch && widget.externalWindowFrame ? SizedBox( key: Key( widget.navigationOnly ? 'sidebar-projects-header' : 'project-content-header', ), height: AppDesktopMetrics.panelHeader, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ Icon( widget.resourcesSelected ? AppIcons.mediaLibrary : AppIcons.folder, size: 16, ), const SizedBox(width: 8), Expanded( child: Text( key: !widget.resourcesSelected && !widget.librarySelected ? const Key('projects-heading') : null, widget.resourcesSelected ? context.l10n.materials : widget.librarySelected ? context.l10n.navigationLibrary : context.l10n.projects, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleSmall, ), ), if (!widget.resourcesSelected && !widget.librarySelected) IconButton( key: const Key('create-project'), tooltip: context.l10n.newProject, onPressed: widget.onCreateProject, icon: const Icon(AppIcons.add, size: 16), ), ], ), ), ) : legacyModeHeader; final modeHeader = !_touch && widget.navigationOnly ? Column( key: const Key('project-content-header'), mainAxisSize: MainAxisSize.min, children: [ if (!widget.externalWindowFrame) legacyModeHeader, if (widget.librarySelected) SizedBox( height: AppDesktopMetrics.panelHeader, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Align( alignment: AlignmentDirectional.centerStart, child: Text(context.l10n.navigationLibrary), ), ), ) else SidebarCategoryTabs( mediaSelected: widget.resourcesSelected, onSelected: widget.onResourcesSelected, ), if (widget.externalWindowFrame && !widget.resourcesSelected && !widget.librarySelected) sectionHeader, ], ) : sectionHeader; final projectList = SingleChildScrollView( key: const Key('sidebar-projects-conversations'), primary: false, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if ((widget.mode == WorkspaceMode.agent || widget.navigationOnly) && (_touch || !widget.externalWindowFrame)) MouseRegion( onEnter: (_) => setState(() => _projectHeaderHovered = true), onExit: (_) => setState(() => _projectHeaderHovered = false), child: Padding( padding: EdgeInsets.fromLTRB( AppSidebarMetrics.outerPadding, _touch ? 0 : AppSpacing.gap, AppSidebarMetrics.outerPadding, AppSidebarMetrics.sectionGap, ), child: _touch ? TouchProjectsHeader(onCreate: widget.onCreateProject) : _ProjectsHeader( onCreateProject: widget.onCreateProject, hovered: _projectHeaderHovered, ), ), ), if (widget.state.recent.isEmpty) Padding( padding: const EdgeInsets.symmetric( horizontal: AppSidebarMetrics.outerPadding + AppSidebarMetrics.cellPadding, vertical: AppSpacing.small, ), child: Text( context.l10n.projectsNone, style: AppSidebarTypography.style( context, fontSize: AppSidebarMetrics.hintFontSize, height: AppSidebarMetrics.lineHeight, color: AppSidebarColors.of(context).tertiary, ), ), ), for (var index = 0; index < widget.state.recent.length; index++) ...[ if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap), _projectGroup(widget.state.recent[index]), ], Consumer( builder: (context, ref, _) { ref.watch( conversationSidebarProvider.select( (value) => (value.hasError, value.value?.reloadFailed), ), ); return _conversationError == null ? const SizedBox.shrink() : Padding( padding: const EdgeInsets.all(AppSpacing.small), child: Text( _conversationError!, style: Theme.of(context).textTheme.bodySmall, ), ); }, ), Consumer( builder: (context, ref, _) { ref.watch( conversationSidebarProvider.select( (value) => (value.value?.projectId, value.value?.trashed), ), ); return widget.state.activeProject == null || (_trashed.isEmpty && !_showTrash) ? const SizedBox.shrink() : ExpansionTile( title: Text( context.l10n.agentTrash, style: AppSidebarTypography.style( context, color: AppSidebarColors.of(context).tertiary, weight: FontWeight.w500, ), ), initiallyExpanded: _showTrash, onExpansionChanged: (value) => setState(() => _showTrash = value), trailing: _trashed.isEmpty ? Icon( _showTrash ? AppIcons.expandLess : AppIcons.expandMore, ) : TextButton( onPressed: _emptyTrash, child: Text(context.l10n.agentEmptyTrash), ), children: [ ListView.builder( primary: false, shrinkWrap: true, itemCount: _trashed.length, itemBuilder: (context, index) { final item = _trashed[index]; return ListTile( dense: true, title: Text( item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppSidebarTypography.style( context, fontSize: AppSidebarMetrics.fontSize, height: AppSidebarMetrics.lineHeight, color: AppSidebarColors.of(context).secondary, ), ), trailing: AppDropdownMenu( items: [ AppMenuItem( label: context.l10n.agentRestore, onPressed: () => _restoreConversation(item), ), AppMenuItem( label: context.l10n.agentDeleteForever, destructive: true, onPressed: () => _deleteForever(item), ), ], builder: (context, toggle, focus) => IconButton( focusNode: focus, onPressed: toggle, icon: const Icon(AppIcons.more), tooltip: context.l10n.agentConversationActions, ), ), ); }, ), ], ); }, ), ], ), ); final chatPanel = widget.agent; if (widget.navigationOnly) { return Material( color: Theme.of(context).colorScheme.surfaceContainerLow, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ modeHeader, Expanded( child: _touch ? projectList : IndexedStack( index: widget.librarySelected ? 2 : widget.resourcesSelected ? 1 : 0, children: [ TickerMode( enabled: !widget.resourcesSelected && !widget.librarySelected, child: projectList, ), TickerMode( enabled: widget.resourcesSelected && !widget.librarySelected, child: ExcludeFocus( excluding: !widget.resourcesSelected || widget.librarySelected, child: _resourcesVisited ? MediaPanel( projectId: widget.state.activeProject?.id, onSelectProject: widget.onSelectProject, ) : Center( child: Text(context.l10n.projectsNone), ), ), ), const SizedBox.expand( key: Key('resource-library-empty'), ), ], ), ), ], ), ); } final content = widget.mode == WorkspaceMode.agent ? Row( key: const Key('agent-mode-layout'), children: [ if (!widget.navigationCollapsed) SizedBox( width: widget.navigationWidth, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ modeHeader, Expanded(child: projectList), ], ), ), if (!widget.navigationCollapsed) VerticalDivider( key: const Key('sidebar-chat-divider'), width: 1, color: AppTheme.sidebarDividerColor(context), ), Expanded( child: Material( key: const Key('agent-panel-surface'), color: Theme.of(context).colorScheme.surface, child: WindowHeaderPane( offset: Offset( widget.navigationCollapsed ? 0 : widget.navigationWidth + 1, 0, ), child: Column( children: [ SizedBox( key: const Key('agent-content-header'), height: AppControlSize.panelHeader, child: WindowHeaderPadding( child: LayoutBuilder( builder: (context, constraints) { final header = Row( children: [ widget.agentHeaderLeading, Expanded( child: Text( widget.state.activeProject?.name ?? '', key: const Key( 'workspace-project-title', ), maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .titleSmall, ), ), if (widget.editorHidden) HeaderControlRegion( child: Padding( padding: const EdgeInsetsDirectional.only( end: AppSpacing.small, ), child: SizedBox.square( dimension: AppControlSize.headerButton, child: IconButton( key: const Key( 'expand-editor-button', ), tooltip: context.l10n.expandEditor, onPressed: widget.onExpandEditor, padding: EdgeInsets.zero, icon: const Icon( AppIcons.splitVertical, size: AppIconSize.header, ), ), ), ), ), ], ); if (constraints.maxWidth >= WorkspaceLayoutMetrics .contentMinimumWidth) { return header; } return SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox( width: WorkspaceLayoutMetrics .contentMinimumWidth, child: header, ), ); }, ), ), ), Expanded(child: chatPanel), ], ), ), ), ), ], ) : Column( key: const Key('cut-mode-layout'), crossAxisAlignment: CrossAxisAlignment.stretch, children: [ modeHeader, MouseRegion( onEnter: (_) => setState(() => _projectHeaderHovered = true), onExit: (_) => setState(() => _projectHeaderHovered = false), child: Padding( padding: const EdgeInsets.fromLTRB( AppSidebarMetrics.outerPadding, 4, AppSidebarMetrics.outerPadding, 0, ), child: MenuAnchor( controller: _cutProjectsMenu, consumeOutsideTap: false, alignmentOffset: const Offset(0, 4), style: AppMenuStyle.panel(context, minWidth: 300), menuChildren: [ SizedBox( width: 320, height: (MediaQuery.sizeOf(context).height - 180).clamp( 160.0, 440.0, ), child: projectList, ), ], builder: (context, controller, _) => _ProjectsHeader( hovered: _projectHeaderHovered, onPressed: () => controller.isOpen ? controller.close() : controller.open(), onCreateProject: widget.onCreateProject == null ? null : () { controller.close(); widget.onCreateProject!(); }, ), ), ), ), Expanded(child: chatPanel), ], ); return Material( color: Theme.of(context).colorScheme.surfaceContainerLow, child: compact ? LayoutBuilder( builder: (context, constraints) => SingleChildScrollView( child: SizedBox( height: constraints.maxHeight < 650 ? 650 : constraints.maxHeight, child: content, ), ), ) : content, ); } } class _ProjectsHeader extends StatelessWidget { const _ProjectsHeader({ required this.onCreateProject, required this.hovered, this.onPressed, }); final VoidCallback? onCreateProject; final bool hovered; final VoidCallback? onPressed; @override Widget build(BuildContext context) => Row( children: [ Expanded( child: SizedBox( key: const Key('projects-heading'), height: AppSidebarMetrics.sectionHeight, child: Material( color: Colors.transparent, child: InkWell( key: onPressed == null ? null : const Key('cut-projects-trigger'), onTap: onPressed, hoverColor: AppSidebarColors.of(context).hover, focusColor: AppSidebarColors.of(context).hover, highlightColor: Colors.transparent, splashColor: Colors.transparent, borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppSpacing.small, ), child: Row( children: [ Flexible( child: Text( context.l10n.projects, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppSidebarTypography.style( context, fontSize: AppTheme.isDesktop(context) ? 13 : AppSidebarMetrics.sectionFontSize, weight: FontWeight.w500, color: AppSidebarColors.of(context).section, ), ), ), if (onPressed != null) ...[ const SizedBox(width: AppSpacing.tiny), Icon( AppIcons.expandMore, size: AppSidebarMetrics.iconSize, color: AppSidebarColors.of(context).secondary, ), ], ], ), ), ), ), ), ), const SizedBox(width: AppSpacing.tiny), AnimatedOpacity( opacity: hovered ? 1 : 0, duration: const Duration(milliseconds: 120), child: SizedBox.square( key: const Key('projects-more'), dimension: AppSidebarMetrics.actionSize, child: Center( child: Icon( AppIcons.more, size: AppSidebarMetrics.iconSize, color: AppSidebarColors.of(context).tertiary, ), ), ), ), IgnorePointer( ignoring: !hovered, child: AnimatedOpacity( opacity: hovered ? 1 : 0, duration: const Duration(milliseconds: 120), child: SizedBox.square( dimension: AppSidebarMetrics.actionSize, child: IconButton( key: const Key('create-project'), style: sidebarActionButtonStyle(context), tooltip: context.l10n.newProject, onPressed: onCreateProject, padding: EdgeInsets.zero, icon: const Icon(AppIcons.add, size: AppSidebarMetrics.iconSize), ), ), ), ), ], ); } Color _sidebarItemHighlightColor(BuildContext context) => Theme.of(context).colorScheme.secondaryContainer; ButtonStyle sidebarActionButtonStyle(BuildContext context) => AppTheme.iconButtonStyle(context); ButtonStyle _projectActionButtonStyle(BuildContext context) { if (!AppTheme.isDesktop(context)) return sidebarActionButtonStyle(context); final colors = AppSidebarColors.of(context); final accent = Theme.of(context).colorScheme.primary; return sidebarActionButtonStyle(context).copyWith( foregroundColor: WidgetStateProperty.resolveWith((states) { if (states.contains(WidgetState.disabled)) return colors.disabled; if (states.contains(WidgetState.hovered) || states.contains(WidgetState.focused) || states.contains(WidgetState.pressed)) { return accent; } return colors.secondary; }), backgroundColor: const WidgetStatePropertyAll(Colors.transparent), overlayColor: WidgetStateProperty.resolveWith((states) { if (states.contains(WidgetState.disabled)) return Colors.transparent; if (states.contains(WidgetState.pressed)) { return accent.withValues(alpha: .16); } if (states.contains(WidgetState.hovered) || states.contains(WidgetState.focused)) { return accent.withValues(alpha: .10); } return Colors.transparent; }), shape: WidgetStatePropertyAll( RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), ), ); } String _availabilityLabel( BuildContext context, ProjectAvailability availability, ) => switch (availability) { ProjectAvailability.available => '', ProjectAvailability.missing || ProjectAvailability.volumeOffline || ProjectAvailability.invalid || ProjectAvailability.unavailable => context.l10n.projectAccessFailed, }; class _ProjectTile extends StatelessWidget { const _ProjectTile({ required this.project, required this.active, required this.availabilityLabel, required this.onSelect, required this.onRename, this.sidebarStyle = false, this.hovered = false, this.onNewConversation, this.onRemove, this.onToggleExpanded, this.expanded = true, }); final RecentProject project; final bool active; final String availabilityLabel; final VoidCallback onSelect; final VoidCallback onRename; final bool sidebarStyle; final bool hovered; final VoidCallback? onNewConversation; final VoidCallback? onRemove; final VoidCallback? onToggleExpanded; final bool expanded; List _menuItems(BuildContext context) => [ AppMenuItem( label: context.l10n.rename, icon: AppIcons.rename, onPressed: project.availability.canOpen ? onRename : null, ), if (sidebarStyle) ...[ const AppMenuSeparator(), AppMenuItem( label: context.l10n.removeProjectFromSidebar, onPressed: onRemove, ), ], ]; @override Widget build(BuildContext context) => AppContextMenu( itemsBuilder: _menuItems, child: ListTile( key: ValueKey( '${sidebarStyle ? 'sidebar-project' : 'open-project'}-${project.id}', ), minTileHeight: sidebarStyle ? (AppTheme.isDesktop(context) ? AppDesktopMetrics.sidebarRow : AppSidebarMetrics.rowHeight) : project.availability.canOpen ? 36 : 48, minVerticalPadding: 0, contentPadding: sidebarStyle ? EdgeInsetsDirectional.only( end: AppTheme.isDesktop(context) ? AppSidebarMetrics.cellPadding : 0, ) : const EdgeInsets.symmetric(horizontal: AppSpacing.small), horizontalTitleGap: sidebarStyle ? AppSidebarMetrics.iconGap : AppSpacing.small, minLeadingWidth: sidebarStyle ? AppSidebarMetrics.iconSlotWidth : null, visualDensity: VisualDensity.standard, titleAlignment: ListTileTitleAlignment.center, selected: active, selectedTileColor: sidebarStyle ? AppTheme.isDesktop(context) ? AppSidebarColors.of(context).hover : Colors.transparent : _sidebarItemHighlightColor(context), textColor: project.availability.canOpen ? null : Theme.of(context).disabledColor, iconColor: project.availability.canOpen ? null : Theme.of(context).disabledColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( sidebarStyle && AppTheme.isDesktop(context) ? AppRadius.large : AppRadius.extraLarge, ), ), hoverColor: sidebarStyle ? AppSidebarColors.of(context).hover : _sidebarItemHighlightColor(context), focusColor: sidebarStyle ? AppSidebarColors.of(context).hover : null, splashColor: Colors.transparent, leading: sidebarStyle ? SizedBox( width: AppSidebarMetrics.iconSlotWidth, height: AppTheme.isDesktop(context) ? AppDesktopMetrics.sidebarRow : AppSidebarMetrics.rowHeight, child: IconButton( key: ValueKey('sidebar-project-toggle-${project.id}'), tooltip: expanded ? context.l10n.collapseProject : context.l10n.expandProject, padding: EdgeInsets.zero, style: sidebarActionButtonStyle(context), onPressed: onToggleExpanded, icon: Icon( !project.availability.canOpen ? AppIcons.folderUnavailable : hovered ? (expanded ? AppIcons.expandMore : AppIcons.chevronRight) : (expanded ? AppIcons.folderOpen : AppIcons.folder), size: AppSidebarMetrics.iconSize, ), ), ) : Icon( project.availability.canOpen ? AppIcons.folder : AppIcons.folderUnavailable, size: 18, ), title: Text( project.name, maxLines: 1, overflow: TextOverflow.ellipsis, style: sidebarStyle ? AppSidebarTypography.style( context, fontSize: AppTheme.isDesktop(context) ? 13 : AppSidebarMetrics.fontSize, height: AppTheme.isDesktop(context) ? 20 / 13 : AppSidebarMetrics.lineHeight, weight: AppTheme.isDesktop(context) ? FontWeight.w500 : FontWeight.w400, color: project.availability.canOpen ? AppSidebarColors.of(context).primary : AppSidebarColors.of(context).disabled, ) : Theme.of(context).textTheme.bodyMedium?.copyWith( color: project.availability.canOpen ? null : Theme.of(context).disabledColor, ), ), subtitle: project.availability.canOpen ? null : Text( availabilityLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: sidebarStyle ? AppSidebarTypography.style( context, fontSize: AppSidebarMetrics.hintFontSize, height: AppSidebarMetrics.lineHeight, color: AppSidebarColors.of(context).tertiary, ) : null, ), trailing: sidebarStyle ? IgnorePointer( ignoring: !hovered, child: AnimatedOpacity( opacity: hovered ? 1 : 0, duration: const Duration(milliseconds: 120), child: Row( mainAxisSize: MainAxisSize.min, children: [ SizedBox.square( dimension: AppSidebarMetrics.actionSize, child: AppPopover( width: 160, child: Column( mainAxisSize: MainAxisSize.min, children: _menuItems(context), ), builder: (context, toggle) => IconButton( key: ValueKey('sidebar-project-more-${project.id}'), onPressed: toggle, style: _projectActionButtonStyle(context), padding: EdgeInsets.zero, icon: Icon( AppIcons.more, size: AppTheme.isDesktop(context) ? 14 : AppSidebarMetrics.iconSize, ), ), ), ), const SizedBox(width: 4), SizedBox.square( dimension: AppSidebarMetrics.actionSize, child: IconButton( key: ValueKey('new-agent-conversation-${project.id}'), tooltip: context.l10n.agentNewConversation, onPressed: onNewConversation, style: _projectActionButtonStyle(context), padding: EdgeInsets.zero, icon: Icon( AppIcons.edit, size: AppTheme.isDesktop(context) ? 14 : AppSidebarMetrics.iconSize, ), ), ), ], ), ), ) : null, onTap: onSelect, ), ); }