: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
feat(desktop): add Slack DM settings for task comments (#81292)
Shy Alter33c93aef45a3
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 80c093ca5eb8..9e67349ce3e6 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -1750,6 +1750,76 @@ export class PostHogAPIClient {}}+ /** The user's linked Slack identities. Empty until they run the Sign-in-with-Slack flow. */+ async listSlackUserIntegrations(): Promise<+ {+ slack_user_id: string;+ slack_team_id: string;+ slack_team_name: string | null;+ }[]+ > {+ const urlPath = `/api/users/@me/integrations/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ url.searchParams.set("kind", "slack");+ const response = await this.api.fetcher.fetch({+ method: "get",+ url,+ path: urlPath,+ });+ if (!response.ok) {+ throw new Error(+ `Failed to list Slack integrations: ${response.statusText}`,+ );+ }+ const data = (await response.json()) as {+ results?: {+ slack_user_id: string;+ slack_team_id: string;+ slack_team_name: string | null;+ }[];+ };+ return data.results ?? [];+ }++ /**+ * `POST .../integrations/slack/start`. Returns the Sign-in-with-Slack URL; Slack tells the+ * callback which user authorized, so nobody types a Slack ID.+ */+ async startSlackUserIntegrationConnect(+ teamId?: number,+ ): Promise<{ install_url: string }> {+ const id = teamId ?? (await this.getTeamId());+ const urlPath = `/api/users/@me/integrations/slack/start/`;+ const url = new URL(`${this.api.baseUrl}${urlPath}`);+ const response = await this.api.fetcher.fetch({+ method: "post",+ url,+ path: urlPath,+ overrides: { body: JSON.stringify({ team_id: id }) },+ });+ if (!response.ok) {+ const err = (await response.json().catch(() => ({}))) as {+ detail?: unknown;+ };+ throw new Error(+ typeof err.detail === "string"+ ? err.detail+ : `Failed to start Slack connect: ${response.statusText}`,+ );+ }+ return (await response.json()) as { install_url: string };+ }++ /** Patch the user's server-side notification settings. Merged server-side, so pass only the keys you change. */+ async updateNotificationSettings(+ settings: Record<string, unknown>,+ ): Promise<void> {+ await this.api.patch("/api/users/{uuid}/", {+ path: { uuid: "@me" },+ body: { notification_settings: settings } as Record<string, unknown>,+ });+ }+async switchOrganization(orgId: string): Promise<void> {await this.api.patch("/api/users/{uuid}/", {path: { uuid: "@me" },diff --git a/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsxindex 478407db2957..87161d8f5ff5 100644--- a/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/NotificationsSettings.tsx@@ -15,6 +15,7 @@ import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlaimport { NotificationBus } from "@posthog/ui/features/notifications/notifications";import { SettingRow } from "@posthog/ui/features/settings/SettingRow";import { AddCustomSoundDialog } from "@posthog/ui/features/settings/sections/AddCustomSoundDialog";+import { SlackCommentNotificationsSettings } from "@posthog/ui/features/settings/sections/SlackCommentNotificationsSettings";import {type CompletionSound,type CustomSound,@@ -386,6 +387,8 @@ export function NotificationsSettings() {{spokenNarrationEnabled && <SpokenNotificationsSection />}+ <SlackCommentNotificationsSettings />+<NotificationTestHarnessbus={bus}notifications={notifications}diff --git a/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsxnew file mode 100644index 000000000000..ccc46b3495c1--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/SlackCommentNotificationsSettings.tsx@@ -0,0 +1,124 @@+import { Button, Switch, Text } from "@posthog/quill";+import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";+import { SettingRow } from "@posthog/ui/features/settings/SettingRow";+import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { toast } from "@posthog/ui/primitives/toast";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";+import { useQueryClient } from "@tanstack/react-query";++// Server-side, unlike the toggles above it: the DM is sent by a worker, so the preference has to+// be readable when this app is closed.+const SETTING_KEY = "task_comments_slack_dm";++export function SlackCommentNotificationsSettings() {+ const queryClient = useQueryClient();+ const { data: me, isLoading } = useMeQuery();+ const { data: links, isLoading: linksLoading } = useAuthenticatedQuery(+ ["slack-user-integrations"],+ async (client) => await client.listSlackUserIntegrations(),+ );++ const enabled = Boolean(+ (me?.notification_settings as Record<string, unknown> | undefined)?.[+ SETTING_KEY+ ],+ );+ const linked = (links?.length ?? 0) > 0;++ const { mutate, isPending } = useAuthenticatedMutation<void, Error, boolean>(+ async (client, next) =>+ await client.updateNotificationSettings({ [SETTING_KEY]: next }),+ {+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: ["me"] });+ },+ onError: (error) =>+ toast.error("Couldn't update Slack notifications", {+ description: error.message,+ }),+ },+ );++ // Slack's OAuth callback tells us which Slack user authorized, so the link is established+ // without anyone entering an ID.+ const { mutate: connect, isPending: connecting } = useAuthenticatedMutation<+ void,+ Error,+ void+ >(+ async (client) => {+ const { install_url } = await client.startSlackUserIntegrationConnect();+ openExternalUrl(install_url);+ },+ {+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: ["slack-user-integrations"],+ });+ },+ // The endpoint refuses when the project has no Slack app connected, or when the org is+ // outside the rollout. Without this the button does nothing, which reads as a broken build.+ onError: (error) =>+ toast.error("Couldn't start Slack linking", {+ description: error.message,+ }),+ },+ );++ return (+ <>+ <Text+ size="sm"+ weight="medium"+ className="mt-4 mb-1 block border-gray-6 border-t pt-4"+ >+ Slack+ </Text>+ <Text size="xs" variant="muted" className="mb-1 block">+ Comment notifications can also reach you in Slack, so you hear about+ them when PostHog Code isn't open.+ </Text>++ <SettingRow+ label="Slack account"+ description={+ linked+ ? `Linked to ${links?.[0]?.slack_team_name ?? "Slack"}`+ : "Only needed when your Slack email differs from your PostHog email. Otherwise we find you by email."+ }+ >+ {linked ? (+ <Text size="xs" variant="muted">+ Linked+ </Text>+ ) : (+ <Button+ size="xs"+ loading={connecting}+ disabled={linksLoading}+ onClick={() => connect()}+ >+ Link Slack account+ </Button>+ )}+ </SettingRow>++ <SettingRow+ label="Slack DMs for comments"+ description="Get a direct message when someone mentions you, replies to your comment, or comments on something you own"+ noBorder+ >+ <div className="flex items-center gap-2">+ {/* Deliberately not gated on a link: an unlinked recipient is matched to Slack by+ email, so gating here would hide a path that works. */}+ <Switch+ checked={enabled}+ onCheckedChange={(next) => mutate(next)}+ disabled={isLoading || isPending}+ />+ </div>+ </SettingRow>+ </>+ );+}