Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): pick a cloud environment or image, and star a favorite (#91224)

Shy Alteredec912c713a
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index 116d28c5d3f5..52a8e5f0e05f 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -34,7 +34,9 @@ import {
type AgentAdapter,
useSettingsStore,
} from "../../settings/settingsStore";
+import { cloudTargetIds } from "../../task-detail/cloudTargets";
import { WorkspaceModeSelect } from "../../task-detail/components/WorkspaceModeSelect";
+import { useCloudTargetSelection } from "../../task-detail/hooks/useCloudTarget";
import { usePreviewConfig } from "../../task-detail/hooks/usePreviewConfig";
import { useResolvedWorkspaceMode } from "../../task-detail/hooks/useResolvedWorkspaceMode";
import { useTaskCreation } from "../../task-detail/hooks/useTaskCreation";
@@ -152,12 +154,8 @@ export const ChannelHomeComposer = forwardRef<
isLoadingIntegrations,
allowWorktree: false,
});
- const [selectedCloudEnvId, setSelectedCloudEnvId] = useState<string | null>(
- null,
- );
- const [selectedCustomImageId, setSelectedCustomImageId] = useState<
- string | null
- >(null);
+ const { cloudTarget, setCloudTarget } = useCloudTargetSelection();
+ const cloudIds = workspaceMode === "cloud" ? cloudTargetIds(cloudTarget) : {};
const [repositoryDialogOpen, setRepositoryDialogOpen] = useState(false);
const repositoryDraft = useTaskRepositoryDraftStore(
(s) => s.drafts[channelId],
@@ -255,14 +253,8 @@ export const ChannelHomeComposer = forwardRef<
? (taskGithubIntegration ?? undefined)
: undefined,
workspaceMode,
- sandboxEnvironmentId:
- workspaceMode === "cloud" && selectedCloudEnvId
- ? selectedCloudEnvId
- : undefined,
- customImageId:
- workspaceMode === "cloud" && selectedCustomImageId
- ? selectedCustomImageId
- : undefined,
+ sandboxEnvironmentId: cloudIds.sandboxEnvironmentId,
+ customImageId: cloudIds.customImageId,
editorIsEmpty,
adapter,
runtime,
@@ -396,10 +388,8 @@ export const ChannelHomeComposer = forwardRef<
onChange={setWorkspaceMode}
adapter={runtime === "pi" ? undefined : adapter}
overrideModes={["local", "cloud"]}
- selectedCloudEnvironmentId={selectedCloudEnvId}
- onCloudEnvironmentChange={setSelectedCloudEnvId}
- selectedCustomImageId={selectedCustomImageId}
- onCustomImageChange={setSelectedCustomImageId}
+ cloudTarget={cloudTarget}
+ onCloudTargetChange={setCloudTarget}
size="1"
disabled={isBusy}
/>
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index 1e60c1360576..d8a917dc0c37 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -146,6 +146,7 @@ interface SettingsStore {
lastUsedContextWindow: "200k" | "1m" | null;
lastUsedFastMode: boolean | null;
lastUsedCloudRepository: string | null;
+ favoriteCloudTargetKey: string | null;
cachedCloudRepositoryMap: Record<string, UserRepositoryIntegrationRef>;
// Last-known default ("trunk") branch per cloud repo, keyed by lowercased
// "owner/repo". Persisted so a cold start can pre-select trunk in the branch
@@ -173,6 +174,7 @@ interface SettingsStore {
setLastUsedContextWindow: (value: "200k" | "1m") => void;
setLastUsedFastMode: (enabled: boolean) => void;
setLastUsedCloudRepository: (repo: string | null) => void;
+ setFavoriteCloudTargetKey: (key: string | null) => void;
setCachedCloudRepositoryMap: (
map: Record<string, UserRepositoryIntegrationRef>,
) => void;
@@ -372,6 +374,7 @@ export const useSettingsStore = create<SettingsStore>()(
lastUsedContextWindow: null,
lastUsedFastMode: null,
lastUsedCloudRepository: null,
+ favoriteCloudTargetKey: null,
cachedCloudRepositoryMap: {},
cachedCloudDefaultBranchMap: {},
lastUsedEnvironments: {},
@@ -398,6 +401,7 @@ export const useSettingsStore = create<SettingsStore>()(
setLastUsedFastMode: (enabled) => set({ lastUsedFastMode: enabled }),
setLastUsedCloudRepository: (repo) =>
set({ lastUsedCloudRepository: repo }),
+ setFavoriteCloudTargetKey: (key) => set({ favoriteCloudTargetKey: key }),
setCachedCloudRepositoryMap: (map) =>
set({ cachedCloudRepositoryMap: map }),
setCachedCloudDefaultBranch: (repo, branch) =>
diff --git a/products/desktop/packages/ui/src/features/task-detail/cloudTargets.test.ts b/products/desktop/packages/ui/src/features/task-detail/cloudTargets.test.ts
new file mode 100644
index 000000000000..5f6c11fe86b0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/cloudTargets.test.ts
@@ -0,0 +1,118 @@
+import type {
+ SandboxCustomImage,
+ SandboxEnvironment,
+} from "@posthog/shared/domain-types";
+import { describe, expect, it } from "vitest";
+import {
+ buildCloudTargetOptions,
+ type CloudTarget,
+ cloudTargetFromKey,
+ cloudTargetIds,
+ cloudTargetKey,
+ moveFavoriteFirst,
+ resolveCloudTarget,
+} from "./cloudTargets";
+
+const env = (overrides: Partial<SandboxEnvironment>): SandboxEnvironment =>
+ ({
+ id: "env-1",
+ name: "Internal APIs",
+ network_access_level: "custom",
+ allowed_domains: ["github.com"],
+ custom_image_id: null,
+ ...overrides,
+ }) as SandboxEnvironment;
+
+const image = (overrides: Partial<SandboxCustomImage>): SandboxCustomImage =>
+ ({
+ id: "image-1",
+ name: "posthog stack",
+ status: "ready",
+ version: 279,
+ ...overrides,
+ }) as SandboxCustomImage;
+
+describe("cloudTargets", () => {
+ it("offers an image that no environment starts from", () => {
+ const options = buildCloudTargetOptions({
+ environments: [env({})],
+ images: [image({})],
+ imagesEnabled: true,
+ });
+
+ expect(options.map((option) => option.key)).toEqual([
+ "default",
+ "environment:env-1",
+ "image:image-1",
+ ]);
+ });
+
+ it.each([
+ [
+ "attached to an environment",
+ {
+ environments: [env({ custom_image_id: "image-1" })],
+ images: [image({})],
+ imagesEnabled: true,
+ },
+ ],
+ [
+ "not ready",
+ {
+ environments: [env({})],
+ images: [image({ status: "building" })],
+ imagesEnabled: true,
+ },
+ ],
+ [
+ "images are off",
+ {
+ environments: [env({})],
+ images: [image({})],
+ imagesEnabled: false,
+ },
+ ],
+ ])("hides an image that is %s", (_case, input) => {
+ const options = buildCloudTargetOptions(input);
+
+ expect(options.some((option) => option.key === "image:image-1")).toBe(
+ false,
+ );
+ });
+
+ it.each([
+ [{ kind: "default" }, {}],
+ [{ kind: "environment", id: "env-1" }, { sandboxEnvironmentId: "env-1" }],
+ [{ kind: "image", id: "image-1" }, { customImageId: "image-1" }],
+ ] as [CloudTarget, ReturnType<typeof cloudTargetIds>][])(
+ "sends %o as %o",
+ (target, ids) => {
+ expect(cloudTargetIds(target)).toEqual(ids);
+ expect(cloudTargetFromKey(cloudTargetKey(target))).toEqual(target);
+ },
+ );
+
+ it("puts the favorite first", () => {
+ const options = buildCloudTargetOptions({
+ environments: [env({})],
+ images: [image({})],
+ imagesEnabled: true,
+ });
+
+ expect(
+ moveFavoriteFirst(options, "image:image-1").map((option) => option.key),
+ ).toEqual(["image:image-1", "default", "environment:env-1"]);
+ });
+
+ it("falls back to the default when the favorite is gone", () => {
+ const options = buildCloudTargetOptions({
+ environments: [],
+ images: [],
+ imagesEnabled: true,
+ });
+
+ expect(
+ resolveCloudTarget({ kind: "image", id: "image-1" }, options),
+ ).toEqual({ kind: "default" });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/task-detail/cloudTargets.ts b/products/desktop/packages/ui/src/features/task-detail/cloudTargets.ts
new file mode 100644
index 000000000000..061e4ec40c67
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/cloudTargets.ts
@@ -0,0 +1,111 @@
+import type {
+ SandboxCustomImage,
+ SandboxEnvironment,
+} from "@posthog/shared/domain-types";
+
+export type CloudTarget =
+ | { kind: "default" }
+ | { kind: "environment"; id: string }
+ | { kind: "image"; id: string };
+
+export const DEFAULT_CLOUD_TARGET: CloudTarget = { kind: "default" };
+
+export interface CloudTargetOption {
+ key: string;
+ target: CloudTarget;
+ name: string;
+ description: string;
+}
+
+export function cloudTargetKey(target: CloudTarget): string {
+ return target.kind === "default" ? "default" : `${target.kind}:${target.id}`;
+}
+
+export function cloudTargetFromKey(key: string | null): CloudTarget | null {
+ if (!key) return null;
+ if (key === "default") return DEFAULT_CLOUD_TARGET;
+ const [kind, id] = key.split(":");
+ if (!id) return null;
+ if (kind === "environment") return { kind: "environment", id };
+ if (kind === "image") return { kind: "image", id };
+ return null;
+}
+
+export function cloudTargetIds(target: CloudTarget): {
+ sandboxEnvironmentId?: string;
+ customImageId?: string;
+} {
+ if (target.kind === "environment") return { sandboxEnvironmentId: target.id };
+ if (target.kind === "image") return { customImageId: target.id };
+ return {};
+}
+
+function environmentDescription(environment: SandboxEnvironment): string {
+ if (environment.network_access_level === "full") return "Full network access";
+ if (environment.network_access_level === "trusted") {
+ return "Trusted sources only";
+ }
+ const count = environment.allowed_domains.length;
+ return `${count} allowed domain${count === 1 ? "" : "s"}`;
+}
+
+export function buildCloudTargetOptions({
+ environments,
+ images,
+ imagesEnabled,
+}: {
+ environments: readonly SandboxEnvironment[];
+ images: readonly SandboxCustomImage[];
+ imagesEnabled: boolean;
+}): CloudTargetOption[] {
+ const attachedImageIds = new Set(
+ environments.flatMap((environment) =>
+ environment.custom_image_id ? [environment.custom_image_id] : [],
+ ),
+ );
+ const standaloneImages = imagesEnabled
+ ? images.filter(
+ (image) => image.status === "ready" && !attachedImageIds.has(image.id),
+ )
+ : [];
+
+ return [
+ {
+ key: "default",
+ target: DEFAULT_CLOUD_TARGET,
+ name: "Default",
+ description: "Full network access",
+ },
+ ...environments.map((environment) => ({
+ key: cloudTargetKey({ kind: "environment", id: environment.id }),
+ target: { kind: "environment" as const, id: environment.id },
+ name: environment.name,
+ description: environmentDescription(environment),
+ })),
+ ...standaloneImages.map((image) => ({
+ key: cloudTargetKey({ kind: "image", id: image.id }),
+ target: { kind: "image" as const, id: image.id },
+ name: image.name,
+ description: `Image v${image.version}, full network access`,
+ })),
+ ];
+}
+
+export function resolveCloudTarget(
+ favorite: CloudTarget | null,
+ options: readonly CloudTargetOption[],
+): CloudTarget {
+ if (!favorite) return DEFAULT_CLOUD_TARGET;
+ return options.some((option) => option.key === cloudTargetKey(favorite))
+ ? favorite
+ : DEFAULT_CLOUD_TARGET;
+}
+
+export function moveFavoriteFirst(
+ options: readonly CloudTargetOption[],
+ favoriteKey: string | null,
+): CloudTargetOption[] {
+ const favorite = options.find((option) => option.key === favoriteKey);
+ if (!favorite) return [...options];
+ return [favorite, ...options.filter((option) => option !== favorite)];
+}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index 93fb14675ca7..a2cc2e3a6382 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -108,6 +108,8 @@ import {
useSettingsStore,
} from "../../settings/settingsStore";
import { useSkills } from "../../skills/useSkills";
+import { cloudTargetIds } from "../cloudTargets";
+import { useCloudTargetSelection } from "../hooks/useCloudTarget";
import {
areReposReady,
useInitialRepoSelectionFromFolderId,
@@ -341,12 +343,7 @@ export function TaskInput({
const [selectedEnvironment, setSelectedEnvironmentRaw] = useState<
string | null
>(null);
- const [selectedCloudEnvId, setSelectedCloudEnvId] = useState<string | null>(
- null,
- );
- const [selectedCustomImageId, setSelectedCustomImageId] = useState<
- string | null
- >(null);
+ const { cloudTarget, setCloudTarget } = useCloudTargetSelection();
const [activeReportAssociation, setActiveReportAssociation] = useState(
reportAssociation ?? null,
);
@@ -800,6 +797,7 @@ export function TaskInput({
}
const effectiveWorkspaceMode = workspaceMode;
+ const cloudIds = workspaceMode === "cloud" ? cloudTargetIds(cloudTarget) : {};
const repoOptional = !!allowNoRepo && workspaceMode === "cloud";
@@ -880,8 +878,8 @@ export function TaskInput({
runtimeAdapter: adapter ?? null,
model: effectiveModel,
reasoningEffort: effectiveReasoningLevel,
- sandboxEnvironmentId: workspaceMode === "cloud" ? selectedCloudEnvId : null,
- customImageId: workspaceMode === "cloud" ? selectedCustomImageId : null,
+ sandboxEnvironmentId: cloudIds.sandboxEnvironmentId ?? null,
+ customImageId: cloudIds.customImageId ?? null,
});
const branchForTaskCreation =
@@ -1020,14 +1018,8 @@ export function TaskInput({
onTaskCreated,
onTaskCreatedEffect: handleTaskCreatedEffect,
environmentId: selectedEnvironment,
- sandboxEnvironmentId:
- effectiveWorkspaceMode === "cloud" && selectedCloudEnvId
- ? selectedCloudEnvId
- : undefined,
- customImageId:
- effectiveWorkspaceMode === "cloud" && selectedCustomImageId
- ? selectedCustomImageId
- : undefined,
+ sandboxEnvironmentId: cloudIds.sandboxEnvironmentId,
+ customImageId: cloudIds.customImageId,
signalReportId: activeReportAssociation?.reportId,
channelContext: includeChannelContext ? channelContext : undefined,
channelContextPath: includeChannelContext ? channelContextPath : undefined,
@@ -1304,10 +1296,8 @@ export function TaskInput({
value={workspaceMode}
onChange={setWorkspaceMode}
adapter={runtime === "pi" ? undefined : adapter}
- selectedCloudEnvironmentId={selectedCloudEnvId}
- onCloudEnvironmentChange={setSelectedCloudEnvId}
- selectedCustomImageId={selectedCustomImageId}
- onCustomImageChange={setSelectedCustomImageId}
+ cloudTarget={cloudTarget}
+ onCloudTargetChange={setCloudTarget}
size="1"
/>
{repoOptional && (
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
index 0fe7ebb2749d..70670052217c 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
@@ -1,19 +1,21 @@
import {
ArrowsSplit,
Cloud,
- Cube,
Gear,
Laptop,
Plus,
+ Star,
} from "@phosphor-icons/react";
import {
Button,
+ cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
+ ItemActions,
ItemContent,
ItemDescription,
ItemMedia,
@@ -29,9 +31,13 @@ import {
} from "@posthog/ui/features/settings/useCodexSubscription";
import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
import { useCallback, useMemo, useState } from "react";
-import { useSandboxCustomImages } from "../../settings/sections/environments/useSandboxCustomImages";
-import { useSandboxEnvironments } from "../../settings/sections/environments/useSandboxEnvironments";
+import {
+ type CloudTarget,
+ cloudTargetKey,
+ DEFAULT_CLOUD_TARGET,
+} from "../cloudTargets";
import { useCloudModeEnabled } from "../hooks/useCloudModeEnabled";
+import { useCloudTargetOptions } from "../hooks/useCloudTarget";
export type { WorkspaceMode };
@@ -42,10 +48,8 @@ interface WorkspaceModeSelectProps {
disabled?: boolean;
overrideModes?: WorkspaceMode[];
adapter?: Adapter;
- selectedCloudEnvironmentId?: string | null;
- onCloudEnvironmentChange?: (envId: string | null) => void;
- selectedCustomImageId?: string | null;
- onCustomImageChange?: (imageId: string | null) => void;
+ cloudTarget?: CloudTarget;
+ onCloudTargetChange?: (target: CloudTarget) => void;
}
const LOCAL_MODES: {
@@ -70,30 +74,25 @@ const LOCAL_MODES: {
const CLOUD_ICON = <Cloud size={14} weight="regular" />;
+const ICON_BUTTON_CLASS =
+ "flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground";
+
export function WorkspaceModeSelect({
value,
onChange,
disabled,
overrideModes,
adapter,
- selectedCloudEnvironmentId,
- onCloudEnvironmentChange,
- selectedCustomImageId,
- onCustomImageChange,
+ cloudTarget = DEFAULT_CLOUD_TARGET,
+ onCloudTargetChange,
}: WorkspaceModeSelectProps) {
const { localWorkspaces } = useHostCapabilities();
const cloudModeEnabled = useCloudModeEnabled();
const codexSubscription = useCodexSubscription();
- const { environments } = useSandboxEnvironments();
- const { images, customImagesEnabled } = useSandboxCustomImages();
+ const { options, favoriteKey, toggleFavorite } = useCloudTargetOptions();
const [menuOpen, setMenuOpen] = useState(false);
- const readyImages = useMemo(
- () => images.filter((image) => image.status === "ready"),
- [images],
- );
-
const handleAddEnvironment = useCallback(() => {
setMenuOpen(false);
openSettings("cloud-environments", "create");
@@ -114,24 +113,18 @@ export function WorkspaceModeSelect({
[overrideModes, localWorkspaces],
);
- const selectedEnvName = useMemo(() => {
- if (value !== "cloud" || !selectedCloudEnvironmentId) return null;
- return environments.find((e) => e.id === selectedCloudEnvironmentId)?.name;
- }, [value, selectedCloudEnvironmentId, environments]);
-
- const selectedImageName = useMemo(() => {
- if (value !== "cloud" || !selectedCustomImageId) return null;
- return images.find((img) => img.id === selectedCustomImageId)?.name;
- }, [value, selectedCustomImageId, images]);
+ const selectedTargetName = useMemo(() => {
+ if (value !== "cloud" || cloudTarget.kind === "default") return null;
+ const key = cloudTargetKey(cloudTarget);
+ return options.find((option) => option.key === key)?.name ?? null;
+ }, [value, cloudTarget, options]);
const triggerLabel = useMemo(() => {
if (value === "cloud") {
- return ["Cloud", selectedEnvName, selectedImageName]
- .filter(Boolean)
- .join(" · ");
+ return ["Cloud", selectedTargetName].filter(Boolean).join(" · ");
}
return LOCAL_MODES.find((m) => m.mode === value)?.label ?? "Worktree";
- }, [value, selectedEnvName, selectedImageName]);
+ }, [value, selectedTargetName]);
const triggerIcon = useMemo(() => {
if (value === "cloud") return CLOUD_ICON;
@@ -183,7 +176,7 @@ export function WorkspaceModeSelect({
openSettings("harness");
}}
aria-label="Subscription settings"
- className="flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground"
+ className={ICON_BUTTON_CLASS}
>
<Gear size={12} />
</button>
@@ -196,11 +189,7 @@ export function WorkspaceModeSelect({
{localModes.map((item) => (
<DropdownMenuItem
key={item.mode}
- onClick={() => {
- onChange(item.mode);
- onCloudEnvironmentChange?.(null);
- onCustomImageChange?.(null);
- }}
+ onClick={() => onChange(item.mode)}
render={
<ItemMenuItem size="xs" className="w-full">
<ItemMedia variant="icon" className="mt-2 ml-2">
@@ -218,11 +207,11 @@ export function WorkspaceModeSelect({
))}
</DropdownMenuGroup>
- {showCloud && environments.length === 0 && (
+ {showCloud && options.length === 1 && (
<DropdownMenuItem
onClick={() => {
onChange("cloud");
- onCloudEnvironmentChange?.(null);
+ onCloudTargetChange?.(DEFAULT_CLOUD_TARGET);
}}
render={
<ItemMenuItem size="xs" className="w-full">
@@ -240,7 +229,7 @@ export function WorkspaceModeSelect({
/>
)}
- {showCloud && environments.length > 0 && (
+ {showCloud && options.length > 1 && (
<>
<DropdownMenuSeparator />
<div className="flex items-center justify-between px-2 py-1">
@@ -249,119 +238,74 @@ export function WorkspaceModeSelect({
type="button"
onClick={handleAddEnvironment}
aria-label="Add cloud environment"
- className="flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground"
+ className={ICON_BUTTON_CLASS}
>
<Plus size={12} />
</button>
</div>
<DropdownMenuGroup>
- <DropdownMenuItem
- onClick={() => {
- onChange("cloud");
- onCloudEnvironmentChange?.(null);
- }}
- render={
- <ItemMenuItem size="xs" className="w-full">
- <ItemMedia variant="icon" className="mt-2 ml-2">
- <span>{CLOUD_ICON}</span>
- </ItemMedia>
- <ItemContent variant="menuItem">
- <ItemTitle>Default</ItemTitle>
- <ItemDescription className="whitespace-nowrap leading-none">
- Full network access
- </ItemDescription>
- </ItemContent>
- </ItemMenuItem>
- }
- />
-
- {environments.map((env) => (
- <DropdownMenuItem
- key={`cloud-env-${env.id}`}
- onClick={() => {
- onChange("cloud");
- onCloudEnvironmentChange?.(env.id);
- }}
- render={
- <ItemMenuItem size="xs" className="w-full">
- <ItemMedia variant="icon" className="mt-2 ml-2">
- <span>{CLOUD_ICON}</span>
- </ItemMedia>
- <ItemContent variant="menuItem">
- <ItemTitle>{env.name}</ItemTitle>
- <ItemDescription className="whitespace-nowrap leading-none">
- {env.network_access_level === "full"
- ? "Full network access"
- : env.network_access_level === "trusted"
- ? "Trusted sources only"
- : `${env.allowed_domains.length} allowed domain${env.allowed_domains.length !== 1 ? "s" : ""}`}
- </ItemDescription>
- </ItemContent>
- </ItemMenuItem>
- }
- />
- ))}
- </DropdownMenuGroup>
- </>
- )}
-
- {showCloud && customImagesEnabled && readyImages.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <div className="flex items-center justify-between px-2 py-1">
- <MenuLabel className="p-0">Base image</MenuLabel>
- </div>
-
- <DropdownMenuGroup>
- <DropdownMenuItem
- onClick={() => {
- onChange("cloud");
- onCustomImageChange?.(null);
- }}
- render={
- <ItemMenuItem size="xs" className="w-full">
- <ItemMedia variant="icon" className="mt-2 ml-2">
- <span>
- <Cube size={14} weight="regular" />
- </span>
- </ItemMedia>
- <ItemContent variant="menuItem">
- <ItemTitle>Default</ItemTitle>
- <ItemDescription className="whitespace-nowrap leading-none">
- Standard sandbox image
- </ItemDescription>
- </ItemContent>
- </ItemMenuItem>
- }
- />
-
- {readyImages.map((image) => (
- <DropdownMenuItem
- key={`custom-image-${image.id}`}
- onClick={() => {
- onChange("cloud");
- onCustomImageChange?.(image.id);
- }}
- render={
- <ItemMenuItem size="xs" className="w-full">
- <ItemMedia variant="icon" className="mt-2 ml-2">
- <span>
- <Cube size={14} weight="regular" />
- </span>
- </ItemMedia>
- <ItemContent variant="menuItem">
- <ItemTitle>{image.name}</ItemTitle>
- <ItemDescription className="whitespace-nowrap leading-none">
- {image.version > 0
- ? `Custom image · v${image.version}`
- : "Custom image"}
- </ItemDescription>
- </ItemContent>
- </ItemMenuItem>
- }
- />
- ))}
+ {options.map((option) => {
+ const isFavorite = favoriteKey === option.key;
+ return (
+ <DropdownMenuItem
+ key={option.key}
+ onClick={() => {
+ onChange("cloud");
+ onCloudTargetChange?.(option.target);
+ }}
+ render={
+ <ItemMenuItem
+ size="xs"
+ className="w-full"
+ render={<div />}
+ >
+ <ItemMedia variant="icon" className="mt-2 ml-2">
+ <span>{CLOUD_ICON}</span>
+ </ItemMedia>
+ <ItemContent variant="menuItem">
+ <ItemTitle>{option.name}</ItemTitle>
+ <ItemDescription className="whitespace-nowrap leading-none">
+ {option.description}
+ </ItemDescription>
+ </ItemContent>
+ <ItemActions className="mr-1.5 ml-auto self-center">
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-label={
+ isFavorite
+ ? `Stop using ${option.name} by default`
+ : `Use ${option.name} by default`
+ }
+ aria-pressed={isFavorite}
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ toggleFavorite(option.target);
+ }}
+ className={cn(
+ "flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 transition-colors hover:text-foreground",
+ isFavorite
+ ? "text-foreground"
+ : "text-muted-foreground opacity-0 group-hover/dropdown-menu-item:opacity-100",
+ )}
+ >
+ <Star
+ size={12}
+ weight={isFavorite ? "fill" : "regular"}
+ />
+ </button>
+ </ItemActions>
+ </ItemMenuItem>
+ }
+ />
+ );
+ })}
</DropdownMenuGroup>
</>
)}
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudTarget.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudTarget.ts
new file mode 100644
index 000000000000..64be6a184a8a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudTarget.ts
@@ -0,0 +1,91 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useSandboxCustomImages } from "../../settings/sections/environments/useSandboxCustomImages";
+import { useSandboxEnvironments } from "../../settings/sections/environments/useSandboxEnvironments";
+import { useSettingsStore } from "../../settings/settingsStore";
+import {
+ buildCloudTargetOptions,
+ type CloudTarget,
+ type CloudTargetOption,
+ cloudTargetFromKey,
+ cloudTargetKey,
+ DEFAULT_CLOUD_TARGET,
+ moveFavoriteFirst,
+ resolveCloudTarget,
+} from "../cloudTargets";
+
+export interface UseCloudTargetOptionsResult {
+ options: CloudTargetOption[];
+ favoriteKey: string | null;
+ toggleFavorite: (target: CloudTarget) => void;
+ isLoaded: boolean;
+}
+
+export function useCloudTargetOptions(): UseCloudTargetOptionsResult {
+ const { environments, isLoading: environmentsLoading } =
+ useSandboxEnvironments();
+ const {
+ images,
+ customImagesEnabled,
+ isLoading: imagesLoading,
+ } = useSandboxCustomImages();
+ const favoriteKey = useSettingsStore((state) => state.favoriteCloudTargetKey);
+ const setFavoriteKey = useSettingsStore(
+ (state) => state.setFavoriteCloudTargetKey,
+ );
+
+ const options = useMemo(
+ () =>
+ moveFavoriteFirst(
+ buildCloudTargetOptions({
+ environments,
+ images,
+ imagesEnabled: customImagesEnabled,
+ }),
+ favoriteKey,
+ ),
+ [environments, images, customImagesEnabled, favoriteKey],
+ );
+
+ const toggleFavorite = useCallback(
+ (target: CloudTarget) => {
+ const key = cloudTargetKey(target);
+ setFavoriteKey(favoriteKey === key ? null : key);
+ },
+ [favoriteKey, setFavoriteKey],
+ );
+
+ return {
+ options,
+ favoriteKey,
+ toggleFavorite,
+ isLoaded: !environmentsLoading && !imagesLoading,
+ };
+}
+
+export interface UseCloudTargetSelectionResult {
+ cloudTarget: CloudTarget;
+ setCloudTarget: (target: CloudTarget) => void;
+}
+
+export function useCloudTargetSelection(): UseCloudTargetSelectionResult {
+ const { options, favoriteKey, isLoaded } = useCloudTargetOptions();
+ const settingsHydrated = useSettingsStore((state) => state._hasHydrated);
+ const [cloudTarget, setCloudTargetState] =
+ useState<CloudTarget>(DEFAULT_CLOUD_TARGET);
+ const didResolveRef = useRef(false);
+
+ useEffect(() => {
+ if (didResolveRef.current || !settingsHydrated || !isLoaded) return;
+ didResolveRef.current = true;
+ setCloudTargetState(
+ resolveCloudTarget(cloudTargetFromKey(favoriteKey), options),
+ );
+ }, [settingsHydrated, isLoaded, favoriteKey, options]);
+
+ const setCloudTarget = useCallback((target: CloudTarget) => {
+ didResolveRef.current = true;
+ setCloudTargetState(target);
+ }, []);
+
+ return { cloudTarget, setCloudTarget };
+}