Improve project group ordering across hosts

This commit is contained in:
Jinjing
2026-11-09 11:28:36 -08:00
parent 58733086c9
commit 847c60600d
32 changed files with 602 additions and 154 deletions
+1
View File
@@ -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')
@@ -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,
@@ -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
@@ -138,6 +138,12 @@ export class ProjectCollectionOperations {
return getProjectGroupOperations(this).deleteProjectGroup(groupId)
}
updateProjectGroups(
mutations: Parameters<ProjectGroupPersistenceOperations['updateProjectGroups']>[0]
): ProjectGroup[] | null {
return getProjectGroupOperations(this).updateProjectGroups(mutations)
}
getFolderWorkspaces(): FolderWorkspace[] {
return getFolderWorkspaceOperations(this).getFolderWorkspaces()
}
@@ -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)
})
})
@@ -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 {
@@ -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']
@@ -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<ProjectGroup[] | null> {
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,
@@ -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),
@@ -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',
+1
View File
@@ -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),
+4
View File
@@ -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<ProjectGroup>
update: (args: { groupId: string; updates: ProjectGroupUpdate }) => Promise<ProjectGroup | null>
updateMany: (args: {
mutations: readonly ProjectGroupMutation[]
}) => Promise<ProjectGroup[] | null>
delete: (args: { groupId: string }) => Promise<boolean>
moveProject: (args: {
projectId: string
@@ -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 [
@@ -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<string>()
@@ -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<string, number> {
const counts = new Map<string, number>()
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[],
@@ -32,6 +32,49 @@ function repo(id: string, overrides: Partial<Repo> = {}): 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<Repo> }) => ({ ...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' }
@@ -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<RepoSlice, 'repos' | 'projectGroups' | 'updateRepo' | 'updateProjectGroup'>
state: Pick<RepoSlice, 'repos' | 'projectGroups' | 'updateRepo' | 'updateProjectGroups'>
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<boolean>; restore: () => Promise<boolean> }[] = []
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({
@@ -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<string, ExecutionHostId | null>()
@@ -259,11 +266,15 @@ export function useWorktreeSidebarHeaderDrag(args: {
)
const rootProjectHeaderSectionEndByKey = useMemo(
() => getRootProjectHeaderSectionEndByKey(renderRows, firstHeaderIndex),
[renderRows, firstHeaderIndex]
() =>
hasProjectGroups
? getRootProjectHeaderSectionEndByKey(renderRows, firstHeaderIndex)
: new Map<string, number>(),
[hasProjectGroups, renderRows, firstHeaderIndex]
)
return {
rootProjectHeaderCountByOccurrenceKey,
rootProjectHeaderSectionEndByKey,
canReorderRepoHeaders,
canReorderProjectGroupHeaders,
@@ -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 &&
@@ -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(
<TooltipProvider>
{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()
})}
</TooltipProvider>
)
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('')
})
@@ -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: {
@@ -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])
})
@@ -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<string, number> {
const rowStarts = getEstimatedRenderRowStarts(args.rows, args.firstHeaderIndex)
const sectionEndByGroupId = new Map<string, number>()
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<string, number>()
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])
}
@@ -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<StateCreator<AppState>>[0],
get: Parameters<StateCreator<AppState>>[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<string, Map<string | null, ProjectGroup>>()
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
}
}
@@ -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 {
@@ -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,
@@ -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<AppState, [], [], RepoSlice> = (set,
updateFolderWorkspace: folderWorkspaceMutations.updateFolderWorkspace,
deleteFolderWorkspace: folderWorkspaceMutations.deleteFolderWorkspace,
updateProjectGroup: projectGroupMutations.updateProjectGroup,
updateProjectGroups: createProjectGroupBatchUpdateAction(set, get),
deleteProjectGroup: projectGroupMutations.deleteProjectGroup,
deleteProjectGroupWithContainedProjects:
projectGroupMutations.deleteProjectGroupWithContainedProjects,
@@ -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<boolean>
updateProjectGroups: (
mutations: readonly (ProjectGroupMutation & { hostId?: ExecutionHostId })[]
) => Promise<boolean>
deleteProjectGroup: (groupId: string, options?: { hostId?: ExecutionHostId }) => Promise<boolean>
deleteProjectGroupWithContainedProjects: (
groupId: string,
@@ -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
+2
View File
@@ -22,6 +22,8 @@ export type ProjectGroupUpdate = Partial<
Pick<ProjectGroup, 'name' | 'isCollapsed' | 'tabOrder' | 'color'>
> & { rootProjectOrder?: number | null }
export type ProjectGroupMutation = { groupId: string; updates: ProjectGroupUpdate }
export type NestedRepoScanOptions = {
maxDepth?: number
maxRepos?: number
+5 -1
View File
@@ -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,
+4
View File
@@ -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'),
+2
View File
@@ -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,