Skip to content

fix(site): fix resource selection when workspace resources change #11581

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions site/src/pages/WorkspacePage/ResourcesSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import { getResourceIconPath } from "utils/workspace";
type ResourcesSidebarProps = {
failed: boolean;
resources: WorkspaceResource[];
onChange: (resourceId: string) => void;
selected: string;
onChange: (resource: WorkspaceResource) => void;
isSelected: (resource: WorkspaceResource) => boolean;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the isSelected change is an improvement, but I'm wondering if the implementation is getting a little too tied to how useResourcesNav is set up.

What do you think of turning isSelected into just a boolean, and making the parent component call the function to get the right prop to pass in?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to know what is the selected resource and since this is not just an attribute but a "calculation", I think this interface makes things easier to extend.

};

export const ResourcesSidebar = (props: ResourcesSidebarProps) => {
const theme = useTheme();
const { failed, onChange, selected, resources } = props;
const { failed, onChange, isSelected, resources } = props;

return (
<Sidebar>
Expand Down Expand Up @@ -46,8 +46,8 @@ export const ResourcesSidebar = (props: ResourcesSidebarProps) => {
))}
{resources.map((r) => (
<SidebarItem
onClick={() => onChange(r.id)}
isActive={r.id === selected}
onClick={() => onChange(r)}
isActive={isSelected(r)}
key={r.id}
css={styles.root}
>
Expand Down
19 changes: 6 additions & 13 deletions site/src/pages/WorkspacePage/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { SidebarIconButton } from "components/FullPageLayout/Sidebar";
import HubOutlined from "@mui/icons-material/HubOutlined";
import { ResourcesSidebar } from "./ResourcesSidebar";
import { ResourceCard } from "components/Resources/ResourceCard";
import { useResourcesNav } from "./useResourcesNav";
import { MemoizedInlineMarkdown } from "components/Markdown/Markdown";

export type WorkspaceError =
Expand Down Expand Up @@ -158,18 +159,10 @@ export const Workspace: FC<WorkspaceProps> = ({
}
};

const selectedResourceId = useTab("resources", "");
const resources = [...workspace.latest_build.resources].sort(
(a, b) => countAgents(b) - countAgents(a),
);
const selectedResource = workspace.latest_build.resources.find(
(r) => r.id === selectedResourceId.value,
);
useEffect(() => {
if (resources.length > 0 && selectedResourceId.value === "") {
selectedResourceId.set(resources[0].id);
}
}, [resources, selectedResourceId]);
const resourcesNav = useResourcesNav(resources);

return (
<div
Expand Down Expand Up @@ -237,8 +230,8 @@ export const Workspace: FC<WorkspaceProps> = ({
<ResourcesSidebar
failed={workspace.latest_build.status === "failed"}
resources={resources}
selected={selectedResourceId.value}
onChange={selectedResourceId.set}
isSelected={resourcesNav.isSelected}
onChange={resourcesNav.select}
/>
)}
{sidebarOption.value === "history" && (
Expand Down Expand Up @@ -384,9 +377,9 @@ export const Workspace: FC<WorkspaceProps> = ({

{buildLogs}

{selectedResource && (
{resourcesNav.selected && (
<ResourceCard
resource={selectedResource}
resource={resourcesNav.selected}
agentRow={(agent) => (
<AgentRow
key={agent.id}
Expand Down
132 changes: 132 additions & 0 deletions site/src/pages/WorkspacePage/useResourcesNav.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { renderHook } from "@testing-library/react";
import { resourceOptionId, useResourcesNav } from "./useResourcesNav";
import { WorkspaceResource } from "api/typesGenerated";
import { MockWorkspaceResource } from "testHelpers/entities";
import { RouterProvider, createMemoryRouter } from "react-router-dom";

describe("useResourcesNav", () => {
it("selects the first resource if it has agents and no resource is selected", () => {
const resources: WorkspaceResource[] = [
MockWorkspaceResource,
{
...MockWorkspaceResource,
agents: [],
},
];
const { result } = renderHook(() => useResourcesNav(resources), {
wrapper: ({ children }) => (
<RouterProvider
router={createMemoryRouter([{ path: "/", element: children }])}
/>
),
});
expect(result.current.selected?.id).toBe(MockWorkspaceResource.id);
});

it("selects the first resource if it has agents and selected resource is not find", async () => {
const resources: WorkspaceResource[] = [
MockWorkspaceResource,
{
...MockWorkspaceResource,
agents: [],
},
];
const { result } = renderHook(() => useResourcesNav(resources), {
wrapper: ({ children }) => (
<RouterProvider
router={createMemoryRouter([{ path: "/", element: children }], {
initialEntries: ["/?resources=not_found_resource_id"],
})}
/>
),
});
expect(result.current.selected?.id).toBe(MockWorkspaceResource.id);
});

it("selects the resource passed in the URL", () => {
const resources: WorkspaceResource[] = [
{
...MockWorkspaceResource,
type: "docker_container",
name: "coder_python",
},
{
...MockWorkspaceResource,
type: "docker_container",
name: "coder_java",
},
{
...MockWorkspaceResource,
type: "docker_image",
name: "coder_image_python",
agents: [],
},
];
const { result } = renderHook(() => useResourcesNav(resources), {
wrapper: ({ children }) => (
<RouterProvider
router={createMemoryRouter([{ path: "/", element: children }], {
initialEntries: [`/?resources=${resourceOptionId(resources[1])}`],
})}
/>
),
});
expect(result.current.selected?.id).toBe(resources[1].id);
});

it("selects a resource when resources are updated", () => {
const startedResources: WorkspaceResource[] = [
{
...MockWorkspaceResource,
type: "docker_container",
name: "coder_python",
},
{
...MockWorkspaceResource,
type: "docker_container",
name: "coder_java",
},
{
...MockWorkspaceResource,
type: "docker_image",
name: "coder_image_python",
agents: [],
},
];
const { result, rerender } = renderHook(
({ resources }) => useResourcesNav(resources),
{
wrapper: ({ children }) => (
<RouterProvider
router={createMemoryRouter([{ path: "/", element: children }])}
/>
),
initialProps: { resources: startedResources },
},
);
expect(result.current.selected?.id).toBe(startedResources[0].id);

// When a workspace is stopped, there are no resources with agents, so we
// need to retain the currently selected resource. This ensures consistency
// when handling workspace updates that involve a sequence of stopping and
// starting. By preserving the resource selection, we maintain the desired
// configuration and prevent unintended changes during the stop-and-start
// process.
const stoppedResources: WorkspaceResource[] = [
{
...MockWorkspaceResource,
type: "docker_image",
name: "coder_image_python",
agents: [],
},
];
rerender({ resources: stoppedResources });
expect(result.current.selectedValue).toBe(
resourceOptionId(startedResources[0]),
);

// When a workspace is started again a resource is selected
rerender({ resources: startedResources });
expect(result.current.selected?.id).toBe(startedResources[0].id);
});
});
55 changes: 55 additions & 0 deletions site/src/pages/WorkspacePage/useResourcesNav.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { WorkspaceResource } from "api/typesGenerated";
import { useTab } from "hooks";
import { useEffectEvent } from "hooks/hookPolyfills";
import { useCallback, useEffect } from "react";

export const resourceOptionId = (resource: WorkspaceResource) => {
return `${resource.type}_${resource.name}`;
};

// TODO: This currently serves as a temporary workaround for synchronizing the
// resources tab during workspace transitions. The optimal resolution involves
// eliminating the sync and updating the URL within the workspace data update
// event in the WebSocket "onData" event. However, this requires substantial
// refactoring. Consider revisiting this solution in the future for a more
// robust implementation.
export const useResourcesNav = (resources: WorkspaceResource[]) => {
const resourcesNav = useTab("resources", "");

const isSelected = useCallback(
(resource: WorkspaceResource) => {
return resourceOptionId(resource) === resourcesNav.value;
},
[resourcesNav.value],
);

const selectedResource = resources.find(isSelected);
const onSelectedResourceChange = useEffectEvent(
(previousResource?: WorkspaceResource) => {
const hasResourcesWithAgents =
resources.length > 0 &&
resources[0].agents &&
resources[0].agents.length > 0;
if (!previousResource && hasResourcesWithAgents) {
resourcesNav.set(resourceOptionId(resources[0]));
}
},
);
useEffect(() => {
onSelectedResourceChange(selectedResource);
}, [onSelectedResourceChange, selectedResource]);

const select = useCallback(
(resource: WorkspaceResource) => {
resourcesNav.set(resourceOptionId(resource));
},
[resourcesNav],
);

return {
isSelected,
select,
selected: selectedResource,
selectedValue: resourcesNav.value,
};
};