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
@@ -1,6 +1,7 @@
export {
type DestroyWorkspaceError,
type DestroyWorkspaceInput,
type DestroyWorkspacePreview,
type DestroyWorkspaceSuccess,
type UseDestroyWorkspace,
useDestroyWorkspace,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import type { TeardownFailureCause } from "@superset/host-service";
import type {
DeleteInProgressCause,
TeardownFailureCause,
} from "@superset/host-service";
import { TRPCClientError } from "@trpc/client";
import { useCallback } from "react";
import { getHostServiceClientByUrl } from "renderer/lib/host-service-client";
import { useWorkspaceHostUrl } from "../useWorkspaceHostUrl";
import {
useWorkspaceHostTarget,
type WorkspaceHostTarget,
} from "../useWorkspaceHostUrl";

export interface DestroyWorkspaceInput {
deleteBranch?: boolean;
Expand All @@ -17,65 +23,118 @@ export interface DestroyWorkspaceSuccess {
warnings: string[];
}

/**
* Mirrors the server's `InspectResult` discriminated union so the renderer
* can't accidentally treat `{ canDelete: false, reason: null }` as a no-op
* — that combination is unrepresentable.
*/
export type DestroyWorkspacePreview =
| {
canDelete: true;
reason: null;
hasChanges: boolean;
hasUnpushedCommits: boolean;
}
| {
canDelete: false;
reason: string;
hasChanges: false;
hasUnpushedCommits: false;
};

export type DestroyWorkspaceError =
| { kind: "conflict"; message: string }
| { kind: "in-progress"; message: string }
| { kind: "teardown-failed"; cause: TeardownFailureCause }
| { kind: "host-unavailable"; reason: WorkspaceHostTarget["status"] }
| { kind: "unknown"; message: string };

export interface UseDestroyWorkspace {
hostTarget: WorkspaceHostTarget;
destroy: (input?: DestroyWorkspaceInput) => Promise<DestroyWorkspaceSuccess>;
inspect: () => Promise<DestroyWorkspacePreview>;
}

/**
* Calls `workspaceCleanup.destroy` on the workspace's owning host-service.
* Translates TRPC errors into a typed discriminated union so callers can
* prompt for `force: true` on conflict or teardown failure.
*
* Throws a DestroyWorkspaceError (not a TRPCClientError) for easier handling.
* Calls `workspaceCleanup.{inspect,destroy}` on the workspace's owning
* host-service. Translates TRPC errors into a typed discriminated union
* so callers can:
* - silently retry with `force: true` on `conflict` (dirty-worktree race)
* - surface a toast on `in-progress` (concurrent destroy) — must NOT retry
* - prompt force-retry on `teardown-failed`
* - render `host-unavailable` as a checking-status spinner, not an error
*/
export function useDestroyWorkspace(workspaceId: string): UseDestroyWorkspace {
const hostUrl = useWorkspaceHostUrl(workspaceId);
const hostTarget = useWorkspaceHostTarget(workspaceId);

// Reduce the (object-identity-unstable) hostTarget down to two scalars so
// memoized callbacks below don't churn on every collection notification.
// useLiveQuery returns a new array each tick, which would otherwise rebuild
// `inspect`/`destroy` and re-fire effects that depend on them.
const hostUrl = hostTarget.status === "ready" ? hostTarget.url : null;
const hostStatus = hostTarget.status;

const destroy = useCallback(
async (
input: DestroyWorkspaceInput = {},
): Promise<DestroyWorkspaceSuccess> => {
if (!hostUrl) {
throw {
kind: "unknown",
message: "Host unavailable",
} satisfies DestroyWorkspaceError;
}

const client = getHostServiceClientByUrl(hostUrl);
const client = getReadyClient(hostUrl, hostStatus);
try {
const result = await client.workspaceCleanup.destroy.mutate({
return await client.workspaceCleanup.destroy.mutate({
workspaceId,
deleteBranch: input.deleteBranch ?? false,
force: input.force ?? false,
});
return result;
} catch (err) {
throw normalizeError(err);
}
},
[hostUrl, workspaceId],
[hostUrl, hostStatus, workspaceId],
);

return { destroy };
const inspect = useCallback(async (): Promise<DestroyWorkspacePreview> => {
const client = getReadyClient(hostUrl, hostStatus);
try {
return await client.workspaceCleanup.inspect.query({ workspaceId });
} catch (err) {
throw normalizeError(err);
}
}, [hostUrl, hostStatus, workspaceId]);

return { hostTarget, destroy, inspect };
}

function getReadyClient(
hostUrl: string | null,
hostStatus: WorkspaceHostTarget["status"],
) {
if (hostUrl == null) {
throw {
kind: "host-unavailable",
reason: hostStatus,
} satisfies DestroyWorkspaceError;
}
return getHostServiceClientByUrl(hostUrl);
}

function normalizeError(err: unknown): DestroyWorkspaceError {
if (isDestroyWorkspaceError(err)) return err;
if (err instanceof TRPCClientError) {
const code = err.data?.code as string | undefined;
const teardownFailure = (
err.data as { teardownFailure?: TeardownFailureCause }
)?.teardownFailure;
const data = err.data as
| {
code?: string;
teardownFailure?: TeardownFailureCause;
deleteInProgress?: DeleteInProgressCause;
}
| undefined;

if (teardownFailure) {
return { kind: "teardown-failed", cause: teardownFailure };
if (data?.teardownFailure) {
return { kind: "teardown-failed", cause: data.teardownFailure };
}
if (data?.deleteInProgress) {
return { kind: "in-progress", message: err.message };
}
if (code === "CONFLICT") {
if (data?.code === "CONFLICT") {
return { kind: "conflict", message: err.message };
}
return { kind: "unknown", message: err.message };
Expand All @@ -85,3 +144,12 @@ function normalizeError(err: unknown): DestroyWorkspaceError {
message: err instanceof Error ? err.message : String(err),
};
}

function isDestroyWorkspaceError(err: unknown): err is DestroyWorkspaceError {
return (
!!err &&
typeof err === "object" &&
"kind" in err &&
typeof (err as { kind: unknown }).kind === "string"
);
}
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export { useWorkspaceHostUrl } from "./useWorkspaceHostUrl";
export {
useWorkspaceHostTarget,
useWorkspaceHostUrl,
type WorkspaceHostTarget,
} from "./useWorkspaceHostUrl";
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ import { env } from "renderer/env.renderer";
import { useCollections } from "renderer/routes/_authenticated/providers/CollectionsProvider";
import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider";

export type WorkspaceHostTarget =
| { status: "loading" }
| { status: "not-found" }
| { status: "local-starting"; hostId: string }
| { status: "ready"; kind: "local" | "remote"; hostId: string; url: string };

/**
* Resolves a workspace ID to its host-service URL.
* Local host → localhost port. Remote host → relay proxy URL.
* Resolves a workspace ID to its owning host-service target.
*
* The status union lets callers distinguish "still loading the collection"
* from "local host hasn't booted yet" from "workspace doesn't exist on this
* client" — three states the previous `string | null` API collapsed into one.
*/
export function useWorkspaceHostUrl(workspaceId: string | null): string | null {
export function useWorkspaceHostTarget(
workspaceId: string | null,
): WorkspaceHostTarget {
const collections = useCollections();
const { machineId, activeHostUrl } = useLocalHostService();

const { data: workspaceRows = [] } = useLiveQuery(
const { data: workspaceRows = [], isReady } = useLiveQuery(
(q) =>
q
.from({ workspaces: collections.v2Workspaces })
Expand All @@ -29,9 +40,34 @@ export function useWorkspaceHostUrl(workspaceId: string | null): string | null {
const match = workspaceId ? (workspaceRows[0] ?? null) : null;

return useMemo(() => {
if (!match) return null;
if (match.hostId === machineId) return activeHostUrl;
if (!workspaceId || !isReady) return { status: "loading" };
if (!match) return { status: "not-found" };
if (machineId && match.hostId === machineId) {
if (activeHostUrl) {
return {
status: "ready",
kind: "local",
hostId: match.hostId,
url: activeHostUrl,
};
}
return { status: "local-starting", hostId: match.hostId };
}
const routingKey = buildHostRoutingKey(match.organizationId, match.hostId);
return `${env.RELAY_URL}/hosts/${routingKey}`;
}, [match, machineId, activeHostUrl]);
return {
status: "ready",
kind: "remote",
hostId: match.hostId,
url: `${env.RELAY_URL}/hosts/${routingKey}`,
};
}, [workspaceId, isReady, match, machineId, activeHostUrl]);
}

/**
* Backwards-compatible URL-only form for existing callers. Returns null
* for any non-`ready` status (loading, local-starting, not-found).
*/
export function useWorkspaceHostUrl(workspaceId: string | null): string | null {
const target = useWorkspaceHostTarget(workspaceId);
return target.status === "ready" ? target.url : null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export function DashboardSidebarDeleteDialog({
setDeleteBranch,
hasChanges,
hasUnpushedCommits,
canConfirm,
blockingReason,
isCheckingStatus,
error,
handleOpenChange,
Expand All @@ -53,6 +55,11 @@ export function DashboardSidebarDeleteDialog({
}

const hasWarnings = hasChanges || hasUnpushedCommits;
const confirmLabel = isCheckingStatus
? "Checking…"
: hasWarnings
? "Delete anyway"
: "Delete";

return (
<DestroyConfirmPane
Expand All @@ -63,8 +70,11 @@ export function DashboardSidebarDeleteDialog({
onDeleteBranchChange={setDeleteBranch}
hasChanges={hasChanges}
hasUnpushedCommits={hasUnpushedCommits}
canConfirm={canConfirm}
blockingReason={blockingReason}
isCheckingStatus={isCheckingStatus}
onConfirm={() => run(hasWarnings)}
confirmLabel={confirmLabel}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ interface DestroyConfirmPaneProps {
onDeleteBranchChange: (next: boolean) => void;
hasChanges: boolean;
hasUnpushedCommits: boolean;
canConfirm: boolean;
blockingReason: string | null;
isCheckingStatus: boolean;
onConfirm: () => void;
confirmLabel: string;
}

export function DestroyConfirmPane({
Expand All @@ -31,8 +34,11 @@ export function DestroyConfirmPane({
onDeleteBranchChange,
hasChanges,
hasUnpushedCommits,
canConfirm,
blockingReason,
isCheckingStatus,
onConfirm,
confirmLabel,
}: DestroyConfirmPaneProps) {
const checkboxId = useId();
const hasWarnings = hasChanges || hasUnpushedCommits;
Expand All @@ -59,6 +65,13 @@ export function DestroyConfirmPane({
</div>
</div>
)}
{blockingReason && (
<div className="px-4 pb-2">
<div className="text-xs text-destructive bg-destructive/10 border border-destructive/20 rounded-md px-2.5 py-1.5">
{blockingReason}
</div>
</div>
)}
<div className="px-4 pb-2">
<div className="flex items-center gap-2">
<Checkbox
Expand Down Expand Up @@ -90,9 +103,9 @@ export function DestroyConfirmPane({
size="sm"
className="h-7 px-3 text-xs"
onClick={onConfirm}
disabled={isCheckingStatus}
disabled={isCheckingStatus || !canConfirm}
>
Delete
{confirmLabel}
</Button>
Comment thread
Kitenite marked this conversation as resolved.
</AlertDialogFooter>
</AlertDialogContent>
Expand Down
Loading
Loading