diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index e9938d386..aacb0a5c9 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -388,8 +388,11 @@ function App(): React.JSX.Element { useShallow((s) => ({ toggleSidebar: s.toggleSidebar, fetchRepos: s.fetchRepos, + fetchReposForAllHosts: s.fetchReposForAllHosts, fetchProjectGroups: s.fetchProjectGroups, + fetchProjectGroupsForAllHosts: s.fetchProjectGroupsForAllHosts, fetchFolderWorkspaces: s.fetchFolderWorkspaces, + fetchFolderWorkspacesForAllHosts: s.fetchFolderWorkspacesForAllHosts, fetchAllWorktrees: s.fetchAllWorktrees, fetchWorktreeLineage: s.fetchWorktreeLineage, fetchSettings: s.fetchSettings, @@ -840,9 +843,12 @@ function App(): React.JSX.Element { // Load settings first so a persisted remote runtime does not boot against // the local filesystem and then hydrate stale local workspace state. await actions.fetchSettings() - await actions.fetchRepos() - await actions.fetchProjectGroups() - await actions.fetchFolderWorkspaces() + // Why: load local + every configured runtime environment (not just the + // active one) so a cold start that restored a remote workspace doesn't + // hide local repos. The sidebar "All hosts" scope then shows them all. + await actions.fetchReposForAllHosts() + await actions.fetchProjectGroupsForAllHosts() + await actions.fetchFolderWorkspacesForAllHosts() await actions.fetchAllWorktrees() await actions.fetchWorktreeLineage() const persistedUI = await window.api.ui.get() diff --git a/src/renderer/src/app-startup-routing.test.ts b/src/renderer/src/app-startup-routing.test.ts index fa5802dbd..0320b41b7 100644 --- a/src/renderer/src/app-startup-routing.test.ts +++ b/src/renderer/src/app-startup-routing.test.ts @@ -11,7 +11,7 @@ describe('renderer startup runtime routing', () => { expect(startupBlock.indexOf('await actions.fetchSettings()')).toBeGreaterThanOrEqual(0) expect(startupBlock.indexOf('await actions.fetchSettings()')).toBeLessThan( - startupBlock.indexOf('await actions.fetchRepos()') + startupBlock.indexOf('await actions.fetchReposForAllHosts()') ) expect(startupBlock.indexOf('await actions.fetchSettings()')).toBeLessThan( startupBlock.indexOf('await actions.fetchAllWorktrees()') diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index b7b64771e..d19cea07d 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -1028,13 +1028,18 @@ export function useIpcEvents(): void { unsubs.push( window.api.repos.onChanged(() => { + const state = useAppStore.getState() if (isRuntimeEnvironmentActive()) { - // Why: this event comes from the local Electron store. While a - // runtime server is selected, repo hydration must be driven by the - // selected server instead of local-disk changes. + // Why: the all-host sidebar includes local repos even when a runtime + // is focused, so local store changes must refresh the local slice + // without dropping the runtime-owned slices already shown. + void (async () => { + await state.fetchReposForAllHosts() + await state.fetchProjectGroupsForAllHosts() + await state.fetchFolderWorkspacesForAllHosts() + })() return } - const state = useAppStore.getState() void state.fetchProjectGroups() void state.fetchFolderWorkspaces() void state.fetchRepos() diff --git a/src/renderer/src/store/slices/repos-all-hosts.test.ts b/src/renderer/src/store/slices/repos-all-hosts.test.ts new file mode 100644 index 000000000..902f808fc --- /dev/null +++ b/src/renderer/src/store/slices/repos-all-hosts.test.ts @@ -0,0 +1,270 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createTestStore } from './store-test-helpers' +import type { + FolderWorkspace, + Project, + ProjectHostSetup, + ProjectGroup, + Repo +} from '../../../../shared/types' +import { + createCompatibleRuntimeStatusResponseIfNeeded, + type RuntimeEnvironmentCallRequest +} from '../../runtime/runtime-compatibility-test-fixture' +import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' + +const localRepo: Repo = { + id: 'local-repo', + path: '/local', + displayName: 'Local', + badgeColor: '#000', + addedAt: 1 +} + +const remoteRepo: Repo = { + id: 'remote-repo', + path: '/srv/repo', + displayName: 'Remote', + badgeColor: '#000', + addedAt: 1 +} + +const localProject: Project = { + id: 'local-project', + displayName: 'Local project', + badgeColor: '#000', + sourceRepoIds: ['local-repo'], + createdAt: 1, + updatedAt: 1 +} + +const localProjectHostSetup: ProjectHostSetup = { + id: 'local-setup', + projectId: 'local-project', + hostId: 'local', + repoId: 'local-repo', + path: '/local', + displayName: 'Local setup', + setupState: 'setting-up', + setupMethod: 'imported-existing-folder', + createdAt: 1, + updatedAt: 1 +} + +const localProjectGroup: ProjectGroup = { + id: 'local-group', + name: 'Local group', + parentPath: '/local', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +const remoteProjectGroup: ProjectGroup = { + id: 'remote-group', + name: 'Remote group', + parentPath: '/srv', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +const localFolderWorkspace: FolderWorkspace = { + id: 'local-folder', + projectGroupId: 'local-group', + name: 'Local folder', + folderPath: '/local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + createdAt: 1, + updatedAt: 1 +} + +const remoteFolderWorkspace: FolderWorkspace = { + id: 'remote-folder', + projectGroupId: 'remote-group', + name: 'Remote folder', + folderPath: '/srv', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + createdAt: 1, + updatedAt: 1 +} + +const reposList = vi.fn() +const projectsList = vi.fn() +const listHostSetups = vi.fn() +const projectGroupsList = vi.fn() +const folderWorkspacesList = vi.fn() +const runtimeEnvironmentsList = vi.fn() +const runtimeEnvironmentCall = vi.fn() +const runtimeEnvironmentTransportCall = vi.fn() +const dispatchEventMock = vi.fn() + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + reposList.mockReset() + projectsList.mockReset() + listHostSetups.mockReset() + projectGroupsList.mockReset() + folderWorkspacesList.mockReset() + runtimeEnvironmentsList.mockReset() + runtimeEnvironmentCall.mockReset() + runtimeEnvironmentTransportCall.mockReset() + dispatchEventMock.mockReset() + + reposList.mockResolvedValue([localRepo]) + projectsList.mockResolvedValue([localProject]) + listHostSetups.mockResolvedValue([localProjectHostSetup]) + projectGroupsList.mockResolvedValue([localProjectGroup]) + folderWorkspacesList.mockResolvedValue([localFolderWorkspace]) + runtimeEnvironmentsList.mockResolvedValue([{ id: 'env-1', name: 'lobster' }]) + runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'repo.list') { + return { + id: 'rpc-repo-list', + ok: true, + result: { repos: [remoteRepo] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + if (args.method === 'projectGroup.list') { + return { + id: 'rpc-project-group-list', + ok: true, + result: { groups: [remoteProjectGroup] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + if (args.method === 'folderWorkspace.list') { + return { + id: 'rpc-folder-workspace-list', + ok: true, + result: { folderWorkspaces: [remoteFolderWorkspace] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + return { + id: 'rpc-other', + ok: true, + result: { projects: [], setups: [] }, + _meta: { runtimeId: 'runtime-remote' } + } + }) + runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) + }) + + vi.stubGlobal('window', { + api: { + repos: { list: reposList }, + projects: { list: projectsList, listHostSetups: listHostSetups }, + projectGroups: { list: projectGroupsList }, + folderWorkspaces: { list: folderWorkspacesList }, + runtimeEnvironments: { + call: runtimeEnvironmentTransportCall, + list: runtimeEnvironmentsList + } + }, + dispatchEvent: dispatchEventMock + }) +}) + +describe('fetchReposForAllHosts', () => { + it('loads local + all configured runtime environments even when a remote env is active', async () => { + // Why: a cold start that restored a remote workspace leaves the remote + // environment active. The active-host-only fetchRepos would drop local + // repos entirely; fetchReposForAllHosts must surface both. + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + + await store.getState().fetchReposForAllHosts() + + const ids = store + .getState() + .repos.map((repo) => repo.id) + .sort() + expect(ids).toEqual(['local-repo', 'remote-repo']) + expect(store.getState().projects).toContainEqual(localProject) + expect(store.getState().projectHostSetups).toContainEqual(localProjectHostSetup) + }) + + it('fails soft when a runtime environment is unreachable, keeping local repos', async () => { + runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'repo.list') { + throw new Error('runtime_unreachable') + } + return { + id: 'rpc-other', + ok: true, + result: { projects: [], setups: [] }, + _meta: { runtimeId: 'runtime-remote' } + } + }) + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + + await store.getState().fetchReposForAllHosts() + + expect(store.getState().repos.map((repo) => repo.id)).toEqual(['local-repo']) + }) + + it('loads project groups and folder workspaces for every host', async () => { + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + + await store.getState().fetchProjectGroupsForAllHosts() + await store.getState().fetchFolderWorkspacesForAllHosts() + + expect(store.getState().projectGroups).toEqual([ + { ...localProjectGroup, executionHostId: 'local' }, + { ...remoteProjectGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces.map((workspace) => workspace.id)).toEqual([ + 'local-folder', + 'remote-folder' + ]) + }) + + it('keeps local project groups and folder workspaces when a runtime is unreachable', async () => { + runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'projectGroup.list' || args.method === 'folderWorkspace.list') { + throw new Error('runtime_unreachable') + } + return { + id: 'rpc-other', + ok: true, + result: { repos: [], projects: [], setups: [] }, + _meta: { runtimeId: 'runtime-remote' } + } + }) + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + + await store.getState().fetchProjectGroupsForAllHosts() + await store.getState().fetchFolderWorkspacesForAllHosts() + + expect(store.getState().projectGroups).toEqual([ + { ...localProjectGroup, executionHostId: 'local' } + ]) + expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + }) +}) diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index 6b9974295..a8a55aeb6 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -417,6 +417,56 @@ function getProjectHostSetupOwnerKey(setup: ProjectHostSetup): string { return `${setup.hostId}:${setup.repoId ?? setup.id}` } +function getProjectHostIds( + project: Project, + setups: readonly ProjectHostSetup[], + repos: readonly Repo[] +): Set { + const hostIds = new Set() + const repoById = new Map(repos.map((repo) => [repo.id, repo])) + for (const setup of setups) { + if (setup.projectId === project.id) { + hostIds.add(setup.hostId) + } + } + for (const repoId of project.sourceRepoIds) { + const repo = repoById.get(repoId) + if (repo) { + hostIds.add(getRepoExecutionHostId(repo)) + } + } + if (hostIds.size === 0) { + hostIds.add(LOCAL_EXECUTION_HOST_ID) + } + return hostIds +} + +function mergeFetchedProjectCompatibilityForHost({ + previous, + fetched, + repos, + hostId +}: { + previous: Pick + fetched: Pick + repos: readonly Repo[] + hostId: string +}): Pick { + const fetchedSetupsForHost = fetched.projectHostSetups.filter((setup) => setup.hostId === hostId) + const preservedSetups = previous.projectHostSetups.filter((setup) => setup.hostId !== hostId) + const projectHostSetups = mergeById(preservedSetups, fetchedSetupsForHost) + const fetchedProjectsForHost = fetched.projects.filter((project) => + getProjectHostIds(project, fetched.projectHostSetups, repos).has(hostId) + ) + const preservedProjects = previous.projects.filter( + (project) => !getProjectHostIds(project, previous.projectHostSetups, repos).has(hostId) + ) + return { + projects: mergeById(preservedProjects, fetchedProjectsForHost), + projectHostSetups + } +} + function mergeById(base: readonly T[], overlay: readonly T[]): T[] { const merged = [...base] const indexById = new Map(merged.map((entry, index) => [entry.id, index])) @@ -458,6 +508,48 @@ function mergeFetchedReposForHost( ) } +function getProjectGroupHostId(group: Pick) { + if (group.executionHostId) { + return group.executionHostId + } + return group.connectionId ? toSshExecutionHostId(group.connectionId) : LOCAL_EXECUTION_HOST_ID +} + +function mergeFetchedProjectGroupsForHost( + previous: readonly ProjectGroup[], + fetched: ProjectGroup[], + hostId: string +): ProjectGroup[] { + const fetchedIds = new Set(fetched.map((group) => group.id)) + const preserved = previous.filter((group) => { + const existingHostId = getProjectGroupHostId(group) + return existingHostId !== hostId || fetchedIds.has(group.id) + }) + return mergeById(preserved, fetched) +} + +function mergeFetchedFolderWorkspacesForHost({ + previous, + fetched, + projectGroups, + hostId +}: { + previous: readonly FolderWorkspace[] + fetched: FolderWorkspace[] + projectGroups: readonly ProjectGroup[] + hostId: string +}): FolderWorkspace[] { + const fetchedIds = new Set(fetched.map((workspace) => workspace.id)) + const projectGroupHostIds = new Map( + projectGroups.map((group) => [group.id, getProjectGroupHostId(group)]) + ) + const preserved = previous.filter((workspace) => { + const existingHostId = projectGroupHostIds.get(workspace.projectGroupId) + return existingHostId === undefined || existingHostId !== hostId || fetchedIds.has(workspace.id) + }) + return mergeById(preserved, fetched) +} + async function fetchReposForTarget( target: ReturnType, currentRepos: readonly Repo[] @@ -492,6 +584,66 @@ async function fetchReposForTarget( return { repos: reconciledRepos, projectCompatibility, hostId } } +async function fetchProjectGroupsForTarget( + target: ReturnType, + currentProjectGroups: readonly ProjectGroup[] +): Promise<{ projectGroups: ProjectGroup[]; hostId: ReturnType }> { + const fetchedGroups = + target.kind === 'local' + ? await window.api.projectGroups.list() + : ( + await callRuntimeRpc<{ groups: ProjectGroup[] }>(target, 'projectGroup.list', undefined, { + timeoutMs: 15_000 + }) + ).groups + const hostId = getRuntimeTargetHostId(target) + const ownedGroups = fetchedGroups.map((group) => projectGroupWithFetchedOwner(group, target)) + return { + projectGroups: mergeFetchedProjectGroupsForHost(currentProjectGroups, ownedGroups, hostId), + hostId + } +} + +async function fetchFolderWorkspacesForTarget( + target: ReturnType, + currentFolderWorkspaces: readonly FolderWorkspace[], + projectGroups: readonly ProjectGroup[] +): Promise<{ + folderWorkspaces: FolderWorkspace[] + hostId: ReturnType +}> { + const fetchedFolderWorkspaces = + target.kind === 'local' + ? await window.api.folderWorkspaces.list() + : ( + await callRuntimeRpc<{ folderWorkspaces: FolderWorkspace[] }>( + target, + 'folderWorkspace.list', + undefined, + { timeoutMs: 15_000 } + ) + ).folderWorkspaces + const hostId = getRuntimeTargetHostId(target) + return { + folderWorkspaces: mergeFetchedFolderWorkspacesForHost({ + previous: currentFolderWorkspaces, + fetched: fetchedFolderWorkspaces, + projectGroups, + hostId + }), + hostId + } +} + +async function listRuntimeEnvironmentsForAllHostLoad(): Promise<{ id: string }[]> { + try { + return (await window.api.runtimeEnvironments.list()) ?? [] + } catch (err) { + console.warn('Failed to list runtime environments for all-host load:', err) + return [] + } +} + function settingsForRepoOwner(state: Pick, repoId: string) { return getSettingsForRepoRuntimeOwner(state, repoId) as AppState['settings'] } @@ -625,9 +777,12 @@ export type RepoSlice = { folderWorkspacePathStatuses: Record activeRepoId: string | null fetchRepos: () => Promise + fetchReposForAllHosts: () => Promise fetchRuntimeEnvironmentRepos: (environmentId: string) => Promise fetchProjectGroups: () => Promise + fetchProjectGroupsForAllHosts: () => Promise fetchFolderWorkspaces: () => Promise + fetchFolderWorkspacesForAllHosts: () => Promise addRepo: () => Promise addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise setupProjectExistingFolder: ( @@ -746,9 +901,18 @@ export const createRepoSlice: StateCreator = (set, } = await fetchReposForTarget(target, get().repos) set((s) => { const validRepoIds = new Set(reconciledRepos.map((repo) => repo.id)) + const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({ + previous: { + projects: s.projects, + projectHostSetups: s.projectHostSetups + }, + fetched: projectCompatibility, + repos: reconciledRepos, + hostId + }) return { repos: reconciledRepos, - ...projectCompatibility, + ...mergedProjectCompatibility, folderWorkspacePathStatuses: {}, activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), @@ -776,16 +940,27 @@ export const createRepoSlice: StateCreator = (set, hostId } = await fetchReposForTarget(target, get().repos) const validRepoIds = new Set(reconciledRepos.map((repo) => repo.id)) - set((s) => ({ - repos: reconciledRepos, - ...projectCompatibility, - activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, - filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), - setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( - s.setupScriptPromptDismissedRepoIds, - validRepoIds - ) - })) + set((s) => { + const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({ + previous: { + projects: s.projects, + projectHostSetups: s.projectHostSetups + }, + fetched: projectCompatibility, + repos: reconciledRepos, + hostId + }) + return { + repos: reconciledRepos, + ...mergedProjectCompatibility, + activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, + filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), + setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( + s.setupScriptPromptDismissedRepoIds, + validRepoIds + ) + } + }) const fetchedHostRepos = reconciledRepos.filter( (repo) => getRepoExecutionHostId(repo) === hostId ) @@ -797,24 +972,77 @@ export const createRepoSlice: StateCreator = (set, } }, + fetchReposForAllHosts: async () => { + // Why: a cold start that restores a remote workspace re-activates that + // remote runtime environment, and fetching only the active host hides every + // other host's repos (notably all local repos), which reads as "my projects + // vanished". Load local + every configured runtime environment so the + // sidebar "All hosts" scope shows them together regardless of which + // environment is active. Each host fails soft: an unreachable/disconnected + // host is skipped without blocking the others. + const applyResult = (result: Awaited>): void => { + const validRepoIds = new Set(result.repos.map((repo) => repo.id)) + set((s) => { + const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({ + previous: { + projects: s.projects, + projectHostSetups: s.projectHostSetups + }, + fetched: result.projectCompatibility, + repos: result.repos, + hostId: result.hostId + }) + return { + repos: result.repos, + ...mergedProjectCompatibility, + folderWorkspacePathStatuses: {}, + activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, + filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), + setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( + s.setupScriptPromptDismissedRepoIds, + validRepoIds + ) + } + }) + // Why: preserve the safe-auto fork sync that fetchRepos / + // fetchRuntimeEnvironmentRepos schedule after merging each host, so + // cold-start (which now routes through here) keeps updating safe-auto forks. + scheduleSafeAutoForkSync( + get, + result.repos.filter((repo) => getRepoExecutionHostId(repo) === result.hostId) + ) + } + + // Local first so local repos are present even if a remote fetch stalls. + try { + applyResult(await fetchReposForTarget({ kind: 'local' }, get().repos)) + } catch (err) { + console.error('Failed to fetch local repos for all-host load:', err) + } + + const environments = await listRuntimeEnvironmentsForAllHostLoad() + + // Sequential to avoid concurrent set() races on the merged repos array. + for (const environment of environments) { + try { + applyResult( + await fetchReposForTarget( + { kind: 'environment', environmentId: environment.id }, + get().repos + ) + ) + } catch (err) { + console.warn(`Skipped repos for runtime environment ${environment.id}:`, err) + } + } + }, + fetchProjectGroups: async () => { try { const target = getActiveRuntimeTarget(get().settings) - const projectGroups = - target.kind === 'local' - ? await window.api.projectGroups.list() - : ( - await callRuntimeRpc<{ groups: ProjectGroup[] }>( - target, - 'projectGroup.list', - undefined, - { - timeoutMs: 15_000 - } - ) - ).groups + const { projectGroups } = await fetchProjectGroupsForTarget(target, []) set({ - projectGroups: projectGroups.map((group) => projectGroupWithFetchedOwner(group, target)), + projectGroups, folderWorkspacePathStatuses: {} }) } catch (err) { @@ -822,26 +1050,91 @@ export const createRepoSlice: StateCreator = (set, } }, + fetchProjectGroupsForAllHosts: async () => { + // Why: startup renders an all-host sidebar; replacing groups with only the + // active host would leave repos from other hosts visible but ungrouped. + const applyResult = (result: Awaited>): void => { + set({ + projectGroups: result.projectGroups, + folderWorkspacePathStatuses: {} + }) + } + + try { + applyResult(await fetchProjectGroupsForTarget({ kind: 'local' }, get().projectGroups)) + } catch (err) { + console.error('Failed to fetch local project groups for all-host load:', err) + } + + const environments = await listRuntimeEnvironmentsForAllHostLoad() + for (const environment of environments) { + try { + applyResult( + await fetchProjectGroupsForTarget( + { kind: 'environment', environmentId: environment.id }, + get().projectGroups + ) + ) + } catch (err) { + console.warn(`Skipped project groups for runtime environment ${environment.id}:`, err) + } + } + }, + fetchFolderWorkspaces: async () => { try { const target = getActiveRuntimeTarget(get().settings) - const folderWorkspaces = - target.kind === 'local' - ? await window.api.folderWorkspaces.list() - : ( - await callRuntimeRpc<{ folderWorkspaces: FolderWorkspace[] }>( - target, - 'folderWorkspace.list', - undefined, - { timeoutMs: 15_000 } - ) - ).folderWorkspaces + const { folderWorkspaces } = await fetchFolderWorkspacesForTarget( + target, + [], + get().projectGroups + ) set({ folderWorkspaces, folderWorkspacePathStatuses: {} }) } catch (err) { console.error('Failed to fetch folder workspaces:', err) } }, + fetchFolderWorkspacesForAllHosts: async () => { + // Why: folder workspaces are owned through their project groups, so startup + // must fetch groups first and then merge each host's folder slice. + const applyResult = ( + result: Awaited> + ): void => { + set({ + folderWorkspaces: result.folderWorkspaces, + folderWorkspacePathStatuses: {} + }) + } + + try { + applyResult( + await fetchFolderWorkspacesForTarget( + { kind: 'local' }, + get().folderWorkspaces, + get().projectGroups + ) + ) + } catch (err) { + console.error('Failed to fetch local folder workspaces for all-host load:', err) + } + + const environments = await listRuntimeEnvironmentsForAllHostLoad() + for (const environment of environments) { + try { + applyResult( + await fetchFolderWorkspacesForTarget( + { kind: 'environment', environmentId: environment.id }, + get().folderWorkspaces, + get().projectGroups + ) + ) + } catch (err) { + console.warn(`Skipped folder workspaces for runtime environment ${environment.id}:`, err) + } + } + }, + getFolderWorkspacePathStatusCacheKey: (request, options) => `${getRuntimeTargetCachePrefix( getFolderWorkspacePathStatusRouteSettings(options, get().settings)