: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(tasks): share a private task from the task header (#129382)
Shy Alter0a5379cd2bd0
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskShareControl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskShareControl.tsxnew file mode 100644index 000000000000..c30b69217e74--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskShareControl.tsx@@ -0,0 +1,175 @@+import { useActions, useValues } from 'kea'+import { RefObject, useRef } from 'react'++import { IconChevronDown, IconGlobe, IconLock, IconPeople, IconRefresh, IconShare } from '@posthog/icons'+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Badge,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@posthog/quill'++import { IconLink } from 'lib/lemon-ui/icons'+import { teamLogic } from 'scenes/teamLogic'++import { TaskVisibility, taskShareLogic } from '../taskShareLogic'++const LABELS: Record<TaskVisibility, string> = { private: 'Private', public: 'Public', shared: 'Shared' }+const ICONS: Record<TaskVisibility, JSX.Element> = {+ private: <IconLock />,+ public: <IconGlobe />,+ shared: <IconPeople />,+}++function ShareTaskDialog({+ taskId,+ open,+ controlRef,+}: {+ taskId: string+ open: boolean+ controlRef: RefObject<HTMLDivElement | null>+}): JSX.Element {+ const logic = taskShareLogic({ taskId })+ const { visibilityChanging } = useValues(logic)+ const { closeShareDialog, setVisibility } = useActions(logic)+ const { currentTeam } = useValues(teamLogic)+ const project = currentTeam?.name ? `Everyone in ${currentTeam.name}` : 'Everyone in this project'++ return (+ <AlertDialog+ open={open}+ onOpenChange={(nextOpen: boolean) => {+ if (!nextOpen && !visibilityChanging) {+ closeShareDialog()+ }+ }}+ >+ <AlertDialogContent+ // A share swaps the Share button for the Public menu, so focus the button that is there now.+ finalFocus={() => controlRef.current?.querySelector<HTMLElement>('button') ?? true}+ >+ <AlertDialogHeader>+ <AlertDialogTitle>Make this task public?</AlertDialogTitle>+ <AlertDialogDescription>+ {`${project} can see this task and its chat. We copy the link for you.`}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={() => closeShareDialog()}+ disabled={visibilityChanging}+ data-attr="task-share-cancel"+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ loading={visibilityChanging}+ onClick={() => setVisibility('public')}+ data-attr="task-share-confirm"+ >+ <IconGlobe />+ Make public+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )+}++function ShareControlButton({ taskId }: { taskId: string }): JSX.Element | null {+ const logic = taskShareLogic({ taskId })+ const { visibility, isCreator, visibilityChanging, shareStateLoadFailed, shareStateLoading } = useValues(logic)+ const { openShareDialog, setVisibility, copyLink, loadShareState } = useActions(logic)++ if (shareStateLoadFailed) {+ return (+ <Button+ variant="outline"+ loading={shareStateLoading}+ onClick={() => loadShareState()}+ title="Could not load who can see this task. Click to try again."+ data-attr="task-share-retry"+ >+ <IconRefresh />+ Share+ </Button>+ )+ }+ if (!visibility || (visibility === 'private' && !isCreator)) {+ return null+ }+ if (visibility === 'private') {+ return (+ <Button+ variant="outline"+ loading={visibilityChanging}+ onClick={() => openShareDialog()}+ data-attr="task-share"+ >+ <IconShare />+ Share+ </Button>+ )+ }+ if (!isCreator) {+ return (+ <Badge aria-label={LABELS[visibility]}>+ {ICONS[visibility]}+ {LABELS[visibility]}+ </Badge>+ )+ }+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="outline"+ loading={visibilityChanging}+ aria-label={`${LABELS[visibility]}. Change who can see this task`}+ data-attr="task-visibility"+ />+ }+ >+ {ICONS[visibility]}+ {LABELS[visibility]}+ <IconChevronDown />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-48">+ <DropdownMenuItem onClick={() => copyLink()} data-attr="task-copy-link">+ <IconLink />+ Copy link+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => setVisibility('private')} data-attr="task-make-private">+ <IconLock />+ Make private+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}++export function QuillTaskShareControl({ taskId }: { taskId: string }): JSX.Element {+ const { isCreator, shareDialogOpen } = useValues(taskShareLogic({ taskId }))+ const controlRef = useRef<HTMLDivElement>(null)++ return (+ <div data-quill className="contents" ref={controlRef}>+ <ShareControlButton taskId={taskId} />+ {isCreator && <ShareTaskDialog taskId={taskId} open={shareDialogOpen} controlRef={controlRef} />}+ </div>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsxindex 1a50dba118b7..8df9bba7772f 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx@@ -13,6 +13,7 @@ import { isPiTaskRuntime } from '../../../types/taskTypes'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { QuillTaskHeaderActions } from './QuillTaskHeaderActions'+import { QuillTaskShareControl } from './QuillTaskShareControl'import { TaskHeaderActionsSkeleton } from './taskDetailSkeletons'import { TaskRunTabs } from './TaskRunArtifacts'import { TaskRunLog } from './TaskRunLog'@@ -133,6 +134,7 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPagheaderDivider={!artifactsTabEnabled}titleActions={<div className="flex flex-wrap items-center gap-2">+ {todayRailNav && task && <QuillTaskShareControl taskId={task.id} />}{taskActions}{titleActions}</div>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.test.tsnew file mode 100644index 000000000000..1be13937dc9f--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.test.ts@@ -0,0 +1,87 @@+import { expectLogic } from 'kea-test-utils'++import { copyToClipboard } from 'lib/utils/copyToClipboard'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { TaskShareState, TaskSpace, taskShareLogic, taskVisibility } from './taskShareLogic'++jest.mock('lib/utils/copyToClipboard', () => ({ copyToClipboard: jest.fn(async () => true) }))++const SPACES: TaskSpace[] = [+ { id: 'space-me', system_role: 'personal', channel_type: 'personal' },+ { id: 'space-team', system_role: 'general', channel_type: 'public' },+]++describe('taskShareLogic', () => {+ let patchedChannel: string | null++ beforeEach(() => {+ patchedChannel = null+ useMocks({+ get: {+ '/api/projects/:team_id/task_channels/': { results: SPACES },+ '/api/projects/:team_id/tasks/task-1/': () => [+ 200,+ { id: 'task-1', channel: 'space-me', created_by: { uuid: 'creator' } },+ ],+ },+ patch: {+ '/api/projects/:team_id/tasks/task-1/': async ({ request }) => {+ patchedChannel = ((await request.json()) as { channel: string }).channel+ return [200, { id: 'task-1', channel: patchedChannel }]+ },+ },+ })+ initKeaTests()+ })++ it.each([+ ['public', 'space-me', 'space-team', true],+ ['public', null, 'space-team', true],+ ['private', 'space-team', 'space-me', false],+ ] as const)('making a task %s moves it to the matching space', async (visibility, from, to, copiesLink) => {+ const logic = taskShareLogic({ taskId: 'task-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadShareStateSuccess'])+ logic.actions.channelChanged(from)++ logic.actions.setVisibility(visibility)+ await expectLogic(logic)+ .toDispatchActions(['moveToSpace', 'channelChanged', 'visibilityChanged'])+ .toMatchValues({+ visibility,+ visibilityChanging: false,+ })++ expect(patchedChannel).toBe(to)+ if (copiesLink) {+ expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('/ai?task=task-1'), 'task link', {+ silent: true,+ })+ } else {+ expect(copyToClipboard).not.toHaveBeenCalled()+ }+ jest.mocked(copyToClipboard).mockClear()+ })++ it.each<[string, Partial<TaskShareState>, string | null]>([+ ['a task in the personal space', { channel: 'space-me' }, 'private'],+ ['a task in the team space', { channel: 'space-team' }, 'public'],+ ['a Slack task in the personal space', { channel: 'space-me', originProduct: 'slack' }, null],+ ['a user task with no space', {}, 'private'],+ ['a scout task, which can be a creator-only trial', { originProduct: 'signals_scout' }, null],+ ['a signal report task with no space', { originProduct: 'signal_report' }, 'public'],+ ['a task with no space and no creator', { creatorUuid: null }, 'public'],+ ])('shows the visibility of %s', (_, overrides, expected) => {+ const state: TaskShareState = {+ channel: null,+ creatorUuid: 'creator',+ originProduct: 'posthog_ai',+ spaces: SPACES,+ ...overrides,+ }+ expect(taskVisibility(state)).toBe(expected)+ })+})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.tsnew file mode 100644index 000000000000..79603e8c9acc--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskShareLogic.ts@@ -0,0 +1,342 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { toast } from '@posthog/quill'++import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { todaySessionMenuLogic } from '~/layout/today/todaySessionMenuLogic'+import type { UserType } from '~/types'++import {+ taskChannelsList,+ taskChannelsProvisionDefaultsCreate,+ tasksPartialUpdate,+ tasksRetrieve,+} from 'products/tasks/frontend/generated/api'+import type { ChannelDTOApi, ChannelListResponseApi } from 'products/tasks/frontend/generated/api.schemas'++export type TaskVisibility = 'private' | 'public' | 'shared'+export type TaskSpace = Pick<ChannelDTOApi, 'id' | 'system_role' | 'channel_type'>++export interface TaskShareLogicProps {+ taskId: string+}++export interface TaskShareState {+ channel: string | null+ creatorUuid: string | null+ originProduct: string | null+ spaces: TaskSpace[]+}++// Mirrors products/tasks/backend/visibility.py. For these origins the space does not decide who can+// read the task: Slack tasks in a shared thread are team readable, and scout trial tasks stay+// creator only. The task DTO does not show which scout tasks are trials, so all scout tasks are left out.+const SPACE_INDEPENDENT_ORIGIN_PRODUCTS = new Set(['slack', 'signals_scout'])+// Tasks from these origins stay team readable while they have no space.+const TEAM_READABLE_ORIGIN_PRODUCTS = new Set([+ 'signal_report',+ 'signals_scout',+ 'onboarding',+ 'hogdesk',+ 'workflow',+ 'experiments',+])++export function taskVisibility(shareState: TaskShareState): TaskVisibility | null {+ if (!shareState.spaces.length || SPACE_INDEPENDENT_ORIGIN_PRODUCTS.has(shareState.originProduct ?? '')) {+ return null+ }+ if (!shareState.channel) {+ const teamReadable =+ !shareState.creatorUuid || TEAM_READABLE_ORIGIN_PRODUCTS.has(shareState.originProduct ?? '')+ return teamReadable ? 'public' : 'private'+ }+ const space = shareState.spaces.find((space) => space.id === shareState.channel)+ return space ? spaceVisibility(space) : null+}++export function spaceVisibility(space: Pick<TaskSpace, 'system_role' | 'channel_type'>): TaskVisibility {+ if (space.system_role === 'personal' || space.channel_type === 'personal') {+ return 'private'+ }+ return space.channel_type === 'private' ? 'shared' : 'public'+}++function toSpaces(response: ChannelListResponseApi): TaskSpace[] {+ const rows = Array.isArray(response) ? response : response.results+ return rows.map((row) => ({+ id: String(row.id),+ system_role: row.system_role ?? null,+ channel_type: row.channel_type ?? '',+ }))+}++async function loadSpaces(projectId: string): Promise<TaskSpace[]> {+ const spaces = toSpaces(await taskChannelsList(projectId))+ const hasDefaults = ['personal', 'general'].every((role) => spaces.some((space) => space.system_role === role))+ if (hasDefaults) {+ return spaces+ }+ return toSpaces((await taskChannelsProvisionDefaultsCreate(projectId)).channels)+}++function taskLink(taskId: string): string {+ // The project in the path opens this task for someone whose current project differs.+ return urls.absolute(urls.currentProject(urls.aiTask(taskId)))+}++// Undo runs outside the logic so it still works after the person leaves the task.+function notifyTaskChanged(taskId: string): void {+ todaySessionMenuLogic.findMounted()?.actions.sessionUpdated(taskId)+}++async function undoMove(projectId: string, taskId: string, previousSpaceId: string | null): Promise<void> {+ try {+ const updated = await tasksPartialUpdate(projectId, taskId, { channel: previousSpaceId })+ taskShareLogic.findMounted({ taskId })?.actions.channelChanged(updated.channel ?? null)+ notifyTaskChanged(taskId)+ posthog.capture('task visibility changed', { task_id: taskId, visibility: 'undo' })+ toast.success({ title: 'The change is undone' })+ } catch {+ toast.error({+ title: 'Could not undo the change',+ action: { label: 'Retry', onClick: () => void undoMove(projectId, taskId, previousSpaceId) },+ })+ }+}++const EMPTY_STATE: TaskShareState = { channel: null, creatorUuid: null, originProduct: null, spaces: [] }++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskShareLogicValues {+ currentProjectId: number | null // projectLogic+ user: UserType | null // userLogic+ isCreator: boolean+ shareDialogOpen: boolean+ shareState: TaskShareState+ shareStateLoadFailed: boolean+ shareStateLoading: boolean+ visibility: TaskVisibility | null+ visibilityChanging: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskShareLogicActions {+ channelChanged: (channel: string | null) => {+ channel: string | null+ }+ closeShareDialog: () => {+ value: true+ }+ copyLink: () => {+ value: true+ }+ loadShareState: () => any+ loadShareStateFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadShareStateSuccess: (+ shareState: {+ channel: string | null+ creatorUuid: string | null+ originProduct: string+ spaces: TaskSpace[]+ },+ payload?: any+ ) => {+ shareState: {+ channel: string | null+ creatorUuid: string | null+ originProduct: string+ spaces: TaskSpace[]+ }+ payload?: any+ }+ moveToSpace: (+ spaceId: string,+ previousSpaceId: string | null,+ visibility: 'private' | 'public'+ ) => {+ previousSpaceId: string | null+ spaceId: string+ visibility: 'private' | 'public'+ }+ openShareDialog: () => {+ value: true+ }+ setVisibility: (visibility: 'private' | 'public') => {+ visibility: 'private' | 'public'+ }+ visibilityChanged: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskShareLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ visibility: (shareState: TaskShareState) => TaskVisibility | null+ isCreator: (shareState: TaskShareState, user: UserType | null) => boolean+ }+}++export type taskShareLogicType = MakeLogicType<+ taskShareLogicValues,+ taskShareLogicActions,+ TaskShareLogicProps,+ taskShareLogicMeta+>++export const taskShareLogic = kea<taskShareLogicType>([+ path((key) => ['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskShareLogic', key]),+ props({} as TaskShareLogicProps),+ key((props) => props.taskId),++ connect(() => ({+ values: [projectLogic, ['currentProjectId'], userLogic, ['user']],+ })),++ actions({+ openShareDialog: true,+ closeShareDialog: true,+ setVisibility: (visibility: 'private' | 'public') => ({ visibility }),+ moveToSpace: (spaceId: string, previousSpaceId: string | null, visibility: 'private' | 'public') => ({+ spaceId,+ previousSpaceId,+ visibility,+ }),+ channelChanged: (channel: string | null) => ({ channel }),+ visibilityChanged: true,+ copyLink: true,+ }),++ loaders(({ props, values }) => ({+ shareState: [+ EMPTY_STATE,+ {+ loadShareState: async () => {+ const projectId = String(values.currentProjectId)+ const [task, spaces] = await Promise.all([+ tasksRetrieve(projectId, props.taskId),+ loadSpaces(projectId),+ ])+ return {+ channel: task.channel ?? null,+ creatorUuid: task.created_by?.uuid ?? null,+ originProduct: task.origin_product ?? null,+ spaces,+ }+ },+ },+ ],+ })),++ reducers({+ shareState: {+ channelChanged: (state, { channel }) => ({ ...state, channel }),+ },+ shareStateLoadFailed: [+ false,+ {+ loadShareState: () => false,+ loadShareStateSuccess: () => false,+ loadShareStateFailure: () => true,+ },+ ],+ shareDialogOpen: [+ false,+ {+ openShareDialog: () => true,+ closeShareDialog: () => false,+ visibilityChanged: () => false,+ },+ ],+ visibilityChanging: [+ false,+ {+ setVisibility: () => true,+ moveToSpace: () => true,+ visibilityChanged: () => false,+ },+ ],+ }),++ selectors({+ visibility: [+ (s) => [s.shareState],+ (shareState: TaskShareState): TaskVisibility | null => taskVisibility(shareState),+ ],+ isCreator: [+ (s) => [s.shareState, s.user],+ (shareState: TaskShareState, user: UserType | null): boolean =>+ !!shareState.creatorUuid && shareState.creatorUuid === user?.uuid,+ ],+ }),++ listeners(({ actions, values, props }) => ({+ setVisibility: ({ visibility }) => {+ const role = visibility === 'private' ? 'personal' : 'general'+ const target = values.shareState.spaces.find((space) => space.system_role === role)+ if (!target) {+ toast.error({ title: `Could not make the task ${visibility}`, description: 'Try again.' })+ actions.visibilityChanged()+ return+ }+ actions.moveToSpace(target.id, values.shareState.channel, visibility)+ },+ moveToSpace: async ({ spaceId, previousSpaceId, visibility }) => {+ const projectId = String(values.currentProjectId)+ const taskId = props.taskId+ try {+ const updated = await tasksPartialUpdate(projectId, taskId, { channel: spaceId })+ actions.channelChanged(updated.channel ?? null)+ notifyTaskChanged(taskId)+ posthog.capture('task visibility changed', { task_id: taskId, visibility })+ const copied =+ visibility === 'public' &&+ (await copyToClipboard(taskLink(props.taskId), 'task link', { silent: true }))+ toast.success({+ title: visibility === 'public' ? 'The task is public' : 'The task is private',+ description:+ visibility !== 'public'+ ? undefined+ : copied+ ? 'Paste the link to share it.'+ : 'Could not copy the link. Use Copy link in the Public menu.',+ action: { label: 'Undo', onClick: () => void undoMove(projectId, taskId, previousSpaceId) },+ })+ } catch {+ toast.error({+ title: `Could not make the task ${visibility}`,+ description: 'Try again.',+ })+ } finally {+ actions.visibilityChanged()+ }+ },+ [todaySessionMenuLogic.actionTypes.sessionUpdated]: ({ sessionId }: { sessionId: string }) => {+ // A handoff changes the creator, so the controls must load again.+ if (sessionId === props.taskId) {+ actions.loadShareState()+ }+ },+ copyLink: async () => {+ await copyToClipboard(taskLink(props.taskId), 'task link')+ },+ })),++ afterMount(({ actions }) => {+ actions.loadShareState()+ }),+])