: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): restore space repository linking (#77252)
Shy Alterf8c1962a0324
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 3bb335a8802a..b6c3e7b68e7a 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2454,6 +2454,32 @@ export class PostHogAPIClient {return (await response.json()) as TaskChannel;}+ async updateTaskChannelRepositories(+ id: string,+ githubIntegration: number | null,+ repositories: string[],+ ): Promise<TaskChannel> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/task_channels/${encodeURIComponent(id)}/`;+ const response = await this.api.fetcher.fetch({+ method: "patch",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ overrides: {+ body: JSON.stringify({+ github_integration: githubIntegration,+ repositories,+ }),+ },+ });+ if (!response.ok) {+ throw new Error(+ `Failed to update space repositories: ${response.statusText}`,+ );+ }+ return (await response.json()) as TaskChannel;+ }+async deleteTaskChannel(id: string): Promise<void> {const teamId = await this.getTeamId();const urlPath = `/api/projects/${teamId}/task_channels/${encodeURIComponent(id)}/`;diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 5b84b7221f88..774f12ab4934 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -102,6 +102,8 @@ export interface TaskChannel {name: string;channel_type: "public" | "personal";starred: boolean;+ github_integration?: number | null;+ repositories?: string[];created_at: string;created_by?: UserBasic | null;}diff --git a/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsxindex c5b55d3ad58c..0fadb32de3a2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/CreateChannelModal.tsx@@ -14,12 +14,15 @@ import {FieldError,FieldLabel,Input,+ Text,Textarea,} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { RepositoriesField } from "@posthog/ui/features/canvas/components/RepositoriesField";import { useChannelMutations } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useGenerateContext } from "@posthog/ui/features/canvas/hooks/useGenerateContext";+import { useUpdateTaskChannelRepositories } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { toast } from "@posthog/ui/primitives/toast";import { track } from "@posthog/ui/shell/analytics";import { useNavigate } from "@tanstack/react-router";@@ -99,11 +102,18 @@ export function CreateChannelModal({const spacesLayout = useChannelsLayout();const { createChannel, isCreating } = useChannelMutations();const { generate, isStarting } = useGenerateContext();+ const linkRepositories = useUpdateTaskChannelRepositories();const navigate = useNavigate();const [name, setName] = useState("");const [description, setDescription] = useState("");+ const [repositories, setRepositories] = useState<string[]>([]);+ const [repositoryIntegration, setRepositoryIntegration] = useState<+ number | null+ >(null);// Create mode's step. Describe mode has no name step, so it starts past it.- const [step, setStep] = useState<"name" | "describe">("name");+ const [step, setStep] = useState<"name" | "describe" | "repositories">(+ "name",+ );const descriptionHelperId = useId();// Reset the fields each time the modal opens so a previous draft never@@ -115,6 +125,8 @@ export function CreateChannelModal({if (open) {setName("");setDescription("");+ setRepositories([]);+ setRepositoryIntegration(null);setStep("name");}}@@ -124,7 +136,7 @@ export function CreateChannelModal({const remaining = MAX_CONTEXT_NAME_LENGTH - name.length;const nameError = isDescribeMode ? null : validateChannelName(trimmedName);- const busy = isCreating || isStarting;+ const busy = isCreating || isStarting || linkRepositories.isPending;const canAdvance = !busy && !!trimmedName && !nameError;const canDescribe = !busy && !!trimmedDescription;@@ -143,7 +155,7 @@ export function CreateChannelModal({}};- const submitCreate = async (withContextMd: boolean) => {+ const submitCreate = async (linkSelectedRepositories: boolean) => {let contextId: string;try {const channel = await createChannel(trimmedName);@@ -166,7 +178,21 @@ export function CreateChannelModal({return;}- if (withContextMd && trimmedDescription) {+ if (linkSelectedRepositories && repositories.length > 0) {+ try {+ await linkRepositories.mutateAsync({+ channelId: contextId,+ githubIntegration: repositoryIntegration,+ repositories,+ });+ } catch (error) {+ toast.error("Couldn't link repositories", {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }++ if (trimmedDescription) {track(ANALYTICS_EVENTS.CONTEXT_ACTION, {action_type: "generate_started",channel_id: contextId,@@ -217,10 +243,9 @@ export function CreateChannelModal({if (isDescribeMode) {if (!canDescribe) return;await submitDescribe();- } else {- if (!canDescribe) return;- await submitCreate(true);+ return;}+ if (canDescribe) setStep("repositories");};const descriptionField = (@@ -370,11 +395,10 @@ export function CreateChannelModal({</Button></DialogFooter>- {/* Step two (About), nested inside step one rather than replacing it:- quill scales and dims a parent that has a nested dialog open, so the- name step stays visible behind. */}+ {/* The About dialog stays mounted behind the repository step so Quill+ can preserve the visual stack and return path. */}<Dialog- open={step === "describe"}+ open={step === "describe" || step === "repositories"}onOpenChange={(next) => {if (!busy && !next) setStep("name");}}@@ -418,7 +442,7 @@ export function CreateChannelModal({disabled={busy}onClick={() => {setDescription("");- void submitOnce(() => submitCreate(false));+ setStep("repositories");}}>Skip@@ -428,9 +452,71 @@ export function CreateChannelModal({disabled={!canDescribe}onClick={() => void submitOnce(submitDescribeStep)}>- Create+ Next</Button></DialogFooter>++ <Dialog+ open={step === "repositories"}+ onOpenChange={(next) => {+ if (!busy && !next) setStep("describe");+ }}+ >+ <DialogContent+ showCloseButton={false}+ className="sm:max-w-lg"+ style={+ {+ "--quill-dialog-top-gap": "max(1rem, 10vh + 3rem)",+ } as CSSProperties+ }+ >+ <DialogHeader>+ <DialogTitle>Link repositories</DialogTitle>+ </DialogHeader>++ <DialogBody viewportClassName="flex flex-col gap-3">+ <Text size="sm" variant="muted">+ New tasks in this {spacesLayout ? "space" : "channel"} can+ use these repositories. You can change them later.+ </Text>+ <RepositoriesField+ selected={repositories}+ integrationId={repositoryIntegration}+ disabled={busy}+ onChange={(nextRepositories, nextIntegration) => {+ setRepositories(nextRepositories);+ setRepositoryIntegration(nextIntegration);+ }}+ />+ </DialogBody>++ <DialogFooter>+ <Button+ variant="outline"+ disabled={busy}+ onClick={() => setStep("describe")}+ >+ Back+ </Button>+ <Button+ variant="default"+ disabled={busy}+ onClick={() => void submitOnce(() => submitCreate(false))}+ >+ Skip+ </Button>+ <Button+ variant="primary"+ disabled={busy || repositories.length === 0}+ loading={busy}+ onClick={() => void submitOnce(() => submitCreate(true))}+ >+ Create+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></DialogContent></Dialog></DialogContent>diff --git a/products/desktop/packages/ui/src/features/canvas/components/RepositoriesField.tsx b/products/desktop/packages/ui/src/features/canvas/components/RepositoriesField.tsxindex eaa294e4abe3..9fd36602cfce 100644--- a/products/desktop/packages/ui/src/features/canvas/components/RepositoriesField.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/RepositoriesField.tsx@@ -1,14 +1,22 @@import { GithubLogoIcon, XIcon } from "@phosphor-icons/react";import {+ Button,+ Chip,+ ChipClose,Input,+ ItemContent,+ ItemMedia,+ ItemMenuItem,+ ItemTitle,Popover,PopoverContent,PopoverTrigger,- Button as QuillButton,+ Spinner,+ Tooltip,+ TooltipContent,+ TooltipTrigger,} from "@posthog/quill";import { useRepositoryIntegration } from "@posthog/ui/features/integrations/useIntegrations";-import { Tooltip } from "@posthog/ui/primitives/Tooltip";-import { Flex, Spinner } from "@radix-ui/themes";import { useState } from "react";export const MAX_REPOSITORIES = 10;@@ -18,27 +26,24 @@ const REPO_SEARCH_THRESHOLD = 10;function RepoChip({repository,onRemove,+ disabled,}: {repository: string;onRemove: () => void;+ disabled: boolean;}) {return (- <span className="group/chip inline-flex h-6 items-center gap-1.5 rounded-md bg-(--gray-a3) pr-2.5 pl-2 font-medium text-(--gray-11) text-[12px] transition-colors hover:bg-(--gray-a4)">- <button- type="button"+ <Chip>+ <GithubLogoIcon size={14} />+ <span className="max-w-[200px] truncate">{repository}</span>+ <ChipClosearia-label={`Remove ${repository}`}- className="relative inline-flex size-4 shrink-0 cursor-pointer items-center justify-center border-none bg-transparent p-0"+ disabled={disabled}onClick={onRemove}>- <span className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-100 transition-opacity duration-150 group-hover/chip:opacity-0 motion-reduce:transition-none">- <GithubLogoIcon size={14} />- </span>- <span className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-150 group-hover/chip:opacity-100 motion-reduce:transition-none">- <XIcon size={13} weight="bold" />- </span>- </button>- <span className="max-w-[200px] truncate">{repository}</span>- </span>+ <XIcon size={13} weight="bold" />+ </ChipClose>+ </Chip>);}@@ -72,10 +77,10 @@ function AddRepositoryPopover({><PopoverTriggerrender={- <QuillButton variant="outline" size="sm">+ <Button variant="outline" size="sm"><GithubLogoIcon size={14} />{label}- </QuillButton>+ </Button>}/><PopoverContent@@ -101,18 +106,21 @@ function AddRepositoryPopover({</div>) : (filtered.map((repository) => (- <button+ <ItemMenuItemkey={repository}- type="button"+ size="xs"onClick={() => {onAdd(repository);setOpen(false);}}- className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-[13px] hover:bg-[var(--fill-hover)]">- <GithubLogoIcon size={14} className="shrink-0" />- <span className="truncate">{repository}</span>- </button>+ <ItemMedia variant="icon">+ <GithubLogoIcon size={14} />+ </ItemMedia>+ <ItemContent variant="menuItem">+ <ItemTitle className="truncate">{repository}</ItemTitle>+ </ItemContent>+ </ItemMenuItem>)))}</div>@@ -176,34 +184,39 @@ export function RepositoriesField({: null;return (- // Radix spacing tokens are unavailable inside the dialog portal.- <Flex align="center" wrap="wrap" className="min-h-7 w-fit max-w-full gap-2">+ <div className="flex min-h-7 w-fit max-w-full flex-wrap items-center gap-2">{selected.map((repository) => (<RepoChipkey={repository}repository={repository}+ disabled={disabled}onRemove={() => removeRepository(repository)}/>))}{disabled ? (- <QuillButton variant="outline" size="sm" disabled>+ <Button variant="outline" size="sm" disabled><GithubLogoIcon size={14} />Add repository- </QuillButton>+ </Button>) : isLoadingList && hasGithubIntegration ? (- <QuillButton variant="outline" size="sm" disabled>- <Spinner size="1" />+ <Button variant="outline" size="sm" disabled>+ <Spinner className="size-3.5" />Loading repositories…- </QuillButton>+ </Button>) : addDisabledReason ? (- <Tooltip content={addDisabledReason}>- <span className="inline-flex">- <QuillButton variant="outline" size="sm" disabled>- <GithubLogoIcon size={14} />- Add repository- </QuillButton>- </span>+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="inline-flex">+ <Button variant="outline" size="sm" disabled>+ <GithubLogoIcon size={14} />+ Add repository+ </Button>+ </span>+ }+ />+ <TooltipContent>{addDisabledReason}</TooltipContent></Tooltip>) : (<AddRepositoryPopover@@ -212,6 +225,6 @@ export function RepositoriesField({label={selected.length > 0 ? "Add…" : "Add repository…"}/>)}- </Flex>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/components/WebsiteContext.tsx b/products/desktop/packages/ui/src/features/canvas/components/WebsiteContext.tsxindex 848145da53fd..c9def3a7ffae 100644--- a/products/desktop/packages/ui/src/features/canvas/components/WebsiteContext.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/WebsiteContext.tsx@@ -1,4 +1,8 @@-import { FileTextIcon, SparkleIcon } from "@phosphor-icons/react";+import {+ FileTextIcon,+ GitBranchIcon,+ SparkleIcon,+} from "@phosphor-icons/react";import { FolderInstructionsConflictError } from "@posthog/api-client/posthog-client";import { buildContextSaveProps } from "@posthog/core/canvas/canvasAnalytics";import {@@ -11,9 +15,13 @@ import {Button as QuillButton,} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import type { TaskChannel } from "@posthog/shared/domain-types";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { ChannelHeader } from "@posthog/ui/features/canvas/components/ChannelHeader";import { CreateChannelModal } from "@posthog/ui/features/canvas/components/CreateChannelModal";import { channelPageIcon } from "@posthog/ui/features/canvas/components/channelPages";+import { RepositoriesField } from "@posthog/ui/features/canvas/components/RepositoriesField";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import {@@ -21,6 +29,10 @@ import {useFolderInstructionsMutations,useFolderInstructionsVersions,} from "@posthog/ui/features/canvas/hooks/useFolderInstructions";+import {+ useTaskChannels,+ useUpdateTaskChannelRepositories,+} from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";import {@@ -68,6 +80,8 @@ export function WebsiteContext({ channelId }: WebsiteContextProps) {const channelName =channels.find((c) => c.id === channelId)?.name ??(spacesLayout ? "Space" : "Channel");+ const { channels: taskChannels } = useTaskChannels();+ const taskChannel = taskChannels.find((channel) => channel.id === channelId);const {data: latest,@@ -194,6 +208,9 @@ export function WebsiteContext({ channelId }: WebsiteContextProps) {</PageHeaderHeading></PageHeader>)}+ {spacesLayout && taskChannel ? (+ <SpaceRepositories channel={taskChannel} />+ ) : null}<Flexalign="center"justify="between"@@ -357,6 +374,41 @@ export function WebsiteContext({ channelId }: WebsiteContextProps) {);}+function SpaceRepositories({ channel }: { channel: TaskChannel }) {+ const update = useUpdateTaskChannelRepositories();+ const client = useOptionalAuthenticatedClient();+ const { data: currentUser } = useCurrentUser({ client });+ const canEdit = currentUser?.id === channel.created_by?.id;++ return (+ <div className="flex shrink-0 flex-col gap-2 border-b border-b-(--gray-5) px-4 py-3">+ <div className="flex items-center gap-2">+ <GitBranchIcon size={15} className="text-muted-foreground" />+ <span className="font-medium text-[13px]">Repositories</span>+ {update.isPending ? (+ <Spinner size="1" />+ ) : update.error ? (+ <span className="text-[12px] text-red-11">+ Couldn't save. Try again.+ </span>+ ) : null}+ </div>+ <RepositoriesField+ selected={channel.repositories ?? []}+ integrationId={channel.github_integration ?? null}+ disabled={!canEdit || update.isPending}+ onChange={(repositories, githubIntegration) =>+ update.mutate({+ channelId: channel.id,+ githubIntegration,+ repositories,+ })+ }+ />+ </div>+ );+}+function EmptyState({channelId,channelName,diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsxindex 98ee6b095d62..8329d0f7a67c 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.test.tsx@@ -1,17 +1,22 @@import type { TaskChannel } from "@posthog/shared/domain-types";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { renderHook, waitFor } from "@testing-library/react";+import { act, renderHook, waitFor } from "@testing-library/react";import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";const mockClient = vi.hoisted(() => ({getTaskChannels: vi.fn(),+ updateTaskChannelRepositories: vi.fn(),}));vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => mockClient,}));-import { useTaskChannels } from "./useTaskChannels";+import {+ TASK_CHANNELS_QUERY_KEY,+ useTaskChannels,+ useUpdateTaskChannelRepositories,+} from "./useTaskChannels";function taskChannel(id: string,@@ -65,4 +70,51 @@ describe("useTaskChannels", () => {expect(result.current.channels).toEqual([]);expect(result.current.personalChannel).toBeUndefined();});++ it("updates repository links immediately while the request is pending", async () => {+ const channel = taskChannel("1", "growth");+ queryClient.setQueryData<TaskChannel[]>(TASK_CHANNELS_QUERY_KEY, [channel]);+ let finishUpdate: (updated: TaskChannel) => void = () => {};+ mockClient.updateTaskChannelRepositories.mockReturnValue(+ new Promise((resolve) => {+ finishUpdate = resolve;+ }),+ );++ const { result } = renderHook(() => useUpdateTaskChannelRepositories(), {+ wrapper,+ });+ act(() => {+ result.current.mutate({+ channelId: channel.id,+ githubIntegration: 42,+ repositories: ["posthog/posthog"],+ });+ });++ await waitFor(() => expect(result.current.isPending).toBe(true));+ expect(+ queryClient.getQueryData<TaskChannel[]>(TASK_CHANNELS_QUERY_KEY),+ ).toEqual([+ {+ ...channel,+ github_integration: 42,+ repositories: ["posthog/posthog"],+ },+ ]);++ await act(async () => {+ finishUpdate({+ ...channel,+ github_integration: 42,+ repositories: ["posthog/posthog"],+ });+ });+ await waitFor(() => expect(result.current.isPending).toBe(false));+ expect(mockClient.updateTaskChannelRepositories).toHaveBeenCalledWith(+ "1",+ 42,+ ["posthog/posthog"],+ );+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.tsindex 9259d057a152..138284869458 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskChannels.ts@@ -1,5 +1,7 @@import type { TaskChannel } from "@posthog/shared/domain-types";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { useMutation, useQueryClient } from "@tanstack/react-query";import { useMemo } from "react";const TASK_CHANNELS_POLL_INTERVAL_MS = 30_000;@@ -33,3 +35,57 @@ export function useTaskChannels(options?: { enabled?: boolean }): {);return { channels, personalChannel, isLoading: query.isLoading };}++export function useUpdateTaskChannelRepositories() {+ const client = useOptionalAuthenticatedClient();+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (input: {+ channelId: string;+ githubIntegration: number | null;+ repositories: string[];+ }) => {+ if (!client) throw new Error("Not authenticated");+ return client.updateTaskChannelRepositories(+ input.channelId,+ input.githubIntegration,+ input.repositories,+ );+ },+ onMutate: async (input) => {+ await queryClient.cancelQueries({ queryKey: TASK_CHANNELS_QUERY_KEY });+ const previous = queryClient.getQueryData<TaskChannel[]>(+ TASK_CHANNELS_QUERY_KEY,+ );+ queryClient.setQueryData<TaskChannel[]>(+ TASK_CHANNELS_QUERY_KEY,+ (channels) =>+ channels?.map((channel) =>+ channel.id === input.channelId+ ? {+ ...channel,+ github_integration: input.githubIntegration,+ repositories: input.repositories,+ }+ : channel,+ ),+ );+ return { previous };+ },+ onError: (_error, _input, context) => {+ if (context?.previous) {+ queryClient.setQueryData(TASK_CHANNELS_QUERY_KEY, context.previous);+ }+ },+ onSuccess: (updatedChannel) => {+ queryClient.setQueryData<TaskChannel[]>(+ TASK_CHANNELS_QUERY_KEY,+ (channels) =>+ channels?.map((channel) =>+ channel.id === updatedChannel.id ? updatedChannel : channel,+ ),+ );+ },+ });+}