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 1 commit
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
Next Next commit
fix(site): fix resource selection when workspace resources change
  • Loading branch information
BrunoQuaresma committed Jan 11, 2024
commit 1222a24dbbd96a57bde28f98e58cdcf4d5695afb
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";

export type WorkspaceError =
| "getBuildsError"
Expand Down Expand Up @@ -155,18 +156,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 @@ -233,8 +226,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 @@ -374,9 +367,9 @@ export const Workspace: FC<WorkspaceProps> = ({

{buildLogs}

{selectedResource && (
{resourcesNav.selected && (
<ResourceCard
resource={selectedResource}
resource={resourcesNav.selected}
agentRow={(agent) => (
<AgentRow
key={agent.id}
Expand Down
125 changes: 125 additions & 0 deletions site/src/pages/WorkspacePage/useResourcesNav.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
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 is no resource with agents
const stoppedResources: WorkspaceResource[] = [
{
...MockWorkspaceResource,
type: "docker_image",
name: "coder_image_python",
agents: [],
},
];
rerender({ resources: stoppedResources });
expect(result.current.selected).toBe(undefined);
Copy link
Member

Choose a reason for hiding this comment

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

Do you think it makes sense to add testing logic to check that the URL is syncing correctly on renders/re-renders, too?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think it is too much since we don't care too much about the URL but what the hook is returning. What use case could justify this test?

Copy link
Member

Choose a reason for hiding this comment

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

It's more for making sure that the value we're getting back isn't getting out of sync with the URL. I don't think the current implementation has any real risks of that, but the way I see the hook, it does two things:

  • Exposes the selection values
  • Fires side effects to sync the selections with the URL

And we're only testing one of those things


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

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

export const useResourcesNav = (resources: WorkspaceResource[]) => {
const resourcesNav = useTab("resources", "");
const selectedResource = resources.find(
(r) => resourceOptionId(r) === resourcesNav.value,
);

useEffect(() => {
const hasResourcesWithAgents =
resources.length > 0 &&
resources[0].agents &&
resources[0].agents.length > 0;
if (!selectedResource && hasResourcesWithAgents) {
resourcesNav.set(resourceOptionId(resources[0]));
}
}, [resources, selectedResource, resourcesNav]);
Copy link
Member

@Parkreiner Parkreiner Jan 11, 2024

Choose a reason for hiding this comment

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

Since the only cue for synchronization seems to be when selectedResource changes, could this be redefined with useEffectEvent to make sure useEffect doesn't run too often?

const syncSelectionChange = useEffectEvent((previousResource) => {
  const hasResourcesWithAgents =
    resources.length > 0 &&
    resources[0].agents &&
    resources[0].agents.length > 0;
  if (!previousResource && hasResourcesWithAgents) {
    resourcesNav.set(resourceOptionId(resources[0]));
  }
});

useEffect(() => {
  syncSelectionChange(selectedResource);
}, [syncSelectionChange, selectedResource]);

Even if resources changes by array reference, if the selected resource is still in there, I wouldn't think that should be a cause for making the effect re-run. And because the set function doesn't have memoization, it would cause the effect to run on every render

Though I think there's one more edge case: what would happen if we had a resource selected, but then the resources array becomes completely empty? Would we need to set things back to an empty string?

Copy link
Member

@Parkreiner Parkreiner Jan 11, 2024

Choose a reason for hiding this comment

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

Overall, though, I think the effect logic is what's pushing me to think that a custom hook might be justified, mainly because it's relying on URL syncs via React Router. We can't really get away with derived values or inline state syncs because we'd have to talk to an outside system during the renders

I do think there's value in abstracting over those syncs and giving you a guarantee that things will "just work". I'm just wondering if it's worth testing the hook itself, or if it's better to treat it like an implementation detail, and test the whole component

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, this would be the ideal scenario but rendering the workspace component and testing this behavior requires some server events mocking which I would like to avoid. I rather have a simple solution like this for now and only go for more complex ones if it is needed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Though I think there's one more edge case: what would happen if we had a resource selected, but then the resources array becomes completely empty? Would we need to set things back to an empty string?

Hm... I think this would not happen because when resources are returned, we can expect at least one resource. I think Coder does not allow workspace creations without a resource but if it does, I think it is not a huge concern right now.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

And because the set function doesn't have memoization, it would cause the effect to run on every render

I would not care too much about effects running on every render if it is not going to mess up with the state or cause a loop. I would rather optimize it to be ok running on every render one million times.

Copy link
Collaborator Author

@BrunoQuaresma BrunoQuaresma Jan 12, 2024

Choose a reason for hiding this comment

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

I said all of that but after some thought I think the useEffectEvent is a good use case for this as you suggested, and I appreciate you providing the code for refactoring for that ❤️


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

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

return {
isSelected,
select,
selected: selectedResource,
};
};