Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

67 changes: 65 additions & 2 deletions packages/web-shell/client/components/sidebar/WebShellSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,20 @@ import { DialogShell } from '../dialogs/DialogShell';
import { AddWorkspaceDialog } from '../dialogs/AddWorkspaceDialog';
import { WorkspaceSection } from './WorkspaceSection';
import { SessionGroupSection } from './SessionGroupSection';
import {
COLLAPSED_SESSION_SECTIONS_STORAGE_KEY,
isPrimaryCollapsedSectionId,
readCollapsedSessionSectionIds,
replaceOwnedCollapsedSessionSectionIds,
} from './collapsedSessionSections';
import {
SESSION_LIST_PAGE_SIZE,
SESSION_ORGANIZATION_FEATURE,
} from '../../constants/sessions';
import styles from './WebShellSidebar.module.css';

const SIDEBAR_WIDTH_STORAGE_KEY = 'qwen-code-web-shell-sidebar-width';
export { COLLAPSED_SESSION_SECTIONS_STORAGE_KEY };
const SIDEBAR_DEFAULT_WIDTH = 260;
const SIDEBAR_MIN_WIDTH = 220;
const SIDEBAR_MAX_WIDTH = 420;
Expand Down Expand Up @@ -441,6 +448,7 @@ export function WebShellSidebar({
sessions,
loading,
error,
data: sessionsPage,
reload,
deleteSession,
exportSession,
Expand All @@ -454,6 +462,14 @@ export function WebShellSidebar({
? { view: 'organized' as const, group: 'all' }
: {}),
});
// useDaemonResource starts with loading=false before autoLoad runs, so
// !loading is not “settled”. Treat the first data/error as the ready signal
// (empty lists are still defined data) so the initial-catalog latch waits.
const sessionsCatalogReady =
!organizationEnabled ||
!includePrimaryWorkspaceSessions ||
sessionsPage !== undefined ||
Boolean(error);
const { sessions: primaryPinnedSessions, reload: reloadPinnedSessions } =
useSessions({
autoLoad: organizationEnabled,
Expand Down Expand Up @@ -524,8 +540,22 @@ export function WebShellSidebar({
} | null>(null);
const [collapsedSessionSectionIds, setCollapsedSessionSectionIds] = useState<
Set<string>
>(() => new Set());
>(
() =>
new Set(
Array.from(readCollapsedSessionSectionIds()).filter(
isPrimaryCollapsedSectionId,
),
),
);
const knownSessionSectionIdsRef = useRef<Set<string>>(new Set());
// Dedicated first-sync latch. Cleared only after both groups catalog and
// sessions list have settled (including empty responses). Do not infer this
// from knownSessionSectionIdsRef.size — seeding that set early would make the
// first real sync look mid-session and auto-collapse restored expansions.
const awaitingInitialSessionCatalogRef = useRef(true);
const [groupsCatalogReady, setGroupsCatalogReady] =
useState(!organizationEnabled);
const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);
const [projectExpanded, setProjectExpanded] = useState(false);
const [projectsExpanded, setProjectsExpanded] = useState(true);
Expand Down Expand Up @@ -837,6 +867,7 @@ export function WebShellSidebar({
if (!organizationEnabled) {
setGroups([]);
setColorOptions([]);
setGroupsCatalogReady(true);
return;
}
try {
Expand All @@ -846,15 +877,21 @@ export function WebShellSidebar({
setColorOptions(catalog.colorOptions);
} catch (err) {
onError(err, t('sidebar.groupsLoadFailed'));
} finally {
// Empty catalogs still settle the latch — sessions/groups hydrate on
// independent requests, so readiness cannot wait for a non-empty list.
setGroupsCatalogReady(true);
}
}, [onError, organizationEnabled, t, workspaceActions]);

useEffect(() => {
if (!organizationEnabled) {
setGroups([]);
setColorOptions([]);
setGroupsCatalogReady(true);
return;
}
setGroupsCatalogReady(false);
void reloadGroups();
}, [organizationEnabled, reloadGroups]);

Expand Down Expand Up @@ -1933,17 +1970,43 @@ export function WebShellSidebar({
}, [filteredSessions, groups, organizationEnabled, searchQuery, t]);

useEffect(() => {
if (!organizationEnabled) return;
// Wait for both independent catalog sources. Flipping the latch on the
// first non-empty derived sections would treat later initial recent/color
// ids as brand-new and auto-collapse them; leaving the latch set when the
// first ready catalog is empty would leave the first real section expanded.
if (!groupsCatalogReady || !sessionsCatalogReady) return;

const unseenIds = sessionSections
.map((section) => section.id)
.filter((id) => !knownSessionSectionIdsRef.current.has(id));
const isInitialCatalog = awaitingInitialSessionCatalogRef.current;
if (isInitialCatalog) {
awaitingInitialSessionCatalogRef.current = false;
for (const id of unseenIds) knownSessionSectionIdsRef.current.add(id);
return;
}
if (unseenIds.length === 0) return;
for (const id of unseenIds) knownSessionSectionIdsRef.current.add(id);
// Brand-new sections that appear mid-session still start collapsed.
setCollapsedSessionSectionIds((current) => {
const next = new Set(current);
for (const id of unseenIds) next.add(id);
return next;
});
}, [sessionSections]);
}, [
groupsCatalogReady,
organizationEnabled,
sessionSections,
sessionsCatalogReady,
]);

useEffect(() => {
replaceOwnedCollapsedSessionSectionIds(
collapsedSessionSectionIds,
isPrimaryCollapsedSectionId,
);
}, [collapsedSessionSectionIds]);

const toggleSessionSection = useCallback((sectionId: string) => {
setCollapsedSessionSectionIds((current) => {
Expand Down
23 changes: 21 additions & 2 deletions packages/web-shell/client/components/sidebar/WorkspaceSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import type {
} from '@qwen-code/sdk/daemon';
import { FolderClosedIcon, FolderOpenIcon } from 'lucide-react';
import { SESSION_LIST_PAGE_SIZE } from '../../constants/sessions';
import {
readWorkspaceCollapsedGroupIds,
writeWorkspaceCollapsedGroupIds,
} from './collapsedSessionSections';
import { SessionGroupSection } from './SessionGroupSection';
import styles from './WorkspaceSection.module.css';

Expand Down Expand Up @@ -109,8 +113,8 @@ export function WorkspaceSection({
const [groups, setGroups] = useState<DaemonSessionGroup[]>([]);
const [loadError, setLoadError] = useState(false);
const [internalExpanded, setInternalExpanded] = useState(false);
const [collapsedGroupIds, setCollapsedGroupIds] = useState<Set<string>>(
() => new Set(),
const [collapsedGroupIds, setCollapsedGroupIds] = useState<Set<string>>(() =>
readWorkspaceCollapsedGroupIds(workspace.id),
);
const [actionsVisible, setActionsVisible] = useState(false);
const expanded = controlledExpanded ?? internalExpanded;
Expand All @@ -122,6 +126,21 @@ export function WorkspaceSection({
if (controlledExpanded === undefined) setInternalExpanded(false);
}, [controlledExpanded, workspace.id]);

// Remounted workspace folders must reload their own collapse prefs from the
// shared key (ids are namespaced as `ws:<id>|…` so they cannot collide with
// the primary catalog or another workspace).
useEffect(() => {
setCollapsedGroupIds(readWorkspaceCollapsedGroupIds(workspace.id));
}, [workspace.id]);

useEffect(() => {
// Depend on collapsedGroupIds only. Including workspace.id would briefly
// write the previous folder's local ids under the new workspace key before
// the reload effect above replaces state.
writeWorkspaceCollapsedGroupIds(workspace.id, collapsedGroupIds);
// eslint-disable-next-line react-hooks/exhaustive-deps -- see comment above
}, [collapsedGroupIds]);

useEffect(() => {
if (controlledExpanded === undefined && autoExpandKey) {
setInternalExpanded(true);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from 'vitest';
import {
COLLAPSED_SESSION_SECTIONS_STORAGE_KEY,
readWorkspaceCollapsedGroupIds,
replaceOwnedCollapsedSessionSectionIds,
writeWorkspaceCollapsedGroupIds,
} from './collapsedSessionSections';

afterEach(() => {
window.localStorage.clear();
});

describe('collapsedSessionSections helpers', () => {
it('merges owned ids without removing other owners', () => {
window.localStorage.setItem(
COLLAPSED_SESSION_SECTIONS_STORAGE_KEY,
JSON.stringify([
'group:primary',
'recent',
'ws:alpha|group:g1',
'ws:beta|ungrouped',
]),
);

replaceOwnedCollapsedSessionSectionIds(
new Set(['group:primary', 'color:red']),
(id) => !id.startsWith('ws:'),
);

expect(
JSON.parse(
window.localStorage.getItem(COLLAPSED_SESSION_SECTIONS_STORAGE_KEY) ??
'[]',
),
).toEqual([
'color:red',
'group:primary',
'ws:alpha|group:g1',
'ws:beta|ungrouped',
]);
});

it('round-trips workspace-local group ids through namespaced storage', () => {
writeWorkspaceCollapsedGroupIds('ws-1', new Set(['group-a', 'ungrouped']));
writeWorkspaceCollapsedGroupIds('ws-2', new Set(['group-b']));

expect(Array.from(readWorkspaceCollapsedGroupIds('ws-1')).sort()).toEqual([
'group-a',
'ungrouped',
]);
expect(Array.from(readWorkspaceCollapsedGroupIds('ws-2')).sort()).toEqual([
'group-b',
]);
expect(
JSON.parse(
window.localStorage.getItem(COLLAPSED_SESSION_SECTIONS_STORAGE_KEY) ??
'[]',
),
).toEqual([
'ws:ws-1|group:group-a',
'ws:ws-1|ungrouped',
'ws:ws-2|group:group-b',
]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* Shared localStorage helpers for Web Shell session-organization collapse
* state. Primary sidebar and per-workspace sections both write into one app
* key so preferences survive reload without competing overwrites.
*
* Id conventions:
* - Primary catalog: `group:<id>`, `recent`, `color:<name>`
* - Workspace-scoped: `ws:<workspaceId>|group:<id>`, `ws:<workspaceId>|ungrouped`
*/

export const COLLAPSED_SESSION_SECTIONS_STORAGE_KEY =
'qwen-code-web-shell-collapsed-session-groups';

const WORKSPACE_SECTION_PREFIX = 'ws:';

export function isPrimaryCollapsedSectionId(id: string): boolean {
return !id.startsWith(WORKSPACE_SECTION_PREFIX);
}

export function workspaceGroupSectionId(
workspaceId: string,
groupId: string,
): string {
return `${WORKSPACE_SECTION_PREFIX}${workspaceId}|group:${groupId}`;
}

export function workspaceUngroupedSectionId(workspaceId: string): string {
return `${WORKSPACE_SECTION_PREFIX}${workspaceId}|ungrouped`;
}

export function isWorkspaceCollapsedSectionId(
workspaceId: string,
id: string,
): boolean {
return id.startsWith(`${WORKSPACE_SECTION_PREFIX}${workspaceId}|`);
}

export function readCollapsedSessionSectionIds(): Set<string> {
if (typeof window === 'undefined') return new Set();
try {
const raw = window.localStorage.getItem(
COLLAPSED_SESSION_SECTIONS_STORAGE_KEY,
);
if (!raw) return new Set();
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return new Set();
return new Set(
parsed.filter(
(item): item is string =>
typeof item === 'string' && item.trim().length > 0,
),
);
} catch {
return new Set();
}
}

export function writeCollapsedSessionSectionIds(
ids: ReadonlySet<string>,
): void {
try {
window.localStorage.setItem(
COLLAPSED_SESSION_SECTIONS_STORAGE_KEY,
JSON.stringify(Array.from(ids).sort()),
);
} catch {
// localStorage can be unavailable in private or embedded contexts.
}
}

/**
* Replace one owner's subset of collapsed ids while preserving other owners
* (primary vs per-workspace), so parallel writers do not clobber each other.
*/
export function replaceOwnedCollapsedSessionSectionIds(
ownedIds: ReadonlySet<string>,
isOwned: (id: string) => boolean,
): void {
const stored = readCollapsedSessionSectionIds();
const next = new Set(Array.from(stored).filter((id) => !isOwned(id)));
for (const id of ownedIds) next.add(id);
writeCollapsedSessionSectionIds(next);
}

export function readWorkspaceCollapsedGroupIds(
workspaceId: string,
): Set<string> {
const stored = readCollapsedSessionSectionIds();
const local = new Set<string>();
const groupPrefix = `${WORKSPACE_SECTION_PREFIX}${workspaceId}|group:`;
const ungroupedId = workspaceUngroupedSectionId(workspaceId);
for (const id of stored) {
if (id === ungroupedId) {
local.add('ungrouped');
} else if (id.startsWith(groupPrefix)) {
local.add(id.slice(groupPrefix.length));
}
}
return local;
}

export function writeWorkspaceCollapsedGroupIds(
workspaceId: string,
localIds: ReadonlySet<string>,
): void {
const owned = new Set<string>();
for (const id of localIds) {
owned.add(
id === 'ungrouped'
? workspaceUngroupedSectionId(workspaceId)
: workspaceGroupSectionId(workspaceId, id),
);
}
replaceOwnedCollapsedSessionSectionIds(owned, (id) =>
isWorkspaceCollapsedSectionId(workspaceId, id),
);
}
Loading
Loading