Skip to content
TypeScript

fix(mobile): add project and checkout removal (#21409)

maria0dc38c75f570
diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
index 1838c32e985..7d5ae81eb8c 100644
--- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
@@ -2,16 +2,38 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll
import { AppText as Text, AppTextInput } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { ProjectFavicon } from "../../components/ProjectFavicon";
+import * as Dialog from "../../components/ui/Dialog";
+import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
+import { planProjectRemoval } from "@t3tools/client-runtime/state/projects";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
-import { useState } from "react";
-import { Platform, View } from "react-native";
+import { useNavigation } from "@react-navigation/native";
+import { useEffect, useRef, useState } from "react";
+import { Platform, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { projectEnvironment } from "../../state/projects";
+import { useThreadShells } from "../../state/entities";
+import { appAtomRegistry } from "../../state/atom-registry";
+import {
+ clearComposerDraft,
+ composerDraftsAtom,
+ findNewTaskDraftKeys,
+ waitForComposerDraftsLoaded,
+} from "../../state/use-composer-drafts";
+import {
+ readEnvironmentScope,
+ useEnvironmentScope,
+ useEnvironmentsWithScope,
+} from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsScreen } from "./components/SettingsScreen";
import { SettingsSection } from "./components/SettingsSection";
+import { SettingsActionRow } from "./components/SettingsActionRow";
import {
AndroidSettingsEnvironmentFilter,
SettingsEnvironmentFilterHeader,
@@ -20,7 +42,31 @@ import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-en
export function SettingsProjectOverviewRouteScreen() {
const insets = useSafeAreaInsets();
- const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
+ const [isRemoving, setIsRemoving] = useState(false);
+ const removalPending = useRef(false);
+ const startRemoval = () => {
+ if (removalPending.current) return false;
+ removalPending.current = true;
+ return true;
+ };
+ const finishRemoval = () => {
+ removalPending.current = false;
+ setIsRemoving(false);
+ };
+ const navigation = useNavigation();
+ const { selectedTargets, projectGroups, selectedProjectKey, selectProject } =
+ useSettingsEnvironmentFilter();
+ const latestProjectKey = useRef(selectedProjectKey);
+ useEffect(() => {
+ latestProjectKey.current = selectedProjectKey;
+ }, [selectedProjectKey]);
+ // The filter can move to another project while a removal is still running.
+ const finishProjectRemoval = (projectKey: string | null) => {
+ if (latestProjectKey.current !== projectKey) return;
+ if (navigation.isFocused()) navigation.goBack();
+ // Otherwise the filter keeps pointing at the removed project as an unavailable one.
+ selectProject(null);
+ };
const group = projectGroups.find((entry) => entry.key === selectedProjectKey);
const selectedEnvironmentIds = new Set(selectedTargets.map((entry) => entry.environmentId));
const members =
@@ -49,6 +95,13 @@ export function SettingsProjectOverviewRouteScreen() {
key={`${selectedProjectKey}:${members.map((member) => member.id).join(",")}`}
members={members}
environments={selectedTargets}
+ hasOtherMembers={members.length < (group?.members.length ?? 0)}
+ isRemoving={isRemoving}
+ setIsRemoving={setIsRemoving}
+ startRemoval={startRemoval}
+ finishRemoval={finishRemoval}
+ projectKey={selectedProjectKey}
+ onProjectRemoved={finishProjectRemoval}
/>
)}
</ScrollView>
@@ -60,11 +113,28 @@ export function SettingsProjectOverviewRouteScreen() {
function ProjectOverviewContent(props: {
readonly members: readonly EnvironmentProject[];
readonly environments: readonly SettingsTarget[];
+ readonly hasOtherMembers: boolean;
+ readonly isRemoving: boolean;
+ readonly setIsRemoving: (isRemoving: boolean) => void;
+ readonly startRemoval: () => boolean;
+ readonly finishRemoval: () => void;
+ readonly projectKey: string | null;
+ readonly onProjectRemoved: (projectKey: string | null) => void;
}) {
+ const { isRemoving, setIsRemoving, startRemoval, finishRemoval } = props;
const representative = props.members[0]!;
const displayName = deriveProjectGroupLabel({ representative, members: props.members });
const [draftName, setDraftName] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
+ const threads = useThreadShells();
+ const removableEnvironments = useEnvironmentsWithScope(
+ props.members,
+ AuthOrchestrationOperateScope,
+ );
+ const canRemoveGroup = props.members.every((member) =>
+ removableEnvironments.has(member.environmentId),
+ );
+ const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
const updateProject = useAtomCommand(projectEnvironment.update, {
label: "project name update",
reportFailure: true,
@@ -72,6 +142,85 @@ function ProjectOverviewContent(props: {
const nextName = (draftName ?? displayName).trim();
const canSave = !isSaving && nextName.length > 0 && nextName !== displayName;
+ const checkRemovalAccess = (members: readonly EnvironmentProject[]) => {
+ const denied = members.find(
+ (member) => !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
+ );
+ if (!denied) return true;
+ const environment = props.environments.find(
+ (entry) => entry.environmentId === denied.environmentId,
+ );
+ Dialog.alert(
+ "Failed to remove project",
+ `This connection cannot change projects in ${environment?.label ?? "this environment"}.`,
+ );
+ return false;
+ };
+
+ const removeMembers = (members: readonly EnvironmentProject[]) => {
+ if (!checkRemovalAccess(members) || !startRemoval()) return;
+ const projectKey = props.projectKey;
+ const plan = planProjectRemoval({
+ members: members.map((member) => ({
+ ...member,
+ environmentLabel: props.environments.find(
+ (entry) => entry.environmentId === member.environmentId,
+ )?.label,
+ })),
+ groupMemberCount: props.members.length,
+ hasOtherMembers: props.hasOtherMembers,
+ displayName,
+ threads,
+ });
+ Dialog.confirm({
+ title: plan.targetKind === "checkout" ? "Remove checkout" : "Remove project",
+ message: plan.confirmationMessage,
+ confirmText: plan.targetKind === "checkout" ? "Remove checkout" : "Remove project",
+ destructive: true,
+ onCancel: finishRemoval,
+ onConfirm: () => {
+ void (async () => {
+ setIsRemoving(true);
+ if (!checkRemovalAccess(members)) return;
+ for (const member of members) {
+ if (!checkRemovalAccess([member])) return;
+ const result = await deleteProject({
+ environmentId: member.environmentId,
+ input: { projectId: member.id, force: true },
+ });
+ if (result._tag === "Failure") {
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(
+ `Failed to remove "${member.title}"`,
+ error instanceof Error ? error.message : "An error occurred.",
+ );
+ }
+ return;
+ }
+ await waitForComposerDraftsLoaded()
+ .then(() => {
+ for (const draftKey of findNewTaskDraftKeys(
+ appAtomRegistry.get(composerDraftsAtom),
+ {
+ environmentId: member.environmentId,
+ projectId: member.id,
+ },
+ )) {
+ clearComposerDraft(draftKey);
+ }
+ })
+ .catch((error) => {
+ console.warn("[project-removal] could not clear composer drafts", error);
+ });
+ }
+ // Nothing is left to show once the whole project is gone.
+ if (plan.targetKind === "project") props.onProjectRemoved(projectKey);
+ })().finally(finishRemoval);
+ },
+ });
+ };
+
const saveName = () => {
if (!canSave) return;
setIsSaving(true);
@@ -162,10 +311,59 @@ function ProjectOverviewContent(props: {
<Text className="text-sm leading-normal text-foreground-muted" selectable>
{member.workspaceRoot}
</Text>
+ {props.members.length > 1 || props.hasOtherMembers ? (
+ <RemoveCheckoutAction
+ member={member}
+ disabled={isRemoving}
+ onPress={() => removeMembers([member])}
+ />
+ ) : null}
</View>
);
})}
</SettingsSection>
+ <SettingsSection title="Danger">
+ <SettingsActionRow
+ icon="trash"
+ label={
+ props.hasOtherMembers
+ ? "Remove checkout"
+ : props.members.length > 1
+ ? "Remove this project everywhere"
+ : "Remove project"
+ }
+ description={
+ props.hasOtherMembers
+ ? "Deletes the selected machine's checkout entries and their threads. Other machines and files on disk are not touched."
+ : props.members.length > 1
+ ? `Deletes all ${props.members.length} checkout entries and their threads on every machine. Files on disk are not touched.`
+ : "Deletes the project entry and its threads. Files on disk are not touched."
+ }
+ tone="danger"
+ disabled={!canRemoveGroup || isRemoving}
+ loading={isRemoving}
+ onPress={() => removeMembers(props.members)}
+ />
+ </SettingsSection>
</>
);
}
+
+function RemoveCheckoutAction(props: {
+ readonly member: EnvironmentProject;
+ readonly disabled: boolean;
+ readonly onPress: () => void;
+}) {
+ const canRemove = useEnvironmentScope(props.member.environmentId, AuthOrchestrationOperateScope);
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Remove checkout ${props.member.workspaceRoot}`}
+ disabled={props.disabled || !canRemove}
+ onPress={props.onPress}
+ className="self-start rounded-full border border-border bg-card px-3 py-1.5 disabled:opacity-40"
+ >
+ <Text className="font-t3-medium text-xs text-danger-foreground">Remove checkout</Text>
+ </Pressable>
+ );
+}
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts
index 8a72b3510ce..3d3e1673c01 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { planProjectRemoval } from "@t3tools/client-runtime/state/projects";
import { projectGroupTitleNeedsUpdate } from "./ProjectSettingsPanel.logic";
@@ -21,3 +23,68 @@ describe("projectGroupTitleNeedsUpdate", () => {
);
});
});
+
+describe("project removal confirmation", () => {
+ const local = {
+ id: ProjectId.make("shared-id"),
+ environmentId: EnvironmentId.make("local"),
+ title: "Repo",
+ workspaceRoot: "/work/repo",
+ environmentLabel: "Local",
+ };
+ const remote = {
+ ...local,
+ environmentId: EnvironmentId.make("remote"),
+ environmentLabel: "Remote",
+ };
+
+ it("limits a checkout's thread count to its environment and project", () => {
+ const plan = planProjectRemoval({
+ members: [local],
+ groupMemberCount: 2,
+ hasOtherMembers: false,
+ displayName: "Repo",
+ threads: [
+ { environmentId: local.environmentId, projectId: local.id },
+ { environmentId: remote.environmentId, projectId: remote.id },
+ ],
+ });
+ expect(plan.projectThreads).toHaveLength(1);
+ expect(plan.confirmationMessage).toBe(
+ 'Remove checkout "Repo" and delete its 1 thread?\nPath: /work/repo\nEnvironment: Local\nThis permanently clears conversation history for those threads and any archived threads.\nOther entries in this grouped project are unaffected.\nThis action cannot be undone.',
+ );
+ });
+
+ it("keeps an environment-filtered group scoped to its selected checkout", () => {
+ const plan = planProjectRemoval({
+ members: [remote],
+ groupMemberCount: 1,
+ hasOtherMembers: true,
+ displayName: "Repo",
+ threads: [],
+ });
+ expect(plan.targetKind).toBe("checkout");
+ expect(plan.confirmationMessage).toContain("Environment: Remote");
+ expect(plan.confirmationMessage).toContain(
+ "Other entries in this grouped project are unaffected.",
+ );
+ expect(plan.confirmationMessage).toContain(
+ "This permanently clears any archived conversation history.",
+ );
+ });
+
+ it("states the full group count and preserves files when removing a project everywhere", () => {
+ const plan = planProjectRemoval({
+ members: [local, remote],
+ groupMemberCount: 2,
+ hasOtherMembers: false,
+ displayName: "Repo",
+ threads: [],
+ });
+ expect(plan.targetKind).toBe("project");
+ expect(plan.confirmationMessage).toContain("This removes 2 grouped project entries.");
+ expect(plan.confirmationMessage).toContain(
+ "This removes only the project entries, not the files on disk.",
+ );
+ });
+});
diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
index b9a2919786e..48b8ee6c348 100644
--- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx
@@ -10,6 +10,7 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { planProjectRemoval } from "@t3tools/client-runtime/state/projects";
import { AsyncResult } from "effect/reactivity";
import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
import { useLocation, useNavigate } from "@tanstack/react-router";
@@ -55,10 +56,6 @@ const ProjectIconPickerDialog = lazy(() =>
})),
);
-function memberKey(member: { environmentId: string; id: string }): string {
- return `${member.environmentId}:${member.id}`;
-}
-
export type ProjectSettingsCategory = "general" | "source-control" | "project";
export function ProjectSettingsPanel({
@@ -319,40 +316,15 @@ function ProjectDetail({
const api = readLocalApi();
if (!api) return;
- const memberKeys = new Set(members.map(memberKey));
- const projectThreads = threads.filter((thread) =>
- memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
- );
- const isWholeGroup = members.length === group.memberProjects.length;
- const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project";
- const singleMember = members.length === 1 ? members[0]! : null;
- const targetLabel = singleMember?.title ?? group.displayName;
+ const { projectThreads, isWholeGroup, confirmationMessage } = planProjectRemoval({
+ members,
+ groupMemberCount: group.memberProjects.length,
+ hasOtherMembers,
+ displayName: group.displayName,
+ threads,
+ });
const confirmed = await settlePromise(() =>
- api.dialogs.confirm(
- [
- projectThreads.length > 0
- ? `Remove ${targetKind} "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
- : `Remove ${targetKind} "${targetLabel}"?`,
- ...(singleMember
- ? [
- `Path: ${singleMember.workspaceRoot}`,
- ...(singleMember.environmentLabel
- ? [`Environment: ${singleMember.environmentLabel}`]
- : []),
- ]
- : [`This removes ${members.length} grouped project entries.`]),
- ...(projectThreads.length > 0
- ? [
- "This permanently clears conversation history for those threads and any archived threads.",
- ]
- : ["This permanently clears any archived conversation history."]),
- isWholeGroup && !hasOtherMembers
- ? "This removes only the project entries, not the files on disk."
- : "Other entries in this grouped project are unaffected.",
- "This action cannot be undone.",
- ].join("\n"),
- { variant: "destructive" },
- ),
+ api.dialogs.confirm(confirmationMessage, { variant: "destructive" }),
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
if (checkProjectAccess(members, "Failed to remove project")) return;
diff --git a/packages/client-runtime/src/state/projectRemoval.ts b/packages/client-runtime/src/state/projectRemoval.ts
new file mode 100644
index 00000000000..55e1df25739
--- /dev/null
+++ b/packages/client-runtime/src/state/projectRemoval.ts
@@ -0,0 +1,47 @@
+import type { EnvironmentProject, EnvironmentThreadShell } from "./models.ts";
+
+export function planProjectRemoval<
+ Thread extends Pick<EnvironmentThreadShell, "environmentId" | "projectId">,
+>(options: {
+ readonly members: ReadonlyArray<
+ Pick<EnvironmentProject, "id" | "environmentId" | "title" | "workspaceRoot"> & {
+ readonly environmentLabel?: string | null;
+ }
+ >;
+ readonly groupMemberCount: number;
+ readonly hasOtherMembers: boolean;
+ readonly displayName: string;
+ readonly threads: ReadonlyArray<Thread>;
+}) {
+ const { members, groupMemberCount, hasOtherMembers, displayName, threads } = options;
+ const memberKeys = new Set(members.map((member) => `${member.environmentId}:${member.id}`));
+ const projectThreads = threads.filter((thread) =>
+ memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
+ );
+ const isWholeGroup = members.length === groupMemberCount;
+ const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project";
+ const singleMember = members.length === 1 ? members[0]! : null;
+ const targetLabel = singleMember?.title ?? displayName;
+ const confirmationMessage = [
+ projectThreads.length > 0
+ ? `Remove ${targetKind} "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
+ : `Remove ${targetKind} "${targetLabel}"?`,
+ ...(singleMember
+ ? [
+ `Path: ${singleMember.workspaceRoot}`,
+ ...(singleMember.environmentLabel
+ ? [`Environment: ${singleMember.environmentLabel}`]
+ : []),
+ ]
+ : [`This removes ${members.length} grouped project entries.`]),
+ ...(projectThreads.length > 0
+ ? ["This permanently clears conversation history for those threads and any archived threads."]
+ : ["This permanently clears any archived conversation history."]),
+ isWholeGroup && !hasOtherMembers
+ ? "This removes only the project entries, not the files on disk."
+ : "Other entries in this grouped project are unaffected.",
+ "This action cannot be undone.",
+ ].join("\n");
+
+ return { projectThreads, isWholeGroup, targetKind, confirmationMessage };
+}
diff --git a/packages/client-runtime/src/state/projects.ts b/packages/client-runtime/src/state/projects.ts
index 6268519ea5c..49d0de4bc22 100644
--- a/packages/client-runtime/src/state/projects.ts
+++ b/packages/client-runtime/src/state/projects.ts
@@ -205,3 +205,4 @@ export function canNavigateUp(currentPath: string): boolean {
export * from "./projectCommands.ts";
export * from "./projectEntities.ts";
+export * from "./projectRemoval.ts";