From 847c60600d2dfc2720edca184be7cc7ee29154ca Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:16:14 -0800 Subject: [PATCH] Improve project group ordering across hosts --- src/main/ipc/repos.ts | 1 + src/main/ipc/repos/project-group-handlers.ts | 14 +++ src/main/ipc/repos/repo-ipc-arg-schemas.ts | 4 + .../project-collection-operations.ts | 6 ++ .../project-group-batch-update.test.ts | 61 ++++++++++++ .../project-group-operations.ts | 30 +++++- .../construction/runtime-store-contract.ts | 1 + .../runtime-project-group-controller.ts | 18 +++- .../runtime-repository-command-surface.ts | 2 + src/main/runtime/rpc/methods/projects/repo.ts | 9 ++ src/preload/api/project-groups-bridge.ts | 1 + src/preload/api/repository-api.ts | 4 + .../drag/root-project-header-drop.test.ts | 22 ++++- .../drag/root-project-header-drop.ts | 52 ++++++++--- .../drag/root-project-order-commit.test.ts | 43 +++++++++ .../drag/root-project-order-commit.ts | 66 ++++++------- .../worktree-list/drag/use-header-drag.ts | 17 +++- .../worktree-list/rows/SectionHeader.tsx | 23 ++--- .../rows/section-header-create-host.test.tsx | 46 +++++++++ .../header-folder-composition.test.tsx | 1 + ...worktree-header-section-boundaries.test.ts | 38 ++++++++ .../worktree-header-section-boundaries.ts | 77 ++++++--------- .../project-group-batch-update.ts | 93 +++++++++++++++++++ .../project-groups/project-group-mutations.ts | 32 +------ .../project-group-update-persistence.ts | 74 +++++++++++++-- .../src/store/repos/create-repo-slice.ts | 2 + src/renderer/src/store/repos/repo-state.ts | 4 + src/shared/project-group-order-capability.ts | 1 + src/shared/project-group-types.ts | 2 + src/shared/protocol-version.ts | 6 +- src/shared/rpc-contract/repo-params.ts | 4 + .../rpc-params-catalog.generated.ts | 2 + 32 files changed, 602 insertions(+), 154 deletions(-) create mode 100644 src/main/persistence/tracking-repos/project-group-batch-update.test.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts create mode 100644 src/renderer/src/store/project-groups/project-group-batch-update.ts diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index af8b9c5fe8f..68ae1b3aed9 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -38,6 +38,7 @@ export function registerRepoHandlers( ipcMain.removeHandler('projectGroups:list') ipcMain.removeHandler('projectGroups:create') ipcMain.removeHandler('projectGroups:update') + ipcMain.removeHandler('projectGroups:updateMany') ipcMain.removeHandler('projectGroups:delete') ipcMain.removeHandler('projectGroups:moveProject') ipcMain.removeHandler('projectGroups:scanNested') diff --git a/src/main/ipc/repos/project-group-handlers.ts b/src/main/ipc/repos/project-group-handlers.ts index 1dd1ccfe7e4..bb9462b3349 100644 --- a/src/main/ipc/repos/project-group-handlers.ts +++ b/src/main/ipc/repos/project-group-handlers.ts @@ -12,6 +12,7 @@ import { ProjectGroupScanNestedArgs, ProjectGroupSelectorArgs, ProjectGroupUpdateArgs, + ProjectGroupUpdateManyArgs, parseProjectGroupIpcArgs } from './repo-ipc-arg-schemas' import { @@ -54,6 +55,19 @@ export function registerProjectGroupHandlers(mainWindow: BrowserWindow, store: S return updated }) + ipcMain.handle('projectGroups:updateMany', (_event, rawArgs: unknown): ProjectGroup[] | null => { + const args = parseProjectGroupIpcArgs( + ProjectGroupUpdateManyArgs, + rawArgs, + 'invalid_project_group_update_many_args' + ) + const updated = store.updateProjectGroups(args.mutations) + if (updated?.length) { + notifyReposChanged(mainWindow) + } + return updated + }) + ipcMain.handle('projectGroups:delete', (_event, rawArgs: unknown): boolean => { const args = parseProjectGroupIpcArgs( ProjectGroupSelectorArgs, diff --git a/src/main/ipc/repos/repo-ipc-arg-schemas.ts b/src/main/ipc/repos/repo-ipc-arg-schemas.ts index 32e99ac2f1a..8e3d46c8b44 100644 --- a/src/main/ipc/repos/repo-ipc-arg-schemas.ts +++ b/src/main/ipc/repos/repo-ipc-arg-schemas.ts @@ -30,6 +30,10 @@ export const ProjectGroupSelectorArgs = z.object({ groupId: z.string().min(1) }) +export const ProjectGroupUpdateManyArgs = z.object({ + mutations: z.array(ProjectGroupUpdateArgs) +}) + export const ProjectHostSetupExistingFolderIpcArgs = z.object({ projectId: z.string().min(1), projectProviderIdentity: z diff --git a/src/main/persistence/loading-store/project-collection-operations.ts b/src/main/persistence/loading-store/project-collection-operations.ts index e6d90ede3b8..2e67007eefc 100644 --- a/src/main/persistence/loading-store/project-collection-operations.ts +++ b/src/main/persistence/loading-store/project-collection-operations.ts @@ -138,6 +138,12 @@ export class ProjectCollectionOperations { return getProjectGroupOperations(this).deleteProjectGroup(groupId) } + updateProjectGroups( + mutations: Parameters[0] + ): ProjectGroup[] | null { + return getProjectGroupOperations(this).updateProjectGroups(mutations) + } + getFolderWorkspaces(): FolderWorkspace[] { return getFolderWorkspaceOperations(this).getFolderWorkspaces() } diff --git a/src/main/persistence/tracking-repos/project-group-batch-update.test.ts b/src/main/persistence/tracking-repos/project-group-batch-update.test.ts new file mode 100644 index 00000000000..a5867523bba --- /dev/null +++ b/src/main/persistence/tracking-repos/project-group-batch-update.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultPersistedState } from '../../../shared/constants' +import { createProjectGroup } from '../../../shared/project-groups' +import { ProjectGroupPersistenceOperations } from './project-group-operations' + +function fixture() { + const state = getDefaultPersistedState('/workspace') + state.projectGroups = ['a', 'b', 'other'].map((id, tabOrder) => ({ + ...createProjectGroup({ name: id, createdFrom: 'manual', tabOrder }), + id + })) + const operations = new ProjectGroupPersistenceOperations({ + state, + scheduleSave: () => {}, + removeWorkspaceLineageForRemovedFolder: () => {}, + pruneMobileClientTabSelections: () => {} + }) + return { state, operations } +} + +describe('batch project group updates', () => { + it('updates and clears ranks for selected groups without changing unrelated groups', () => { + const { state, operations } = fixture() + const other = { ...state.projectGroups![2] } + + expect( + operations.updateProjectGroups([ + { groupId: 'b', updates: { rootProjectOrder: 2000, tabOrder: 4 } }, + { groupId: 'a', updates: { rootProjectOrder: 1000, isCollapsed: true } } + ]) + ).toMatchObject([ + { id: 'b', rootProjectOrder: 2000, tabOrder: 4 }, + { id: 'a', rootProjectOrder: 1000, isCollapsed: true } + ]) + operations.updateProjectGroups([ + { groupId: 'a', updates: { rootProjectOrder: null } }, + { groupId: 'b', updates: { rootProjectOrder: 3000 } } + ]) + + expect(state.projectGroups).toMatchObject([ + { id: 'a', tabOrder: 0, isCollapsed: true }, + { id: 'b', rootProjectOrder: 3000, tabOrder: 4 }, + other + ]) + expect(state.projectGroups![0].rootProjectOrder).toBeUndefined() + expect(state.projectGroups![2]).toEqual(other) + }) + + it('rejects the entire batch when a group has disappeared', () => { + const { state, operations } = fixture() + const before = structuredClone(state.projectGroups) + + expect( + operations.updateProjectGroups([ + { groupId: 'a', updates: { rootProjectOrder: 1000 } }, + { groupId: 'missing', updates: { rootProjectOrder: 2000 } } + ]) + ).toBeNull() + expect(state.projectGroups).toEqual(before) + }) +}) diff --git a/src/main/persistence/tracking-repos/project-group-operations.ts b/src/main/persistence/tracking-repos/project-group-operations.ts index e0ff47e67fd..cd7d55bf99c 100644 --- a/src/main/persistence/tracking-repos/project-group-operations.ts +++ b/src/main/persistence/tracking-repos/project-group-operations.ts @@ -1,5 +1,9 @@ import type { PersistedState } from '../../../shared/persisted-state-types' -import type { ProjectGroup, ProjectGroupUpdate } from '../../../shared/project-group-types' +import type { + ProjectGroup, + ProjectGroupMutation, + ProjectGroupUpdate +} from '../../../shared/project-group-types' import { createProjectGroup, getProjectGroupSubtreeIds, @@ -73,6 +77,28 @@ export class ProjectGroupPersistenceOperations { if (!group) { return null } + this.applyGroupUpdate(group, updates) + this.scheduleSave() + return group + } + + updateProjectGroups(mutations: readonly ProjectGroupMutation[]): ProjectGroup[] | null { + const byId = new Map((this.state.projectGroups ?? []).map((group) => [group.id, group])) + if (mutations.some(({ groupId }) => !byId.has(groupId))) { + return null + } + const updated = mutations.map(({ groupId, updates }) => { + const group = byId.get(groupId)! + this.applyGroupUpdate(group, updates) + return group + }) + if (updated.length > 0) { + this.scheduleSave() + } + return updated + } + + private applyGroupUpdate(group: ProjectGroup, updates: ProjectGroupUpdate): void { if (updates.name !== undefined) { group.name = normalizeProjectGroupName(updates.name, group.name) } @@ -94,8 +120,6 @@ export class ProjectGroupPersistenceOperations { group.color = typeof updates.color === 'string' ? updates.color : null } group.updatedAt = Date.now() - this.scheduleSave() - return group } deleteProjectGroup(groupId: string): boolean { diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index 429ecba0b77..e65b65778b7 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -21,6 +21,7 @@ export type RuntimeStore = { getProjectGroups?: Store['getProjectGroups'] createProjectGroup?: Store['createProjectGroup'] updateProjectGroup?: Store['updateProjectGroup'] + updateProjectGroups?: Store['updateProjectGroups'] deleteProjectGroup?: Store['deleteProjectGroup'] moveProjectToGroup?: Store['moveProjectToGroup'] getFolderWorkspace?: Store['getFolderWorkspace'] diff --git a/src/main/runtime/repositories/runtime-project-group-controller.ts b/src/main/runtime/repositories/runtime-project-group-controller.ts index a2552da93d5..175110e036b 100644 --- a/src/main/runtime/repositories/runtime-project-group-controller.ts +++ b/src/main/runtime/repositories/runtime-project-group-controller.ts @@ -1,7 +1,11 @@ import type { WorkspaceAttachmentMutation } from '../../../shared/workspace-attachments/workspace-attachment-mutation' import { refuseWslHostWindowsDrivePath } from '../terminal/launch/wsl-host-windows-drive-guard' import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup, ProjectGroupUpdate } from '../../../shared/project-group-types' +import type { + ProjectGroup, + ProjectGroupMutation, + ProjectGroupUpdate +} from '../../../shared/project-group-types' import type { Repo } from '../../../shared/repo-types' import type { FolderWorkspacePathStatus, @@ -137,6 +141,18 @@ export class RuntimeProjectGroupController { return { deleted } } + async updateGroups(mutations: readonly ProjectGroupMutation[]): Promise { + const store = this.deps.getStore() + if (!store?.updateProjectGroups) { + throw new Error('runtime_unavailable') + } + const updated = store.updateProjectGroups(mutations) + if (updated?.length) { + this.deps.notifyReposChanged() + } + return updated + } + async moveProject( repoSelector: string, groupId: string | null, diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index 928c9142fc4..8cc6306f3fb 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -49,6 +49,7 @@ export type RuntimeRepositoryCommandSurface = { listVisibleFolderWorkspaces: RuntimeProjectGroupController['listVisibleFolderWorkspaces'] createProjectGroup: RuntimeProjectGroupController['createGroup'] updateProjectGroup: RuntimeProjectGroupController['updateGroup'] + updateProjectGroups: RuntimeProjectGroupController['updateGroups'] deleteProjectGroup: RuntimeProjectGroupController['deleteGroup'] moveProjectToGroup: RuntimeProjectGroupController['moveProject'] createFolderWorkspace: RuntimeProjectGroupController['createFolderWorkspace'] @@ -128,6 +129,7 @@ export function installRuntimeRepositoryCommandSurface( listVisibleFolderWorkspaces: groups.listVisibleFolderWorkspaces.bind(groups), createProjectGroup: groups.createGroup.bind(groups), updateProjectGroup: groups.updateGroup.bind(groups), + updateProjectGroups: groups.updateGroups.bind(groups), deleteProjectGroup: groups.deleteGroup.bind(groups), moveProjectToGroup: groups.moveProject.bind(groups), createFolderWorkspace: groups.createFolderWorkspace.bind(groups), diff --git a/src/main/runtime/rpc/methods/projects/repo.ts b/src/main/runtime/rpc/methods/projects/repo.ts index e3987d8a38d..d66fdd97c4a 100644 --- a/src/main/runtime/rpc/methods/projects/repo.ts +++ b/src/main/runtime/rpc/methods/projects/repo.ts @@ -24,6 +24,7 @@ import { ProjectGroupScanNested, ProjectGroupSelector, ProjectGroupUpdate, + ProjectGroupUpdateMany, RepoClone, RepoCreate, RepoHooksCheck, @@ -82,6 +83,14 @@ export const REPO_METHODS = [ params: ProjectGroupSelector, handler: async (params, { runtime }) => runtime.deleteProjectGroup(params.groupId) }), + defineMethod({ + name: 'projectGroup.updateMany', + permission: 'workspace', + params: ProjectGroupUpdateMany, + handler: async (params, { runtime }) => ({ + groups: await runtime.updateProjectGroups(params.mutations) + }) + }), defineMethod({ name: 'projectGroup.moveProject', permission: 'workspace', diff --git a/src/preload/api/project-groups-bridge.ts b/src/preload/api/project-groups-bridge.ts index c14d58b7d00..b7748aca427 100644 --- a/src/preload/api/project-groups-bridge.ts +++ b/src/preload/api/project-groups-bridge.ts @@ -6,6 +6,7 @@ export const projectGroupsApi = { list: () => ipcRenderer.invoke('projectGroups:list'), create: (args) => ipcRenderer.invoke('projectGroups:create', args), update: (args) => ipcRenderer.invoke('projectGroups:update', args), + updateMany: (args) => ipcRenderer.invoke('projectGroups:updateMany', args), delete: (args) => ipcRenderer.invoke('projectGroups:delete', args), moveProject: (args) => ipcRenderer.invoke('projectGroups:moveProject', args), scanNested: (args) => ipcRenderer.invoke('projectGroups:scanNested', args), diff --git a/src/preload/api/repository-api.ts b/src/preload/api/repository-api.ts index e74b1a80af9..16c91ac61d3 100644 --- a/src/preload/api/repository-api.ts +++ b/src/preload/api/repository-api.ts @@ -6,6 +6,7 @@ import type { NestedRepoScanResult, ProjectGroup, ProjectGroupUpdate, + ProjectGroupMutation, ProjectGroupImportMode, ProjectGroupImportResult } from '../../shared/project-group-types' @@ -131,6 +132,9 @@ export type ProjectGroupsApi = { createdFrom?: ProjectGroup['createdFrom'] }) => Promise update: (args: { groupId: string; updates: ProjectGroupUpdate }) => Promise + updateMany: (args: { + mutations: readonly ProjectGroupMutation[] + }) => Promise delete: (args: { groupId: string }) => Promise moveProject: (args: { projectId: string diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.test.ts index f47e4cb68bd..9aa470f600f 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it } from 'vitest' import type { ProjectGroup } from '../../../../../../shared/project-group-types' import type { Repo } from '../../../../../../shared/repo-types' import { + getRootProjectHeaderCountByOccurrenceKey, getRootProjectHeaderDragKeys, getSidebarRootProjectHeaderKeys, measureRootProjectHeaderDragRects, @@ -204,6 +205,16 @@ describe('root project header drops', () => { hostId: 'runtime:remote', repeated: true }, + { + type: 'header', + key: 'repo:remote-x', + count: 1, + icon: { kind: 'project' }, + repo: repo('remote-x', { executionHostId: 'runtime:remote' }), + anchorRepo: repo('x'), + hostId: 'runtime:remote', + repeated: true + }, { type: 'header', key: 'repo:y', @@ -220,13 +231,22 @@ describe('root project header drops', () => { 'repo:x', 'host:runtime:remote', 'group:a', + 'repo:x', 'repo:y' ]) expect(getRootProjectHeaderDragKeys(keys, 'group:a', 'runtime:remote')).toEqual([ 'group:a', + 'repo:x', 'repo:y' ]) - expect(getRootProjectHeaderDragKeys(keys, 'repo:x', 'runtime:remote')).toBeUndefined() + expect(getRootProjectHeaderDragKeys(keys, 'repo:y', 'local')).toBeUndefined() + expect([...getRootProjectHeaderCountByOccurrenceKey(keys)]).toEqual([ + ['["local","group:a"]', 2], + ['["local","repo:x"]', 2], + ['["runtime:remote","group:a"]', 3], + ['["runtime:remote","repo:x"]', 3], + ['["runtime:remote","repo:y"]', 3] + ]) const container = document.createElement('div') for (const [hostId, key] of [ diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.ts b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.ts index 2a129bf1efa..033f3bdd9c4 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-header-drop.ts @@ -10,6 +10,7 @@ import { import { getDistinctProjectGroups } from '../../../../../../shared/project-groups' import { getLogicalRepoOrderRankById } from '../../../../../../shared/project-section-order' import type { HostSectionRow } from '../../../../../../shared/sidebar-list/host-section-rows' +import type { GroupHeaderRow } from '../../../../../../shared/sidebar-list/row-types' export type RootProjectHeaderDrag = { rootProjectHeaderKeys?: readonly string[] @@ -49,6 +50,18 @@ export function getRootProjectHeaderDragKeys( return keys.slice(start, end) } +export function getRootProjectHeaderKey(row: GroupHeaderRow): string | undefined { + if ((row.projectGroupDepth ?? 0) !== 0) { + return undefined + } + const repo = row.repo && (row.anchorRepo ?? row.repo) + return repo + ? `repo:${repo.id}` + : row.projectGroup?.id + ? `group:${row.projectGroup.id}` + : undefined +} + export function getSidebarRootProjectHeaderKeys(rows: readonly HostSectionRow[]): string[] { const keys: string[] = [] const seen = new Set() @@ -58,21 +71,12 @@ export function getSidebarRootProjectHeaderKeys(rows: readonly HostSectionRow[]) seen.clear() continue } - if (row.type !== 'header' || (row.projectGroupDepth ?? 0) !== 0) { + if (row.type !== 'header') { continue } - const repo = row.repo - if (repo) { - const key = `repo:${repo.id}` - if (!seen.has(key)) { - keys.push(key) - } - seen.add(key) - } else if (row.projectGroup?.id) { - const key = `group:${row.projectGroup.id}` - if (!seen.has(key)) { - keys.push(key) - } + const key = getRootProjectHeaderKey(row) + if (key && !seen.has(key)) { + keys.push(key) seen.add(key) } } @@ -83,6 +87,28 @@ export function getRootProjectHeaderOccurrenceKey(key: string, hostId?: string): return JSON.stringify([hostId ?? '', key]) } +export function getRootProjectHeaderCountByOccurrenceKey( + keys: readonly string[] | undefined +): Map { + const counts = new Map() + if (!keys) { + return counts + } + let start = 0 + let hostId: string | undefined + for (let end = 0; end <= keys.length; end += 1) { + if (end < keys.length && !keys[end].startsWith('host:')) { + continue + } + for (let index = start; index < end; index += 1) { + counts.set(getRootProjectHeaderOccurrenceKey(keys[index], hostId), end - start) + } + hostId = keys[end]?.slice('host:'.length) + start = end + 1 + } + return counts +} + export function measureRootProjectHeaderDragRects( container: HTMLElement, keys: readonly string[], diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.test.ts b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.test.ts index 2d185f3dfa5..f87589a6c89 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.test.ts @@ -32,6 +32,49 @@ function repo(id: string, overrides: Partial = {}): Repo { beforeEach(() => clearRuntimeCompatibilityCache()) describe('saving root project order', () => { + it('inserts a project among legacy groups and preserves their relative order', async () => { + const groups = [group('a'), group('b', { tabOrder: 1 }), group('c', { tabOrder: 2 })] + const project = repo('x') + const store = createTestStore() + store.setState({ projectGroups: groups, repos: [project] }) + vi.stubGlobal('window', { + api: { + projectGroups: { + updateMany: async ({ + mutations + }: { + mutations: { groupId: string; updates: ProjectGroupUpdate }[] + }) => + mutations + .map(({ groupId, updates }) => ({ + ...groups.find((entry) => entry.id === groupId), + ...updates + })) + .toReversed() + }, + repos: { + update: async ({ updates }: { updates: Partial }) => ({ ...project, ...updates }) + } + } + }) + + await expect( + saveRootProjectOrderForSidebarDrop({ + state: store.getState(), + visibleKeys: ['group:a', 'group:b', 'group:c', 'repo:x'], + draggedKey: 'repo:x', + dropIndex: 1, + onCommit: () => {} + }) + ).resolves.toBe(true) + expect(store.getState().projectGroups).toMatchObject([ + { id: 'a', tabOrder: 0 }, + { id: 'b', rootProjectOrder: 1000, tabOrder: 1 }, + { id: 'c', rootProjectOrder: 2000, tabOrder: 2 } + ]) + expect(store.getState().repos).toMatchObject([{ id: 'x', projectGroupOrder: 0 }]) + }) + it('persists the moved logical group on both owners and leaves unrelated roots intact', async () => { const local = group('a', { rootProjectOrder: 0 }) const remote = { ...local, executionHostId: 'runtime:remote' } diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.ts b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.ts index fcd94e5e64e..de1b0c652d0 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/root-project-order-commit.ts @@ -4,10 +4,11 @@ import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibilit import { ipcOrRuntimeTargetForHostId } from '@/runtime/rpc/targets/runtime-client-target' import { getProjectGroupHostId } from '@/store/project-groups/project-group-owner-routing' import type { RepoSlice } from '@/store/repos/repo-state' +import { getIndexedReposById } from '@/store/repos/repository-catalog-index' import { getRootProjectOrderUpdatesForSidebarDrop } from './root-project-header-drop' export async function saveRootProjectOrderForSidebarDrop(args: { - state: Pick + state: Pick visibleKeys: readonly string[] draggedKey: string dropIndex: number @@ -22,26 +23,22 @@ export async function saveRootProjectOrderForSidebarDrop(args: { if (updates.length === 0) { return true } + const groupCopiesById = Map.groupBy(state.projectGroups, (group) => group.id) const groupUpdates = updates.flatMap((update) => { if (update.entry.kind !== 'group') { return [] } const groupId = update.entry.group.id - return state.projectGroups - .filter((group) => group.id === groupId) - .map((group) => ({ ...update, group })) + return (groupCopiesById.get(groupId) ?? []).map((group) => ({ ...update, group })) }) - const groupIds = new Set(state.projectGroups.map((group) => group.id)) const repoUpdates = updates.flatMap((update) => { if (update.entry.kind !== 'repo' || update.rootProjectOrder === undefined) { return [] } const repoId = update.entry.repo.id const order = update.rootProjectOrder - return state.repos - .filter( - (repo) => repo.id === repoId && (!repo.projectGroupId || !groupIds.has(repo.projectGroupId)) - ) + return getIndexedReposById(state.repos, repoId) + .filter((repo) => !repo.projectGroupId || !groupCopiesById.has(repo.projectGroupId)) .map((repo) => ({ repo, order })) }) const targets = groupUpdates.flatMap((update) => { @@ -68,28 +65,35 @@ export async function saveRootProjectOrderForSidebarDrop(args: { return false } args.onCommit() - const mutations = groupUpdates.map(({ group, rootProjectOrder, tabOrder }) => ({ - save: () => - state.updateProjectGroup( - group.id, - { - ...(rootProjectOrder !== undefined ? { rootProjectOrder } : {}), - ...(tabOrder !== undefined ? { tabOrder } : {}) - }, - { hostId: getProjectGroupHostId(group) } - ), - restore: () => - state.updateProjectGroup( - group.id, - { - ...(rootProjectOrder !== undefined - ? { rootProjectOrder: group.rootProjectOrder ?? null } - : {}), - ...(tabOrder !== undefined ? { tabOrder: group.tabOrder } : {}) - }, - { hostId: getProjectGroupHostId(group) } - ) - })) + const mutations: { save: () => Promise; restore: () => Promise }[] = [] + if (groupUpdates.length > 0) { + mutations.push({ + save: () => + state.updateProjectGroups( + groupUpdates.map(({ group, rootProjectOrder, tabOrder }) => ({ + groupId: group.id, + hostId: getProjectGroupHostId(group), + updates: { + ...(rootProjectOrder !== undefined ? { rootProjectOrder } : {}), + ...(tabOrder !== undefined ? { tabOrder } : {}) + } + })) + ), + restore: () => + state.updateProjectGroups( + groupUpdates.map(({ group, rootProjectOrder, tabOrder }) => ({ + groupId: group.id, + hostId: getProjectGroupHostId(group), + updates: { + ...(rootProjectOrder !== undefined + ? { rootProjectOrder: group.rootProjectOrder ?? null } + : {}), + ...(tabOrder !== undefined ? { tabOrder: group.tabOrder } : {}) + } + })) + ) + }) + } for (const { repo, order } of repoUpdates) { const hostId = getRepoExecutionHostId(repo) mutations.push({ diff --git a/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts b/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts index c3d18bc3ccf..42e2b6e0154 100644 --- a/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts +++ b/src/renderer/src/components/sidebar/worktree-list/drag/use-header-drag.ts @@ -24,7 +24,10 @@ import { getSidebarOrderedRepoHeaderIdsByBucket } from './project-header-drop' import { useProjectGroupHeaderDrag } from './project-group-header-drag' import { getSidebarOrderedProjectGroupHeaderIdsByBucket } from './project-group-header-drop' import { USER_SCROLL_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS } from '../viewport/use-scroll-suppression' -import { getSidebarRootProjectHeaderKeys } from './root-project-header-drop' +import { + getRootProjectHeaderCountByOccurrenceKey, + getSidebarRootProjectHeaderKeys +} from './root-project-header-drop' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' @@ -105,6 +108,10 @@ export function useWorktreeSidebarHeaderDrag(args: { () => new Map(projectGroups.map((group) => [group.id, group])), [projectGroups] ) + const rootProjectHeaderCountByOccurrenceKey = useMemo( + () => getRootProjectHeaderCountByOccurrenceKey(rootProjectHeaderKeys), + [rootProjectHeaderKeys] + ) // Why: an id shared by two hosts has no single owner, so leave it unrouted rather than guess. const projectGroupOwnerHostIdByGroupId = useMemo(() => { const byGroupId = new Map() @@ -259,11 +266,15 @@ export function useWorktreeSidebarHeaderDrag(args: { ) const rootProjectHeaderSectionEndByKey = useMemo( - () => getRootProjectHeaderSectionEndByKey(renderRows, firstHeaderIndex), - [renderRows, firstHeaderIndex] + () => + hasProjectGroups + ? getRootProjectHeaderSectionEndByKey(renderRows, firstHeaderIndex) + : new Map(), + [hasProjectGroups, renderRows, firstHeaderIndex] ) return { + rootProjectHeaderCountByOccurrenceKey, rootProjectHeaderSectionEndByKey, canReorderRepoHeaders, canReorderProjectGroupHeaders, diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/SectionHeader.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/SectionHeader.tsx index dc4df2b769f..cd13338ba46 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/SectionHeader.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/SectionHeader.tsx @@ -1,5 +1,5 @@ import { - getRootProjectHeaderDragKeys, + getRootProjectHeaderKey, getRootProjectHeaderOccurrenceKey } from '../drag/root-project-header-drop' import React from 'react' @@ -79,7 +79,7 @@ export function renderWorktreeSectionHeaderRow( ) const headerRepo = isRepoHeader ? usesRootProjectDrag - ? row.repo + ? (row.anchorRepo ?? row.repo) : getHeaderDragRepo(row) : undefined const projectIdForHeader = headerRepo?.id @@ -104,19 +104,14 @@ export function renderWorktreeSectionHeaderRow( projectGroupDragIdForHeader !== undefined ? headerDrag.projectGroupHeaderBucketByGroupId.get(projectGroupDragIdForHeader) : undefined - const rootProjectHeaderKey = usesRootProjectDrag - ? projectIdForHeader - ? `repo:${projectIdForHeader}` - : projectGroupDragIdForHeader - ? `group:${projectGroupDragIdForHeader}` - : undefined - : undefined + const rootProjectHeaderKey = usesRootProjectDrag ? getRootProjectHeaderKey(row) : undefined const rootProjectHeaderCount = rootProjectHeaderKey - ? getRootProjectHeaderDragKeys( - headerDrag.rootProjectHeaderKeys, - rootProjectHeaderKey, - row.hostId - )?.length + ? (headerDrag.rootProjectHeaderCountByOccurrenceKey.get( + getRootProjectHeaderOccurrenceKey(rootProjectHeaderKey, row.hostId) + ) ?? + headerDrag.rootProjectHeaderCountByOccurrenceKey.get( + getRootProjectHeaderOccurrenceKey(rootProjectHeaderKey) + )) : undefined const isDraggableRepoHeader = Boolean( headerDrag.canReorderRepoHeaders && diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx index e9f0b80ba5b..810b4bbb9c8 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx @@ -103,6 +103,7 @@ function headerContext(): SectionHeaderRowContext { repoHeaderSectionEndByRepoId: new Map(), projectGroupHeaderSectionEndByGroupId: new Map(), rootProjectHeaderKeys: undefined, + rootProjectHeaderCountByOccurrenceKey: new Map(), rootProjectHeaderSectionEndByKey: new Map() }, projectActions: { @@ -162,3 +163,48 @@ it("leaves an empty twin header to the composer's focused host, not the registra expect(useAppStore.getState().activeModal).toBe('new-workspace-composer') expect(useAppStore.getState().modalData).not.toHaveProperty('initialWorkspaceTarget') }) + +it('arms a remote root header with its ordering anchor in a view without host headers', () => { + const remote = { ...serverTwin, id: 'remote-twin' } + useAppStore.setState({ repos: [localTwin, remote] }) + const ctx = headerContext() + ctx.headerDrag = { + ...ctx.headerDrag, + canReorderRepoHeaders: true, + rootProjectHeaderKeys: ['group:projects', 'repo:repo-twin'], + rootProjectHeaderCountByOccurrenceKey: new Map([ + ['["","group:projects"]', 2], + ['["","repo:repo-twin"]', 2] + ]), + sidebarRepoHeaderIdsByBucket: new Map([['ungrouped', ['repo-twin']]]), + repoHeaderIndexByRepoId: new Map([['repo-twin', 0]]), + repoHeaderBucketByRepoId: new Map([['repo-twin', 'ungrouped']]) + } + const view = render( + + {renderWorktreeSectionHeaderRow({ + ctx, + row: { + type: 'header', + key: 'remote-header', + count: 1, + icon: { kind: 'project' }, + repo: remote, + anchorRepo: localTwin, + hostId: 'runtime:home', + repeated: true + }, + vItem: { key: 'header', index: 0, start: 0, size: 35, end: 35, lane: 0 }, + isActiveStickyHeader: false, + hasStickyHost: false, + hasHeaderTopSpacing: false, + measureVirtualRowElement: vi.fn() + })} + + ) + const header = view.container.querySelector('[data-root-project-header-key]') + expect(header?.getAttribute('data-root-project-header-key')).toBe('repo:repo-twin') + expect(header?.getAttribute('data-repo-header-id')).toBe('repo-twin') + expect(header?.getAttribute('data-root-project-header-host')).toBe('runtime:home') + expect(header?.getAttribute('data-repo-header-drag-handle')).toBe('') +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx b/src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx index 5c6841fce7b..f8f77fea67f 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx @@ -163,6 +163,7 @@ it('composes real dispatched headers, current repo gates and folder cache refres repoHeaderSectionEndByRepoId: new Map(), projectGroupHeaderSectionEndByGroupId: new Map(), rootProjectHeaderKeys: undefined, + rootProjectHeaderCountByOccurrenceKey: new Map(), rootProjectHeaderSectionEndByKey: new Map() }, projectActions: { diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts new file mode 100644 index 00000000000..1b014b043ec --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.test.ts @@ -0,0 +1,38 @@ +import { expect, it } from 'vitest' +import type { RenderRow } from '../listing/render-row' +import { getRootProjectHeaderSectionEndByKey } from './worktree-header-section-boundaries' + +it('ends a root group before a removed project header and its pending creation', () => { + const rows: RenderRow[] = [ + { + type: 'header', + key: 'group:projects', + count: 1, + icon: { kind: 'project' }, + projectGroup: { + id: 'projects', + name: 'Projects', + parentPath: null, + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + } + }, + { + type: 'header', + key: 'repo:member', + count: 0, + icon: { kind: 'project' }, + repo: { id: 'member', path: '/member', displayName: 'Member', badgeColor: '', addedAt: 1 }, + projectGroupDepth: 1 + }, + { type: 'header', key: 'repo:removed', count: 0, icon: { kind: 'project' } }, + { type: 'pending-creation', key: 'creation', creationId: 'creation', repo: undefined } + ] + + expect([...getRootProjectHeaderSectionEndByKey(rows, 0).values()]).toEqual([60]) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.ts b/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.ts index 790550554e6..416fa784afc 100644 --- a/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.ts +++ b/src/renderer/src/components/sidebar/worktree-list/viewport/worktree-header-section-boundaries.ts @@ -1,4 +1,7 @@ -import { getRootProjectHeaderOccurrenceKey } from '../drag/root-project-header-drop' +import { + getRootProjectHeaderKey, + getRootProjectHeaderOccurrenceKey +} from '../drag/root-project-header-drop' import { estimateRenderRowSize } from './virtual-rows' import type { RenderRow } from '../listing/render-row' import { getHeaderDragRepo } from '../../../../../../shared/sidebar-list/row-types' @@ -27,30 +30,6 @@ function findNextHeaderRenderRowIndex(rows: readonly RenderRow[], startIndex: nu return rows.length } -function findProjectGroupSectionEndIndex( - rows: readonly RenderRow[], - startIndex: number, - depth: number -): number { - for (let index = startIndex; index < rows.length; index++) { - const row = rows[index] - if (!row) { - continue - } - if (row.type === 'host-header') { - return index - } - if (row.type !== 'header') { - continue - } - const rowDepth = row.projectGroupDepth ?? 0 - if (rowDepth <= depth || (!row.repo && !row.projectGroup)) { - return index - } - } - return rows.length -} - export function getRepoHeaderSectionEndByRepoId(args: { rows: readonly RenderRow[] firstHeaderIndex: number @@ -78,26 +57,29 @@ export function getProjectGroupHeaderSectionEndByGroupId(args: { }): Map { const rowStarts = getEstimatedRenderRowStarts(args.rows, args.firstHeaderIndex) const sectionEndByGroupId = new Map() + const pendingGroups: { groupId: string; depth: number }[] = [] for (let index = 0; index < args.rows.length; index++) { const row = args.rows[index] - const projectGroupHeader = - row?.type === 'header' && - !row.repo && - !row.repeated && - row.projectGroup && - typeof row.projectGroup.id === 'string' - ? { row, groupId: row.projectGroup.id } - : null - const groupId = projectGroupHeader?.groupId - if (!groupId) { + if (row.type !== 'header' && row.type !== 'host-header') { continue } - const depth = projectGroupHeader.row.projectGroupDepth ?? 0 - const endIndex = findProjectGroupSectionEndIndex(args.rows, index + 1, depth) - sectionEndByGroupId.set( - groupId, - rowStarts[endIndex >= 0 ? endIndex : args.rows.length] ?? rowStarts[args.rows.length] ?? 0 - ) + const depth = + row.type === 'host-header' || (!row.repo && !row.projectGroup) + ? Number.NEGATIVE_INFINITY + : (row.projectGroupDepth ?? 0) + while (pendingGroups.length > 0) { + const pending = pendingGroups.at(-1) + if (!pending || pending.depth < depth) { + break + } + pendingGroups.pop() + sectionEndByGroupId.set(pending.groupId, rowStarts[index]) + } + if (row.type === 'header' && !row.repo && !row.repeated && row.projectGroup?.id) { + const groupId = row.projectGroup.id + sectionEndByGroupId.set(groupId, rowStarts[args.rows.length]) + pendingGroups.push({ groupId, depth: row.projectGroupDepth ?? 0 }) + } } return sectionEndByGroupId } @@ -110,15 +92,10 @@ export function getRootProjectHeaderSectionEndByKey( const ends = new Map() let pendingKey: string | undefined for (const [index, row] of rows.entries()) { - const key = - row.type === 'header' && (row.projectGroupDepth ?? 0) === 0 - ? row.repo - ? `repo:${row.repo.id}` - : row.projectGroup?.id - ? `group:${row.projectGroup.id}` - : undefined - : undefined - if (key || row.type === 'host-header') { + const key = row.type === 'header' ? getRootProjectHeaderKey(row) : undefined + const closesSection = + key || row.type === 'host-header' || (row.type === 'header' && !row.repo && !row.projectGroup) + if (closesSection) { if (pendingKey) { ends.set(pendingKey, rowStarts[index]) } diff --git a/src/renderer/src/store/project-groups/project-group-batch-update.ts b/src/renderer/src/store/project-groups/project-group-batch-update.ts new file mode 100644 index 00000000000..967e3cef0fc --- /dev/null +++ b/src/renderer/src/store/project-groups/project-group-batch-update.ts @@ -0,0 +1,93 @@ +import type { StateCreator } from 'zustand' +import type { AppState } from '../types' +import type { RepoSlice } from '../repos/repo-state' +import type { ProjectGroup, ProjectGroupMutation } from '../../../../shared/project-group-types' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import { + catalogOwnsHost, + getProjectGroupHostId, + resolveProjectGroupOwnerHostId, + runtimeTargetForProjectGroupOwner +} from './project-group-owner-routing' +import { getRuntimeTargetHostId } from '../../runtime/rpc/targets/runtime-client-target' +import { adoptFromEndpoint } from '../host-catalog/endpoint-catalog-adoption' +import { persistProjectGroupUpdates } from './project-group-update-persistence' + +export function createProjectGroupBatchUpdateAction( + set: Parameters>[0], + get: Parameters>[1] +): RepoSlice['updateProjectGroups'] { + return async (mutations) => { + const state = get() + const batches = new Map< + string, + { + target: RuntimeClientTarget + mutations: (ProjectGroupMutation & { ownerHostId: string | null })[] + } + >() + for (const { groupId, updates, hostId } of mutations) { + const target = runtimeTargetForProjectGroupOwner(state, groupId, hostId) + if (!target) { + return false + } + const ownerHostId = resolveProjectGroupOwnerHostId(state, groupId, hostId) + const key = getRuntimeTargetHostId(target) + let batch = batches.get(key) + if (!batch) { + batch = { target, mutations: [] } + batches.set(key, batch) + } + batch.mutations.push({ groupId, updates, ownerHostId }) + } + const results = await Promise.all( + [...batches.values()].map(async ({ target, mutations }) => { + try { + const groups = await persistProjectGroupUpdates(target, mutations) + return groups.map((group, index) => ({ + group: group ? adoptFromEndpoint(target, { kind: 'projectGroup', row: group }) : null, + ownerHostId: mutations[index].ownerHostId, + groupId: mutations[index].groupId + })) + } catch (err) { + console.error('Failed to update project groups:', err) + return mutations.map(({ ownerHostId, groupId }) => ({ + group: null, + ownerHostId, + groupId + })) + } + }) + ) + const updatedById = new Map>() + let saved = true + for (const { group, groupId, ownerHostId } of results.flat()) { + if (!group) { + saved = false + continue + } + let owners = updatedById.get(groupId) + if (!owners) { + owners = new Map() + updatedById.set(groupId, owners) + } + owners.set(ownerHostId, group) + } + if (updatedById.size > 0) { + set((s) => ({ + projectGroups: s.projectGroups.map((group) => { + const owners = updatedById.get(group.id) + const hostId = getProjectGroupHostId(group) + return ( + owners?.get(hostId) ?? + (catalogOwnsHost('local', hostId) ? owners?.get('local') : undefined) ?? + owners?.get(null) ?? + group + ) + }), + folderWorkspacePathStatuses: {} + })) + } + return saved + } +} diff --git a/src/renderer/src/store/project-groups/project-group-mutations.ts b/src/renderer/src/store/project-groups/project-group-mutations.ts index a2b648bcf48..9c4ae9d3a42 100644 --- a/src/renderer/src/store/project-groups/project-group-mutations.ts +++ b/src/renderer/src/store/project-groups/project-group-mutations.ts @@ -1,7 +1,4 @@ -import { - initializeNewRootProjectGroupOrder, - persistProjectGroupUpdate -} from './project-group-update-persistence' +import { initializeNewRootProjectGroupOrder } from './project-group-update-persistence' import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { ProjectGroup } from '../../../../shared/project-group-types' @@ -101,31 +98,8 @@ export function createProjectGroupMutationActions( } }, - updateProjectGroup: async (groupId, updates, options) => { - try { - // Why: the sidebar lists groups from every host, so the mutation follows the group's owner, not the focused host. - const ownerHostId = resolveProjectGroupOwnerHostId(get(), groupId, options?.hostId) - const target = runtimeTargetForProjectGroupOwner(get(), groupId, options?.hostId) - if (!target) { - return false - } - const updated = await persistProjectGroupUpdate(target, groupId, updates) - if (!updated) { - return false - } - const ownedGroup = adoptFromEndpoint(target, { kind: 'projectGroup', row: updated }) - set((s) => ({ - projectGroups: s.projectGroups.map((group) => - projectGroupMatchesOwnerHost(group, groupId, ownerHostId) ? ownedGroup : group - ), - folderWorkspacePathStatuses: {} - })) - return true - } catch (err) { - console.error('Failed to update project group:', err) - return false - } - }, + updateProjectGroup: (groupId, updates, options) => + get().updateProjectGroups([{ groupId, updates, hostId: options?.hostId }]), deleteProjectGroup: async (groupId, options) => { try { diff --git a/src/renderer/src/store/project-groups/project-group-update-persistence.ts b/src/renderer/src/store/project-groups/project-group-update-persistence.ts index e530ce04c01..fe426e81439 100644 --- a/src/renderer/src/store/project-groups/project-group-update-persistence.ts +++ b/src/renderer/src/store/project-groups/project-group-update-persistence.ts @@ -1,11 +1,25 @@ import { getNextRootProjectOrder } from '../../../../shared/root-project-order' -import type { ProjectGroup } from '../../../../shared/project-group-types' +import type { ProjectGroup, ProjectGroupMutation } from '../../../../shared/project-group-types' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import type { RepoSlice } from '../repos/repo-state' -import { PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY } from '../../../../shared/project-group-order-capability' +import { + PROJECT_GROUP_UPDATE_MANY_RUNTIME_CAPABILITY, + PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY +} from '../../../../shared/project-group-order-capability' import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +function groupOrderMatchesUpdate( + group: ProjectGroup, + updates: ProjectGroupMutation['updates'] +): boolean { + return ( + (updates.rootProjectOrder === undefined || + (group.rootProjectOrder ?? null) === updates.rootProjectOrder) && + (updates.tabOrder === undefined || group.tabOrder === updates.tabOrder) + ) +} + export async function persistProjectGroupUpdate( target: RuntimeClientTarget, groupId: string, @@ -32,17 +46,61 @@ export async function persistProjectGroupUpdate( { timeoutMs: 15_000 } ) ).group - if ( - !updated || - (updates.rootProjectOrder !== undefined && - (updated.rootProjectOrder ?? null) !== updates.rootProjectOrder) || - (updates.tabOrder !== undefined && updated.tabOrder !== updates.tabOrder) - ) { + if (!updated || !groupOrderMatchesUpdate(updated, updates)) { return null } return updated } +export async function persistProjectGroupUpdates( + target: RuntimeClientTarget, + mutations: readonly ProjectGroupMutation[] +): Promise<(ProjectGroup | null)[]> { + if (mutations.length === 0) { + return [] + } + if ( + mutations.length === 1 || + (target.kind === 'environment' && + !(await runtimeEnvironmentSupportsCapability( + target.environmentId, + PROJECT_GROUP_UPDATE_MANY_RUNTIME_CAPABILITY + ))) + ) { + return Promise.all( + mutations.map(({ groupId, updates }) => + persistProjectGroupUpdate(target, groupId, updates).catch(() => null) + ) + ) + } + if ( + target.kind === 'environment' && + mutations.some(({ updates }) => updates.rootProjectOrder !== undefined) && + !(await runtimeEnvironmentSupportsCapability( + target.environmentId, + PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY + )) + ) { + return mutations.map(() => null) + } + const updated = + target.kind === 'local' + ? await window.api.projectGroups.updateMany({ mutations }) + : ( + await callRuntimeRpc<{ groups: ProjectGroup[] | null }>( + target, + 'projectGroup.updateMany', + { mutations }, + { timeoutMs: 15_000 } + ) + ).groups + const byId = new Map(updated?.map((group) => [group.id, group])) + return mutations.map(({ groupId, updates }) => { + const group = byId.get(groupId) + return group && groupOrderMatchesUpdate(group, updates) ? group : null + }) +} + export async function initializeNewRootProjectGroupOrder( target: RuntimeClientTarget, group: ProjectGroup, diff --git a/src/renderer/src/store/repos/create-repo-slice.ts b/src/renderer/src/store/repos/create-repo-slice.ts index a87c926a9ad..ceb5d7fe6ac 100644 --- a/src/renderer/src/store/repos/create-repo-slice.ts +++ b/src/renderer/src/store/repos/create-repo-slice.ts @@ -9,6 +9,7 @@ import { createFolderWorkspaceCatalogActions } from '../folder-workspaces/folder import { createFolderPathStatusActions } from '../folder-workspaces/folder-path-status-actions' import { createNestedRepositoryActions } from '../project-groups/nested-repository-operations' import { createProjectGroupMutationActions } from '../project-groups/project-group-mutations' +import { createProjectGroupBatchUpdateAction } from '../project-groups/project-group-batch-update' import { createFolderWorkspaceMutationActions } from '../folder-workspaces/folder-workspace-mutations' import { createRepoAddActions } from './repo-add-actions' import { createProjectHostSetupActions } from '../projects/project-host-setup-actions' @@ -73,6 +74,7 @@ export const createRepoSlice: StateCreator = (set, updateFolderWorkspace: folderWorkspaceMutations.updateFolderWorkspace, deleteFolderWorkspace: folderWorkspaceMutations.deleteFolderWorkspace, updateProjectGroup: projectGroupMutations.updateProjectGroup, + updateProjectGroups: createProjectGroupBatchUpdateAction(set, get), deleteProjectGroup: projectGroupMutations.deleteProjectGroup, deleteProjectGroupWithContainedProjects: projectGroupMutations.deleteProjectGroupWithContainedProjects, diff --git a/src/renderer/src/store/repos/repo-state.ts b/src/renderer/src/store/repos/repo-state.ts index 683001aec29..b4f327ed498 100644 --- a/src/renderer/src/store/repos/repo-state.ts +++ b/src/renderer/src/store/repos/repo-state.ts @@ -7,6 +7,7 @@ import type { NestedRepoScanResult, ProjectGroup, ProjectGroupUpdate, + ProjectGroupMutation, ProjectGroupImportResult } from '../../../../shared/project-group-types' import type { @@ -273,6 +274,9 @@ export type RepoSlice = { updates: ProjectGroupUpdate, options?: { hostId?: ExecutionHostId } ) => Promise + updateProjectGroups: ( + mutations: readonly (ProjectGroupMutation & { hostId?: ExecutionHostId })[] + ) => Promise deleteProjectGroup: (groupId: string, options?: { hostId?: ExecutionHostId }) => Promise deleteProjectGroupWithContainedProjects: ( groupId: string, diff --git a/src/shared/project-group-order-capability.ts b/src/shared/project-group-order-capability.ts index 63a2fa8df9c..ae1fe9db71f 100644 --- a/src/shared/project-group-order-capability.ts +++ b/src/shared/project-group-order-capability.ts @@ -1 +1,2 @@ export const PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY = 'projectGroup.root-project-order.v1' as const +export const PROJECT_GROUP_UPDATE_MANY_RUNTIME_CAPABILITY = 'projectGroup.update-many.v1' as const diff --git a/src/shared/project-group-types.ts b/src/shared/project-group-types.ts index 24b22b80ea3..034868f823a 100644 --- a/src/shared/project-group-types.ts +++ b/src/shared/project-group-types.ts @@ -22,6 +22,8 @@ export type ProjectGroupUpdate = Partial< Pick > & { rootProjectOrder?: number | null } +export type ProjectGroupMutation = { groupId: string; updates: ProjectGroupUpdate } + export type NestedRepoScanOptions = { maxDepth?: number maxRepos?: number diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index 3ff46af38e3..9a66b201341 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -1,4 +1,7 @@ -import { PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY } from './project-group-order-capability' +import { + PROJECT_GROUP_UPDATE_MANY_RUNTIME_CAPABILITY, + PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY +} from './project-group-order-capability' import { EMULATOR_RUNTIME_CAPABILITIES } from './emulator-runtime-capabilities' import { ACCOUNT_RUNTIME_CAPABILITIES } from './account-runtime-capabilities' import * as agentLaunchCapabilities from './agent-launch/contracts/agent-launch-runtime-capability' @@ -103,6 +106,7 @@ export const RUNTIME_CAPABILITIES = /* @__PURE__ */ (() => ...AUTOMATION_RUNTIME_CAPABILITIES, ...WORKTREE_RUNTIME_CAPABILITIES, PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY, + PROJECT_GROUP_UPDATE_MANY_RUNTIME_CAPABILITY, ...PREFLIGHT_RUNTIME_CAPABILITIES, ...WORKSPACE_PORTS_RUNTIME_CAPABILITIES, ...SESSION_TABS_RUNTIME_CAPABILITIES, diff --git a/src/shared/rpc-contract/repo-params.ts b/src/shared/rpc-contract/repo-params.ts index bb913ea2fc1..2e68770b6b7 100644 --- a/src/shared/rpc-contract/repo-params.ts +++ b/src/shared/rpc-contract/repo-params.ts @@ -81,6 +81,10 @@ export const ProjectGroupSelector = z.object({ groupId: requiredString('Missing group id') }) +export const ProjectGroupUpdateMany = z.object({ + mutations: z.array(ProjectGroupUpdate) +}) + // Why `connectionId` is optional: older clients omit it, and older hosts strip it (bare selector). export const ProjectGroupMoveProject = z.object({ repo: requiredString('Missing repo selector'), diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 605a277feb6..3ee7e258cce 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -575,6 +575,7 @@ import { ProjectGroupScanNested, ProjectGroupSelector, ProjectGroupUpdate, + ProjectGroupUpdateMany, RepoClone, RepoCreate, RepoHooksCheck, @@ -1432,6 +1433,7 @@ export const RPC_PARAMS_BY_METHOD = { 'projectGroup.moveProject': ProjectGroupMoveProject, 'projectGroup.scanNested': ProjectGroupScanNested, 'projectGroup.update': ProjectGroupUpdate, + 'projectGroup.updateMany': ProjectGroupUpdateMany, 'projectHostSetup.clone': ProjectHostSetupClone, 'projectHostSetup.create': ProjectHostSetupCreate, 'projectHostSetup.delete': ProjectHostSetupDelete,