File size: 43,077 Bytes
1f21206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 | import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import '@testing-library/jest-dom'
const desktopUiPreferencesApiMock = vi.hoisted(() => ({
getPreferences: vi.fn(),
updateSidebarPreferences: vi.fn(),
}))
vi.mock('../../api/desktopUiPreferences', () => ({
desktopUiPreferencesApi: desktopUiPreferencesApiMock,
}))
const openTargetStoreMock = vi.hoisted(() => ({
ensureTargets: vi.fn(),
openTarget: vi.fn(),
targets: [{ id: 'finder', kind: 'file_manager', label: 'Finder', platform: 'darwin' }],
}))
vi.mock('../../stores/openTargetStore', () => ({
useOpenTargetStore: {
getState: () => openTargetStoreMock,
},
}))
vi.mock('../../i18n', () => ({
useTranslation: () => (key: string, params?: Record<string, string | number>) => {
const translations: Record<string, string> = {
'sidebar.newSession': 'New Session',
'sidebar.scheduled': 'Scheduled',
'sidebar.settings': 'Settings',
'sidebar.searchPlaceholder': 'Search sessions',
'sidebar.noSessions': 'No sessions',
'sidebar.noMatching': 'No matching sessions',
'sidebar.sessionListFailed': 'Session list failed',
'sidebar.refreshSessions': 'Refresh sessions',
'sidebar.projects': 'Projects',
'sidebar.projectMenu': 'Project menu',
'sidebar.newProject': 'New project',
'sidebar.archiveAllChats': 'Archive all chats',
'sidebar.organizeSidebar': 'Organize sidebar',
'sidebar.sortCondition': 'Sort condition',
'sidebar.organizeByProject': 'By project',
'sidebar.organizeByRecentProject': 'Recent projects',
'sidebar.organizeByTime': 'By time',
'sidebar.sortByCreatedAt': 'Created time',
'sidebar.sortByUpdatedAt': 'Updated time',
'sidebar.newBlankProject': 'New blank project',
'sidebar.useExistingFolder': 'Use existing folder',
'sidebar.chooseProjectFolderUnavailable': 'Folder selection is only available in the desktop app.',
'sidebar.projectActions': 'Project actions for {project}',
'sidebar.pinProject': 'Pin Project',
'sidebar.unpinProject': 'Unpin Project',
'sidebar.openInFinder': 'Open in Finder',
'sidebar.openInFinderFailed': 'Could not open the project in Finder.',
'sidebar.openInFinderUnavailable': 'No file manager is available.',
'sidebar.hideProjectFromSidebar': 'Hide from Sidebar',
'sidebar.restoreProjectToSidebar': 'Restore to Sidebar',
'sidebar.restoreHiddenProjects': 'Restore hidden projects ({count})',
'sidebar.projectHidden': '{project} was hidden from the sidebar. Existing sessions were not deleted.',
'sidebar.newSessionInProject': 'New session in {project}',
'sidebar.showMoreSessions': 'Expand display',
'sidebar.showFewerSessions': 'Collapse display',
'sidebar.expandProject': 'Expand {project}',
'sidebar.collapseProject': 'Collapse {project}',
'sidebar.worktree': 'worktree',
'sidebar.sessionRunning': 'Session running',
'common.retry': 'Retry',
'common.loading': 'Loading...',
'common.cancel': 'Cancel',
'common.delete': 'Delete',
'common.rename': 'Rename',
'sidebar.timeGroup.today': 'Today',
'sidebar.timeGroup.yesterday': 'Yesterday',
'sidebar.timeGroup.last7days': 'Last 7 Days',
'sidebar.timeGroup.last30days': 'Last 30 Days',
'sidebar.timeGroup.older': 'Older',
'sidebar.missingDir': 'Missing',
'sidebar.confirmDelete': 'Delete this session? This cannot be undone.',
'sidebar.batchManage': 'Batch manage',
'sidebar.batchSelectedCount': '{count} selected',
'sidebar.batchSelectAll': 'Select all',
'sidebar.batchDeselectAll': 'Deselect all',
'sidebar.batchSelectGroup': 'Select {group}',
'sidebar.batchDeleteSelected': 'Delete selected ({count})',
'sidebar.batchDeleteConfirm': 'Delete {count} sessions? This cannot be undone.',
'sidebar.batchDeleteConfirmBody': 'The following sessions will be deleted:',
'sidebar.batchDeleteMore': '...and {count} more',
'sidebar.batchExit': 'Cancel batch mode',
'sidebar.batchDeleteSucceeded': 'Deleted {count} sessions.',
'sidebar.batchDeleteFailed': '{count} sessions could not be deleted.',
'sidebar.collapse': 'Collapse sidebar',
'sidebar.expand': 'Expand sidebar',
'session.lastUpdated': 'last updated {time}',
'session.timeJustNow': 'just now',
'session.timeMinutes': '{n}m ago',
'session.timeHours': '{n}h ago',
'session.timeDays': '{n}d ago',
}
let text = translations[key] ?? key
for (const [name, value] of Object.entries(params ?? {})) {
text = text.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value))
}
return text
},
}))
import { Sidebar } from './Sidebar'
import { useChatStore } from '../../stores/chatStore'
import { useSessionStore } from '../../stores/sessionStore'
import { useTabStore } from '../../stores/tabStore'
import { useUIStore } from '../../stores/uiStore'
import type { SessionListItem } from '../../types/session'
const PROJECT_ORDER_STORAGE_KEY = 'cc-haha-sidebar-project-order'
const PROJECT_PINNED_STORAGE_KEY = 'cc-haha-sidebar-pinned-projects'
const PROJECT_HIDDEN_STORAGE_KEY = 'cc-haha-sidebar-hidden-projects'
const PROJECT_ORGANIZATION_STORAGE_KEY = 'cc-haha-sidebar-project-organization'
const PROJECT_SORT_STORAGE_KEY = 'cc-haha-sidebar-project-sort'
function makeSession(
id: string,
title: string,
projectRoot: string,
modifiedAt: string,
): SessionListItem {
return {
id,
title,
createdAt: modifiedAt,
modifiedAt,
messageCount: 1,
projectPath: projectRoot,
projectRoot,
workDir: projectRoot,
workDirExists: true,
}
}
function makeDataTransfer() {
const data = new Map<string, string>()
return {
effectAllowed: '',
dropEffect: '',
setData: vi.fn((type: string, value: string) => data.set(type, value)),
getData: vi.fn((type: string) => data.get(type) ?? ''),
}
}
function projectGroupNames(): string[] {
return screen
.getAllByTestId(/^sidebar-project-group-/)
.map((group) => group.textContent ?? '')
.map((text) => {
if (text.includes('alpha')) return 'alpha'
if (text.includes('beta')) return 'beta'
if (text.includes('gamma')) return 'gamma'
return text
})
}
describe('Sidebar', () => {
const connectToSession = vi.fn()
const disconnectSession = vi.fn()
const fetchSessions = vi.fn()
const createSession = vi.fn()
const deleteSession = vi.fn()
const deleteSessions = vi.fn()
const addToast = vi.fn()
beforeEach(() => {
connectToSession.mockReset()
disconnectSession.mockReset()
fetchSessions.mockReset()
createSession.mockReset()
deleteSession.mockReset()
deleteSessions.mockReset()
addToast.mockReset()
desktopUiPreferencesApiMock.getPreferences.mockReset()
desktopUiPreferencesApiMock.updateSidebarPreferences.mockReset()
desktopUiPreferencesApiMock.getPreferences.mockRejectedValue(new Error('server unavailable'))
desktopUiPreferencesApiMock.updateSidebarPreferences.mockResolvedValue({
ok: true,
preferences: {
schemaVersion: 1,
sidebar: {
projectOrder: [],
pinnedProjects: [],
hiddenProjects: [],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
},
},
})
openTargetStoreMock.ensureTargets.mockReset()
openTargetStoreMock.openTarget.mockReset()
openTargetStoreMock.targets = [{ id: 'finder', kind: 'file_manager', label: 'Finder', platform: 'darwin' }]
window.localStorage.removeItem(PROJECT_ORDER_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_PINNED_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_HIDDEN_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_ORGANIZATION_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_SORT_STORAGE_KEY)
useTabStore.setState({ tabs: [], activeTabId: null })
useSessionStore.setState({
sessions: [],
activeSessionId: null,
isLoading: false,
error: null,
isBatchMode: false,
selectedSessionIds: new Set(),
fetchSessions,
createSession,
deleteSession,
deleteSessions,
})
useChatStore.setState({
connectToSession,
disconnectSession,
} as Partial<ReturnType<typeof useChatStore.getState>>)
useUIStore.setState({
sidebarOpen: true,
addToast,
} as Partial<ReturnType<typeof useUIStore.getState>>)
})
afterEach(() => {
vi.useRealTimers()
cleanup()
useTabStore.setState({ tabs: [], activeTabId: null })
window.localStorage.removeItem(PROJECT_ORDER_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_PINNED_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_HIDDEN_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_ORGANIZATION_STORAGE_KEY)
window.localStorage.removeItem(PROJECT_SORT_STORAGE_KEY)
})
it('opens a new tab when creating a session from the sidebar', async () => {
createSession.mockResolvedValue('session-new-1')
render(<Sidebar />)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
})
await waitFor(() => {
expect(createSession).toHaveBeenCalled()
expect(connectToSession).toHaveBeenCalledWith('session-new-1')
})
expect(useTabStore.getState().tabs).toEqual([
{ sessionId: 'session-new-1', title: 'New Session', type: 'session', status: 'idle' },
])
expect(useTabStore.getState().activeTabId).toBe('session-new-1')
expect(screen.getByRole('complementary')).not.toHaveAttribute('data-tauri-drag-region')
})
it('groups sessions by project and expands overflow rows', () => {
const base = new Date('2026-05-15T10:00:00.000Z').getTime()
useSessionStore.setState({
sessions: [
...Array.from({ length: 11 }, (_, index) => (
makeSession(
`alpha-${index + 1}`,
index === 0 ? 'Alpha newest' : index === 10 ? 'Alpha hidden' : `Alpha ${index + 1}`,
'/workspace/alpha',
new Date(base - index * 1000).toISOString(),
)
)),
makeSession('beta-1', 'Beta only', '/workspace/beta', new Date(base - 4000).toISOString()),
],
})
render(<Sidebar />)
expect(screen.getByText('Projects')).toBeInTheDocument()
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.queryByText('/workspace/alpha')).not.toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Alpha newest/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Alpha hidden/ })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: /Alpha newest/ }).closest('[class*="pl-0"]')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Expand display' }))
expect(screen.getByRole('button', { name: /Alpha hidden/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Collapse display' })).toBeInTheDocument()
})
it('reorders project groups by dragging project headers while preserving expanded state', async () => {
const base = new Date('2026-05-15T10:00:00.000Z').getTime()
useSessionStore.setState({
sessions: [
...Array.from({ length: 11 }, (_, index) => (
makeSession(
`alpha-${index + 1}`,
index === 10 ? 'Alpha hidden' : `Alpha ${index + 1}`,
'/workspace/alpha',
new Date(base - index * 1000).toISOString(),
)
)),
makeSession('beta-1', 'Beta Session', '/workspace/beta', new Date(base - 20_000).toISOString()),
makeSession('gamma-1', 'Gamma Session', '/workspace/gamma', new Date(base - 30_000).toISOString()),
],
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Expand display' }))
expect(screen.getByRole('button', { name: /Alpha hidden/ })).toBeInTheDocument()
expect(projectGroupNames().slice(0, 3)).toEqual(['alpha', 'beta', 'gamma'])
const dataTransfer = makeDataTransfer()
const alphaGroup = screen.getByTestId('sidebar-project-group-workspace-alpha')
vi.spyOn(alphaGroup, 'getBoundingClientRect').mockReturnValue({
top: 0,
bottom: 100,
left: 0,
right: 280,
width: 280,
height: 100,
x: 0,
y: 0,
toJSON: () => ({}),
})
fireEvent.dragStart(screen.getByRole('button', { name: 'Collapse gamma' }), { dataTransfer })
fireEvent.dragOver(alphaGroup, { clientY: -10, dataTransfer })
fireEvent.drop(alphaGroup, { clientY: -10, dataTransfer })
await waitFor(() => {
expect(projectGroupNames().slice(0, 3)).toEqual(['alpha', 'gamma', 'beta'])
})
expect(screen.getByRole('button', { name: /Alpha hidden/ })).toBeInTheDocument()
expect(JSON.parse(window.localStorage.getItem(PROJECT_ORDER_STORAGE_KEY) ?? '[]').slice(0, 3)).toEqual([
'/workspace/alpha',
'/workspace/gamma',
'/workspace/beta',
])
})
it('restores the saved project drag order on render', () => {
window.localStorage.setItem(PROJECT_ORDER_STORAGE_KEY, JSON.stringify([
'/workspace/beta',
'/workspace/alpha',
]))
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
makeSession('gamma-1', 'Gamma Session', '/workspace/gamma', now),
],
})
render(<Sidebar />)
expect(projectGroupNames().slice(0, 3)).toEqual(['beta', 'alpha', 'gamma'])
})
it('collapses a project group without removing the project header', () => {
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Collapse alpha' }))
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Alpha Session/ })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: /Beta Session/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Expand alpha' })).toBeInTheDocument()
})
it('uses a bounded per-project session scroller for large expanded groups', () => {
const base = new Date('2026-05-15T10:00:00.000Z').getTime()
useSessionStore.setState({
sessions: Array.from({ length: 14 }, (_, index) => (
makeSession(`alpha-${index + 1}`, `Alpha ${index + 1}`, '/workspace/alpha', new Date(base - index * 1000).toISOString())
)),
})
render(<Sidebar />)
const expandButton = screen.getByRole('button', { name: 'Expand display' })
expect(expandButton).toHaveAttribute('aria-expanded', 'false')
expect(expandButton.parentElement).toHaveClass('justify-start')
expect(expandButton).toHaveClass('text-[var(--color-text-tertiary)]', 'opacity-75')
fireEvent.click(expandButton)
expect(screen.getByTestId('sidebar-project-session-list-workspace-alpha')).toHaveClass('max-h-[420px]', 'overflow-y-auto')
expect(screen.getByRole('button', { name: 'Collapse display' })).toHaveAttribute('aria-expanded', 'true')
})
it('creates a new session from the project group context', async () => {
createSession.mockResolvedValue('session-alpha-new')
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date().toISOString()),
],
})
render(<Sidebar />)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'New session in alpha' }))
})
await waitFor(() => {
expect(createSession).toHaveBeenCalledWith('/workspace/alpha')
expect(connectToSession).toHaveBeenCalledWith('session-alpha-new')
})
})
it('shows project header menus and starts a blank project session', async () => {
createSession.mockResolvedValue('session-blank-project')
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date().toISOString()),
],
})
render(<Sidebar />)
expect(screen.getByTestId('sidebar-projects-header')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'New project' }))
expect(screen.getByRole('menuitem', { name: 'New blank project' })).toBeInTheDocument()
await act(async () => {
fireEvent.click(screen.getByRole('menuitem', { name: 'New blank project' }))
})
await waitFor(() => {
expect(createSession).toHaveBeenCalledWith(undefined)
expect(connectToSession).toHaveBeenCalledWith('session-blank-project')
})
})
it('persists project header sort preferences through desktop UI settings', async () => {
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', '2026-03-01T00:00:00.000Z'),
{
...makeSession('beta-1', 'Beta Session', '/workspace/beta', '2026-02-01T00:00:00.000Z'),
createdAt: '2026-04-01T00:00:00.000Z',
},
],
})
render(<Sidebar />)
expect(projectGroupNames().slice(0, 2)).toEqual(['alpha', 'beta'])
fireEvent.click(screen.getByRole('button', { name: 'Project menu' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Sort condition' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Created time' }))
await waitFor(() => {
expect(desktopUiPreferencesApiMock.updateSidebarPreferences).toHaveBeenCalledWith({
projectOrder: [],
pinnedProjects: [],
hiddenProjects: [],
projectOrganization: 'recentProject',
projectSortBy: 'createdAt',
})
expect(projectGroupNames().slice(0, 2)).toEqual(['beta', 'alpha'])
})
expect(window.localStorage.getItem(PROJECT_SORT_STORAGE_KEY)).toBe('createdAt')
})
it('hides archive-all from the project header menu', () => {
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Project menu' }))
expect(screen.queryByRole('menuitem', { name: 'Archive all chats' })).not.toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: 'Organize sidebar' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: 'Sort condition' })).toBeInTheDocument()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('keeps project row actions hidden until project hover or focus', () => {
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date().toISOString()),
],
})
render(<Sidebar />)
const actionButton = screen.getByRole('button', { name: 'Project actions for alpha' })
expect(actionButton.parentElement).toHaveClass('opacity-0')
expect(actionButton.parentElement).toHaveClass('group-hover/project:opacity-100')
expect(actionButton.parentElement).toHaveClass('group-focus-within/project:opacity-100')
})
it('shows the project action menu with pin and Finder actions', async () => {
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
],
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Project actions for alpha' }))
expect(screen.getByRole('menuitem', { name: 'Pin Project' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: 'Open in Finder' })).toBeInTheDocument()
expect(screen.getByRole('menuitem', { name: 'Hide from Sidebar' })).toBeInTheDocument()
expect(screen.queryByRole('menuitem', { name: 'Create Permanent Worktree' })).not.toBeInTheDocument()
expect(screen.queryByRole('menuitem', { name: 'Rename Project' })).not.toBeInTheDocument()
expect(screen.queryByRole('menuitem', { name: 'Archive Conversations' })).not.toBeInTheDocument()
await act(async () => {
fireEvent.click(screen.getByRole('menuitem', { name: 'Open in Finder' }))
})
expect(openTargetStoreMock.ensureTargets).toHaveBeenCalledTimes(1)
expect(openTargetStoreMock.openTarget).toHaveBeenCalledWith('finder', '/workspace/alpha')
})
it('pins a project above the rest of the project list', async () => {
const base = new Date('2026-05-15T10:00:00.000Z').getTime()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date(base).toISOString()),
makeSession('beta-1', 'Beta Session', '/workspace/beta', new Date(base - 20_000).toISOString()),
],
})
render(<Sidebar />)
expect(projectGroupNames().slice(0, 2)).toEqual(['alpha', 'beta'])
fireEvent.click(screen.getByRole('button', { name: 'Project actions for beta' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Pin Project' }))
await waitFor(() => {
expect(projectGroupNames().slice(0, 2)).toEqual(['beta', 'alpha'])
})
expect(JSON.parse(window.localStorage.getItem(PROJECT_PINNED_STORAGE_KEY) ?? '[]')).toEqual(['/workspace/beta'])
})
it('removes a project from the sidebar without deleting its sessions', async () => {
const base = new Date('2026-05-15T10:00:00.000Z').getTime()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date(base).toISOString()),
makeSession('beta-1', 'Beta Session', '/workspace/beta', new Date(base - 20_000).toISOString()),
],
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Project actions for beta' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Hide from Sidebar' }))
await waitFor(() => {
expect(screen.queryByText('beta')).not.toBeInTheDocument()
})
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(deleteSessions).not.toHaveBeenCalled()
expect(deleteSession).not.toHaveBeenCalled()
expect(JSON.parse(window.localStorage.getItem(PROJECT_HIDDEN_STORAGE_KEY) ?? '[]')).toEqual(['/workspace/beta'])
expect(addToast).toHaveBeenCalledWith({
type: 'info',
message: 'beta was hidden from the sidebar. Existing sessions were not deleted.',
})
})
it('keeps hidden projects out of the sidebar without the removed project filter', () => {
window.localStorage.setItem(PROJECT_HIDDEN_STORAGE_KEY, JSON.stringify(['/workspace/beta']))
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
render(<Sidebar />)
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.queryByText('beta')).not.toBeInTheDocument()
expect(screen.queryByTestId('project-filter')).not.toBeInTheDocument()
})
it('restores hidden projects from the project header menu', async () => {
window.localStorage.setItem(PROJECT_HIDDEN_STORAGE_KEY, JSON.stringify(['/workspace/beta']))
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
render(<Sidebar />)
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.queryByText('beta')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Project menu' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Restore hidden projects (1)' }))
await waitFor(() => {
expect(screen.getByText('beta')).toBeInTheDocument()
})
expect(JSON.parse(window.localStorage.getItem(PROJECT_HIDDEN_STORAGE_KEY) ?? '[]')).toEqual([])
expect(desktopUiPreferencesApiMock.updateSidebarPreferences).toHaveBeenCalledWith({
projectOrder: [],
pinnedProjects: [],
hiddenProjects: [],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
})
})
it('restores a hidden project when a new session is created in that project', async () => {
window.localStorage.setItem(PROJECT_HIDDEN_STORAGE_KEY, JSON.stringify(['/workspace/beta']))
createSession.mockResolvedValue('beta-new')
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
useTabStore.setState({
tabs: [{ sessionId: 'beta-1', title: 'Beta Session', type: 'session', status: 'idle' }],
activeTabId: 'beta-1',
})
render(<Sidebar />)
expect(screen.queryByText('beta')).not.toBeInTheDocument()
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
})
await waitFor(() => {
expect(createSession).toHaveBeenCalledWith('/workspace/beta')
expect(screen.getByText('beta')).toBeInTheDocument()
})
expect(JSON.parse(window.localStorage.getItem(PROJECT_HIDDEN_STORAGE_KEY) ?? '[]')).toEqual([])
expect(desktopUiPreferencesApiMock.updateSidebarPreferences).toHaveBeenCalledWith({
projectOrder: [],
pinnedProjects: [],
hiddenProjects: [],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
})
})
it('uses server sidebar preferences across browser and desktop storage contexts', async () => {
desktopUiPreferencesApiMock.getPreferences.mockResolvedValueOnce({
exists: true,
preferences: {
schemaVersion: 1,
sidebar: {
projectOrder: ['/workspace/beta', '/workspace/alpha'],
pinnedProjects: ['/workspace/beta'],
hiddenProjects: ['/workspace/alpha'],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
},
},
})
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', now),
makeSession('beta-1', 'Beta Session', '/workspace/beta', now),
],
})
render(<Sidebar />)
await waitFor(() => {
expect(screen.queryByText('alpha')).not.toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
})
expect(JSON.parse(window.localStorage.getItem(PROJECT_ORDER_STORAGE_KEY) ?? '[]')).toEqual([
'/workspace/beta',
'/workspace/alpha',
])
expect(JSON.parse(window.localStorage.getItem(PROJECT_PINNED_STORAGE_KEY) ?? '[]')).toEqual(['/workspace/beta'])
expect(JSON.parse(window.localStorage.getItem(PROJECT_HIDDEN_STORAGE_KEY) ?? '[]')).toEqual(['/workspace/alpha'])
})
it('migrates cached local sidebar preferences when the server file is missing after update', async () => {
desktopUiPreferencesApiMock.getPreferences.mockResolvedValueOnce({
exists: false,
preferences: {
schemaVersion: 1,
sidebar: {
projectOrder: [],
pinnedProjects: [],
hiddenProjects: [],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
},
},
})
window.localStorage.setItem(PROJECT_HIDDEN_STORAGE_KEY, JSON.stringify(['/workspace/beta']))
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date().toISOString()),
makeSession('beta-1', 'Beta Session', '/workspace/beta', new Date().toISOString()),
],
})
render(<Sidebar />)
await waitFor(() => {
expect(desktopUiPreferencesApiMock.updateSidebarPreferences).toHaveBeenCalledWith({
projectOrder: [],
pinnedProjects: [],
hiddenProjects: ['/workspace/beta'],
projectOrganization: 'recentProject',
projectSortBy: 'updatedAt',
})
})
expect(screen.queryByText('beta')).not.toBeInTheDocument()
})
it('ignores corrupt hidden project storage for backward compatibility', () => {
window.localStorage.setItem(PROJECT_HIDDEN_STORAGE_KEY, '{bad json')
useSessionStore.setState({
sessions: [
makeSession('alpha-1', 'Alpha Session', '/workspace/alpha', new Date().toISOString()),
],
})
render(<Sidebar />)
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Alpha Session/ })).toBeInTheDocument()
})
it('keeps persisted worktree sessions under the source project group', () => {
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
makeSession('source-1', 'Source Session', '/workspace/repo', now),
{
...makeSession('worktree-1', 'Worktree Session', '/workspace/repo/.claude/worktrees/desktop-main-12345678', now),
projectRoot: '/workspace/repo',
},
{
...makeSession('subdir-1', 'Subdir Session', '/workspace/repo/packages/app', now),
projectRoot: '/workspace/repo',
},
],
})
render(<Sidebar />)
expect(screen.getByText('repo')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Source Session/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Worktree Session/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Subdir Session/ })).toBeInTheDocument()
expect(screen.getAllByText('worktree')).toHaveLength(1)
})
it('right-aligns running status, worktree marker, and update time on session rows', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-05-19T12:00:00.000Z'))
useSessionStore.setState({
sessions: [
{
...makeSession('running-worktree', 'Running Worktree', '/workspace/repo/.claude/worktrees/desktop-main-12345678', '2026-05-19T07:00:00.000Z'),
projectRoot: '/workspace/repo',
},
makeSession('idle-source', 'Idle Source', '/workspace/repo', '2026-05-19T11:40:00.000Z'),
],
})
useTabStore.setState({
tabs: [
{ sessionId: 'running-worktree', title: 'Running Worktree', type: 'session', status: 'running' },
{ sessionId: 'idle-source', title: 'Idle Source', type: 'session', status: 'idle' },
],
activeTabId: 'running-worktree',
})
render(<Sidebar />)
const runningRow = screen.getByRole('button', { name: /Running Worktree/ })
expect(within(runningRow).getByLabelText('Session running')).toBeInTheDocument()
expect(within(runningRow).getByText('worktree')).toHaveClass('sr-only')
expect(within(runningRow).getByText('5h ago')).toBeInTheDocument()
const idleRow = screen.getByRole('button', { name: /Idle Source/ })
expect(within(idleRow).queryByLabelText('Session running')).not.toBeInTheDocument()
expect(within(idleRow).getByText('20m ago')).toBeInTheDocument()
})
it('shows a toast when session creation fails', async () => {
createSession.mockRejectedValue(new Error('boom'))
render(<Sidebar />)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
})
await waitFor(() => {
expect(addToast).toHaveBeenCalledWith({
type: 'error',
message: 'boom',
})
})
expect(useTabStore.getState().tabs).toEqual([])
})
it('requires confirmation before deleting a session from the sidebar', async () => {
deleteSession.mockResolvedValue(undefined)
useSessionStore.setState({
sessions: [
{
id: 'session-1',
title: 'Open Session',
createdAt: new Date().toISOString(),
modifiedAt: new Date().toISOString(),
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
],
})
useTabStore.setState({
tabs: [{ sessionId: 'session-1', title: 'Open Session', type: 'session', status: 'idle' }],
activeTabId: 'session-1',
})
render(<Sidebar />)
fireEvent.contextMenu(screen.getByRole('button', { name: /Open Session/ }))
fireEvent.click(screen.getByRole('button', { name: 'Delete' }))
expect(deleteSession).not.toHaveBeenCalled()
const dialog = screen.getByRole('dialog')
expect(dialog).toBeInTheDocument()
expect(screen.getByText('Delete this session? This cannot be undone.')).toBeInTheDocument()
await act(async () => {
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
})
await waitFor(() => {
expect(deleteSession).toHaveBeenCalledWith('session-1')
expect(disconnectSession).toHaveBeenCalledWith('session-1')
})
expect(useTabStore.getState().tabs).toEqual([])
expect(useTabStore.getState().activeTabId).toBeNull()
})
it('selects and deletes multiple sessions from batch mode', async () => {
deleteSessions.mockResolvedValue({
ok: true,
successes: ['session-1', 'session-2'],
failures: [],
})
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
{
id: 'session-1',
title: 'First Session',
createdAt: now,
modifiedAt: now,
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
{
id: 'session-2',
title: 'Second Session',
createdAt: now,
modifiedAt: now,
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
],
})
useTabStore.setState({
tabs: [
{ sessionId: 'session-1', title: 'First Session', type: 'session', status: 'idle' },
{ sessionId: 'session-2', title: 'Second Session', type: 'session', status: 'idle' },
],
activeTabId: 'session-1',
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Batch manage' }))
fireEvent.click(screen.getByRole('button', { name: /First Session/ }))
fireEvent.click(screen.getByRole('button', { name: /Second Session/ }))
expect(screen.getByText('2 selected')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Delete selected (2)' }))
const dialog = screen.getByRole('dialog')
expect(within(dialog).getByText('Delete 2 sessions? This cannot be undone.')).toBeInTheDocument()
expect(within(dialog).getByText('First Session')).toBeInTheDocument()
expect(within(dialog).getByText('Second Session')).toBeInTheDocument()
await act(async () => {
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
})
await waitFor(() => {
expect(deleteSessions).toHaveBeenCalledWith(['session-1', 'session-2'])
expect(disconnectSession).toHaveBeenCalledWith('session-1')
expect(disconnectSession).toHaveBeenCalledWith('session-2')
})
expect(useTabStore.getState().tabs).toEqual([])
expect(addToast).toHaveBeenCalledWith({
type: 'success',
message: 'Deleted 2 sessions.',
})
})
it('renders batch-selected sessions as separated selected rows', () => {
const now = new Date().toISOString()
useSessionStore.setState({
sessions: [
{
id: 'session-1',
title: 'First Session',
createdAt: now,
modifiedAt: now,
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
{
id: 'session-2',
title: 'Second Session',
createdAt: now,
modifiedAt: now,
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
{
id: 'session-3',
title: 'Third Session',
createdAt: now,
modifiedAt: now,
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
],
})
useTabStore.setState({
tabs: [{ sessionId: 'session-2', title: 'Second Session', type: 'session', status: 'idle' }],
activeTabId: 'session-2',
})
render(<Sidebar />)
fireEvent.click(screen.getByRole('button', { name: 'Batch manage' }))
fireEvent.click(screen.getByRole('button', { name: /First Session/ }))
expect(screen.getByRole('button', { name: /First Session/ }).parentElement).toHaveClass('mb-0.5')
expect(screen.getByRole('button', { name: /First Session/ })).toHaveClass('sidebar-session-row--selected')
expect(screen.getByRole('button', { name: /Second Session/ })).toHaveClass('sidebar-session-row--active')
expect(screen.getByRole('button', { name: /Third Session/ })).toHaveClass('sidebar-session-row--idle')
})
it('collapses into an icon rail and expands back', async () => {
render(<Sidebar />)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Collapse sidebar' }))
})
expect(useUIStore.getState().sidebarOpen).toBe(false)
expect(screen.queryByPlaceholderText('Search sessions')).not.toBeInTheDocument()
expect(screen.getByRole('complementary')).toHaveAttribute('data-state', 'closed')
expect(screen.getByTestId('sidebar-expand-button')).toHaveClass('sidebar-toggle-button--collapsed')
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Expand sidebar' }))
})
expect(useUIStore.getState().sidebarOpen).toBe(true)
expect(screen.getByPlaceholderText('Search sessions')).toBeInTheDocument()
expect(screen.getByRole('complementary')).toHaveAttribute('data-state', 'open')
})
it('renders search controls without the removed embedded project filter', () => {
render(<Sidebar />)
expect(screen.getByTestId('sidebar-search-controls-section')).toHaveStyle({ overflow: 'visible' })
expect(screen.getByTestId('sidebar-search-controls-section')).toHaveClass('relative', 'z-20')
expect(screen.getByPlaceholderText('Search sessions')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /All projects/i })).not.toBeInTheDocument()
expect(screen.queryByTestId('project-filter')).not.toBeInTheDocument()
})
it('keeps the session list section in a constrained flex column for scrolling', () => {
render(<Sidebar />)
expect(screen.getByTestId('sidebar-session-list-section')).toHaveClass('flex', 'flex-1', 'min-h-0', 'flex-col')
})
it('keeps the settings dock opaque above the scrolling session list', () => {
render(<Sidebar />)
expect(screen.getByTestId('sidebar-settings-dock')).toHaveClass('sidebar-settings-dock')
expect(screen.getByTestId('sidebar-settings-dock')).toHaveClass('absolute', 'bottom-0')
})
it('keeps mobile navigation focused on chat sessions', async () => {
const onRequestClose = vi.fn()
createSession.mockResolvedValue('session-mobile-new')
useSessionStore.setState({
sessions: [
{
id: 'session-1',
title: 'Open Session',
createdAt: new Date().toISOString(),
modifiedAt: new Date().toISOString(),
messageCount: 1,
projectPath: '/workspace/project',
workDir: '/workspace/project',
workDirExists: true,
},
],
})
render(<Sidebar isMobile onRequestClose={onRequestClose} />)
expect(screen.queryByRole('button', { name: 'Scheduled' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Settings' })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /Open Session/ }))
expect(onRequestClose).toHaveBeenCalledTimes(1)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
})
await waitFor(() => {
expect(createSession).toHaveBeenCalled()
})
expect(onRequestClose).toHaveBeenCalledTimes(2)
})
it('shows a loading state instead of an empty session list while initial fetch is pending', () => {
useSessionStore.setState({ isLoading: true, sessions: [] })
render(<Sidebar />)
expect(screen.getByText('Loading...')).toBeInTheDocument()
expect(screen.queryByText('No sessions')).not.toBeInTheDocument()
})
it('refreshes sessions manually and through low-frequency visible polling', async () => {
vi.useFakeTimers()
render(<Sidebar />)
await act(async () => {
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(1)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Refresh sessions' }))
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(2)
await act(async () => {
window.dispatchEvent(new Event('focus'))
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(2)
await act(async () => {
vi.advanceTimersByTime(30_000)
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(3)
})
it('does not poll for session changes while the document is hidden', async () => {
vi.useFakeTimers()
const originalVisibility = document.visibilityState
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: 'hidden',
})
render(<Sidebar />)
await act(async () => {
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(1)
await act(async () => {
vi.advanceTimersByTime(30_000)
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(1)
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: 'visible',
})
await act(async () => {
document.dispatchEvent(new Event('visibilitychange'))
await Promise.resolve()
})
expect(fetchSessions).toHaveBeenCalledTimes(2)
Object.defineProperty(document, 'visibilityState', {
configurable: true,
value: originalVisibility,
})
})
})
|