Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,18 @@ import {
} from "@tanstack/react-router";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
import { useSyncExternalStore } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

import { act, render, type Screen } from "../../../test/render";
import { act, render, stubGlobal, type Screen } from "../../../test/render";
import type { Project } from "../../types";

type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
const state = vi.hoisted(() => ({
sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
projects: [] as Project[],
projectListeners: new Set<() => void>(),
update:
vi.fn<
(request: {
Expand Down Expand Up @@ -76,7 +78,14 @@ vi.mock(import("~/state/environments"), async (original) => ({
}));
vi.mock(import("~/state/entities"), async (original) => ({
...(await original()),
useProjects: (() => state.projects) as never,
useProjects: (() =>
useSyncExternalStore(
(listener) => {
state.projectListeners.add(listener);
return () => state.projectListeners.delete(listener);
},
() => state.projects,
)) as never,
useThreadShells: () => [],
useServerConfigs: (() =>
new Map(
Expand Down Expand Up @@ -208,6 +217,7 @@ function setup() {
? { ...project, ...patch }
: project,
);
for (const listener of state.projectListeners) listener();
return AsyncResult.success(undefined);
});
state.delete.mockResolvedValue(AsyncResult.success(undefined));
Expand Down Expand Up @@ -236,13 +246,16 @@ async function mountPanel(search: Omit<SettingsScopeSearch, "project"> = {}) {
const projectsRoute = createRoute({
getParentRoute: () => settingsRoute,
path: "projects",
component: () => (
<ProjectSettingsPanel
projectKey={key}
environmentId={search.machine ? EnvironmentId.make(search.machine) : null}
checkoutKey={search.checkout ?? null}
/>
),
component: function ProjectsRoute() {
const current: SettingsScopeSearch = settingsRoute.useSearch();
return (
<ProjectSettingsPanel
projectKey={current.project ?? key}
environmentId={current.machine ? EnvironmentId.make(current.machine) : null}
checkoutKey={current.checkout ?? null}
/>
);
},
});
const query = new URLSearchParams({ project: key });
for (const [name, value] of Object.entries(search)) {
Expand Down Expand Up @@ -613,6 +626,59 @@ describe("project settings scope", () => {
});
});

describe("project location", () => {
const changeLocation = () => page.getByRole("button", { name: "Change…" });
// Background connection code also reads the bridge once it exists.
const stubPicker = (pickFolder: () => Promise<string | null>) =>
stubGlobal("desktopBridge", {
pickFolder,
getLocalEnvironmentEnabled: () => true,
getLocalEnvironmentBootstraps: () => [],
});

it("follows the checkout to its new location", async () => {
setup();
using _bridge = stubPicker(async () => "/work/moved");
await using screen = await mountPanel({
machine: primaryId,
checkout: "primary:/work/primary",
});

await userEvent.click(changeLocation());

expect(state.update).toHaveBeenCalledWith({
environmentId: primaryId,
input: { projectId: ProjectId.make("project-primary"), workspaceRoot: "/work/moved" },
});
await vi.waitFor(() =>
expect(screen.router.state.location.search).toMatchObject({
checkout: "primary:/work/moved",
}),
);
await expect.element(page.getByText("/work/moved", { exact: true })).toBeVisible();
});

it("reports a picker failure instead of treating it as a cancel", async () => {
setup();
using _bridge = stubPicker(async () => {
throw new Error("dialog unavailable");
});
await using _screen = await mountPanel({
machine: primaryId,
checkout: "primary:/work/primary",
});

await userEvent.click(changeLocation());

await vi.waitFor(() =>
expect(state.toast).toHaveBeenCalledWith(
expect.objectContaining({ type: "error", title: "Failed to change project location" }),
),
);
expect(state.update).not.toHaveBeenCalled();
});
});

it("returns to the project overview after removal, clearing the selection but keeping the environment", async () => {
setup();
state.projects = [state.projects[1]!];
Expand Down
62 changes: 51 additions & 11 deletions apps/web/src/components/settings/ProjectSettingsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ interface ProjectSelection {
readonly memberKeys: ReadonlyArray<string>;
}

const projectMemberRef = (member: SidebarProjectGroupMember) =>
`${member.environmentId}:${member.id}`;

function sameProjectSelection(a: ProjectSelection | null, b: ProjectSelection): boolean {
return (
a !== null &&
Expand Down Expand Up @@ -103,37 +106,35 @@ export function ProjectSettingsPanel({
(checkoutKey === null || member.physicalProjectKey === checkoutKey),
) ?? [];

// Retain group members so grouping-rule changes can follow the project to its new group.
// Retain group members by id so grouping-rule changes and moves can follow the project.
const [lastSelection, setLastSelection] = useState<ProjectSelection | null>(null);
if (selected && members.length > 0) {
const current: ProjectSelection = {
key: selected.projectKey,
environmentId,
checkoutKey,
memberKeys: members.map((member) => member.physicalProjectKey),
memberKeys: members.map(projectMemberRef),
};
if (!sameProjectSelection(lastSelection, current)) setLastSelection(current);
}

const successor =
const successorMember =
members.length === 0 &&
lastSelection?.key === projectKey &&
lastSelection.environmentId === environmentId &&
lastSelection.checkoutKey === checkoutKey
? groups.find((group) =>
group.memberProjects.some((member) =>
lastSelection.memberKeys.includes(member.physicalProjectKey),
),
)
? groups
.flatMap((group) => group.memberProjects.map((member) => ({ group, member })))
.find(({ member }) => lastSelection.memberKeys.includes(projectMemberRef(member)))
: undefined;
if (successor) {
if (successorMember) {
return (
<Navigate
to={pathname}
search={{
project: successor.projectKey,
project: successorMember.group.projectKey,
machine: environmentId ?? undefined,
checkout: checkoutKey ?? undefined,
checkout: checkoutKey === null ? undefined : successorMember.member.physicalProjectKey,
}}
replace
hashScrollIntoView={false}
Expand Down Expand Up @@ -215,6 +216,12 @@ function ProjectDetail({
)
? window.desktopBridge?.pickProjectFavicon
: undefined;
const pickProjectLocation =
typeof window !== "undefined" &&
representative.environmentId === primaryEnvironmentId &&
canPickExternalProjectFavicon(representative.workspaceRoot, navigator.platform)
? window.desktopBridge?.pickFolder
: undefined;
Comment thread
yordis marked this conversation as resolved.
Resolved

const { updateProjectGroup, canOrganizeProjectGroup } = useProjectGroupUpdate();
const updateAllMembers = (
Expand Down Expand Up @@ -262,6 +269,26 @@ function ProjectDetail({
setIsSavingFavicon(false);
};

const [isChangingLocation, setIsChangingLocation] = useState(false);
const changeLocation = async () => {
if (!pickProjectLocation) return;
setIsChangingLocation(true);
const picked = await pickProjectLocation({
initialPath: representative.workspaceRoot,
}).catch((error: unknown) => {
toastManager.add({
type: "error",
title: "Failed to change project location",
description: error instanceof Error ? error.message : undefined,
});
return null;
});
if (picked && picked !== representative.workspaceRoot) {
await updateAllMembers({ workspaceRoot: picked }, "Failed to change project location");
Comment thread
yordis marked this conversation as resolved.
Resolved
}
setIsChangingLocation(false);
};

const hasMultipleCheckouts = group.memberProjects.length > 1;
const canResetScratchTitle =
group.memberProjects.every((member) => member.isScratch) &&
Expand Down Expand Up @@ -475,6 +502,19 @@ function ProjectDetail({
description={
<span className="select-text break-all">{representative.workspaceRoot}</span>
}
control={
pickProjectLocation ? (
<Button
size="sm"
variant="outline"
type="button"
disabled={isChangingLocation || !canEditGroup}
onClick={() => void changeLocation()}
>
Change…
</Button>
) : undefined
}
/>
)}
<SettingsRow
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/hooks/useProjectGroupUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useOrchestrationCommand } from "../state/use-orchestration-command";

export type ProjectGroupUpdate = Partial<{
title: string;
workspaceRoot: string;
faviconPath: string | null;
projectIcon: ProjectIconOverride | null;
pinned: boolean;
Expand Down
Loading