: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(today): add custom auto-archive days and a creator tag to space settings (#109347)
Shy Alter77acfebb9b74
diff --git a/products/tasks/frontend/spaces/SpaceAccess.tsx b/products/tasks/frontend/spaces/SpaceAccess.tsxindex ee18cc73acf5..1ffb0d8c645b 100644--- a/products/tasks/frontend/spaces/SpaceAccess.tsx+++ b/products/tasks/frontend/spaces/SpaceAccess.tsx@@ -26,7 +26,7 @@ import { membersLogic } from 'scenes/organization/membersLogic'import { spaceSceneLogic } from './spaceSceneLogic'export function SpaceAccess({ id }: { id: string }): JSX.Element | null {- const { space, savingSpace, members, membersLoading } = useValues(spaceSceneLogic({ id }))+ const { space, savingSpace, members, membersLoading, creatorId } = useValues(spaceSceneLogic({ id }))const { updateSpace, setMemberIds } = useActions(spaceSceneLogic({ id }))const { meFirstMembers } = useValues(membersLogic)const { ensureAllMembersLoaded } = useActions(membersLogic)@@ -87,9 +87,22 @@ export function SpaceAccess({ id }: { id: string }): JSX.Element | null {<ComboboxValue>{(userIds: number[]) => (<>- {userIds.map((userId) => (- <ComboboxChip key={userId}>{names.get(userId) ?? ''}</ComboboxChip>- ))}+ {userIds.map((userId) =>+ userId === creatorId ? (+ <ComboboxChip+ key={userId}+ showRemove={false}+ title={`${names.get(userId) ?? ''} (creator)`}+ >+ <span>{names.get(userId) ?? ''}</span>{' '}+ <Text render={<span />} size="xs" variant="muted">+ Creator+ </Text>+ </ComboboxChip>+ ) : (+ <ComboboxChip key={userId}>{names.get(userId) ?? ''}</ComboboxChip>+ )+ )}<ComboboxChipsInput placeholder="Add people" aria-label="Add people" /></>)}@@ -99,14 +112,16 @@ export function SpaceAccess({ id }: { id: string }): JSX.Element | null {<ComboboxEmpty>No one matches that name.</ComboboxEmpty><ComboboxList>{(userId: number) => (- <ComboboxItem key={userId} value={userId}>+ <ComboboxItem key={userId} value={userId} disabled={userId === creatorId}>{names.get(userId)}</ComboboxItem>)}</ComboboxList></ComboboxContent></Combobox>- <FieldDescription>Any member can add or remove people.</FieldDescription>+ <FieldDescription>+ Any member can add or remove people. The creator always stays a member.+ </FieldDescription></div>))}</div>diff --git a/products/tasks/frontend/spaces/SpaceSettings.tsx b/products/tasks/frontend/spaces/SpaceSettings.tsxindex fa3894cb7979..58d2eb8c5be2 100644--- a/products/tasks/frontend/spaces/SpaceSettings.tsx+++ b/products/tasks/frontend/spaces/SpaceSettings.tsx@@ -13,10 +13,14 @@ import {Button,Field,FieldDescription,+ FieldError,FieldGroup,FieldLabel,FieldTitle,Input,+ NumberFieldGroup,+ NumberFieldInput,+ NumberFieldRoot,Select,SelectContent,SelectItem,@@ -31,26 +35,38 @@ import { spaceLabel } from '~/layout/today/todaySpacesLogic'import { SpaceAccess } from './SpaceAccess'import { SpaceRepositories } from './SpaceRepositories'-import { spaceSceneLogic } from './spaceSceneLogic'+import {+ AUTO_ARCHIVE_MAX_DAYS,+ AUTO_ARCHIVE_MIN_DAYS,+ AUTO_ARCHIVE_PRESET_DAYS,+ AutoArchiveSelection,+ spaceSceneLogic,+} from './spaceSceneLogic'-const AUTO_ARCHIVE_DAYS = [1, 3, 7, 14, 30]+const AUTO_ARCHIVE_OPTIONS: { value: AutoArchiveSelection; label: string }[] = [+ { value: null, label: 'Never' },+ ...AUTO_ARCHIVE_PRESET_DAYS.map((days) => ({ value: days, label: `After ${days} ${days === 1 ? 'day' : 'days'}` })),+ { value: 'custom', label: 'Custom…' },+]export function SpaceSettings({ id }: { id: string }): JSX.Element | null {- const { space, savingSpace } = useValues(spaceSceneLogic({ id }))- const { updateSpace, deleteSpace } = useActions(spaceSceneLogic({ id }))+ const {+ space,+ savingSpace,+ autoArchiveSelection,+ autoArchiveDisabledReason,+ autoArchiveCustomDays,+ autoArchiveCustomError,+ autoArchiveCustomSaveDisabledReason,+ } = useValues(spaceSceneLogic({ id }))+ const { updateSpace, deleteSpace, setAutoArchiveSelection, setAutoArchiveCustomDays, saveAutoArchiveCustomDays } =+ useActions(spaceSceneLogic({ id }))const [name, setName] = useState(space?.name ?? '')if (!space) {return null}const defaultSpace = space.system_role !== null- const autoArchiveDays = space.auto_archive_after_days ?? null- const autoArchiveOptions = [- { value: null, label: 'Never' },- ...[...new Set([...AUTO_ARCHIVE_DAYS, ...(autoArchiveDays ? [autoArchiveDays] : [])])]- .sort((first, second) => first - second)- .map((days) => ({ value: days, label: `After ${days} ${days === 1 ? 'day' : 'days'}` })),- ]const trimmedName = name.trim()const renameDisabledReason = defaultSpace? 'Default spaces can’t be renamed'@@ -108,30 +124,82 @@ export function SpaceSettings({ id }: { id: string }): JSX.Element | null {</Field><Field><FieldLabel htmlFor="space-auto-archive">Auto-archive sessions</FieldLabel>- <div>- <Select- items={autoArchiveOptions}- value={autoArchiveDays}- onValueChange={(days: number | null) => updateSpace({ auto_archive_after_days: days })}- disabled={savingSpace}- >- <SelectTrigger id="space-auto-archive" data-attr="today-space-settings-auto-archive">- <SelectValue />- </SelectTrigger>- <SelectContent>- {autoArchiveOptions.map((option) => (- <SelectItem key={option.label} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>+ <Tooltip disabled={!autoArchiveDisabledReason || savingSpace}>+ <TooltipTrigger render={<div className="w-fit" />}>+ <Select<AutoArchiveSelection>+ items={AUTO_ARCHIVE_OPTIONS}+ value={autoArchiveSelection}+ onValueChange={(selection: AutoArchiveSelection) => setAutoArchiveSelection(selection)}+ disabled={!!autoArchiveDisabledReason}+ >+ <SelectTrigger id="space-auto-archive" data-attr="today-space-settings-auto-archive">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {AUTO_ARCHIVE_OPTIONS.map((option) => (+ <SelectItem key={option.label} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </TooltipTrigger>+ <TooltipContent>{autoArchiveDisabledReason}</TooltipContent>+ </Tooltip><FieldDescription>- Sessions with no activity for this long move to the archive. In shared spaces, only project admins- can change this.+ Sessions with no activity for this long move to the archive. New messages and session runs reset+ this period. Sessions being viewed, pinned, or actively running are not archived. In shared spaces,+ only project admins can change this.</FieldDescription></Field>+ {autoArchiveSelection === 'custom' && (+ <Field data-invalid={!!autoArchiveCustomError || undefined}>+ <FieldLabel htmlFor="space-auto-archive-custom-days">Days of inactivity</FieldLabel>+ <div className="flex flex-wrap gap-2">+ <NumberFieldRoot+ id="space-auto-archive-custom-days"+ className="w-24"+ value={autoArchiveCustomDays}+ onValueChange={(days: number | null) => setAutoArchiveCustomDays(days)}+ min={AUTO_ARCHIVE_MIN_DAYS}+ max={AUTO_ARCHIVE_MAX_DAYS}+ step={1}+ allowOutOfRange+ disabled={!!autoArchiveDisabledReason}+ >+ <NumberFieldGroup>+ <NumberFieldInput+ aria-invalid={!!autoArchiveCustomError || undefined}+ data-attr="today-space-settings-auto-archive-custom-days"+ />+ </NumberFieldGroup>+ </NumberFieldRoot>+ <Tooltip disabled={!autoArchiveCustomSaveDisabledReason || savingSpace}>+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ loading={savingSpace}+ disabled={!!autoArchiveCustomSaveDisabledReason}+ onClick={() => saveAutoArchiveCustomDays()}+ data-attr="today-space-settings-auto-archive-custom-save"+ />+ }+ >+ Save+ </TooltipTrigger>+ <TooltipContent>{autoArchiveCustomSaveDisabledReason}</TooltipContent>+ </Tooltip>+ </div>+ {autoArchiveCustomError ? (+ <FieldError>{autoArchiveCustomError}</FieldError>+ ) : (+ <FieldDescription>+ Choose a value from {AUTO_ARCHIVE_MIN_DAYS} to {AUTO_ARCHIVE_MAX_DAYS} days.+ </FieldDescription>+ )}+ </Field>+ )}<Field><FieldTitle>Delete space</FieldTitle><div>diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.test.ts b/products/tasks/frontend/spaces/spaceSceneLogic.test.tsindex 30f95efe0ac7..1c3348da6765 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.test.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.test.ts@@ -8,17 +8,21 @@ import { spaceNewSessionUrl, todaySpacesLogic } from '~/layout/today/todaySpacesimport { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { spaceSceneLogic } from './spaceSceneLogic'+import { AutoArchiveSelection, spaceSceneLogic } from './spaceSceneLogic'describe('spaceSceneLogic', () => {let sessionSpace = 'space-a'let starredIds: string[] = []let starRequests: { id: string; starred: boolean }[] = []+ let spacePatches: Record<string, unknown>[] = []+ let memberUpdates: number[][] = []beforeEach(() => {sessionSpace = 'space-a'starredIds = []starRequests = []+ spacePatches = []+ memberUpdates = []useMocks({get: {'/api/projects/:team_id/task_channels/': () => [@@ -31,6 +35,9 @@ describe('spaceSceneLogic', () => {id: params.id,name: String(params.id),system_role: null,+ channel_type: 'public',+ auto_archive_after_days: 7,+ created_by: { id: 7, uuid: 'user-7', first_name: 'Ada', email: '[email protected]' },github_integration: params.id === 'space-a' ? 3 : null,repositories: params.id === 'space-a' ? ['acme/api', 'acme/web'] : [],},@@ -57,11 +64,19 @@ describe('spaceSceneLogic', () => {return [200, {}]},},+ put: {+ '/api/projects/:team_id/task_channels/:id/members/': async ({ request }) => {+ const { user_ids } = (await request.json()) as { user_ids: number[] }+ memberUpdates.push(user_ids)+ return [200, user_ids.map((id) => ({ id }))]+ },+ },patch: {- '/api/projects/:team_id/task_channels/:id/': async ({ params, request }) => [- 200,- { id: params.id, system_role: null, ...((await request.json()) as Record<string, unknown>) },- ],+ '/api/projects/:team_id/task_channels/:id/': async ({ params, request }) => {+ const body = (await request.json()) as Record<string, unknown>+ spacePatches.push(body)+ return [200, { id: params.id, system_role: null, ...body }]+ },'/api/projects/:team_id/tasks/:id/': async ({ request }) => {const body = (await request.json()) as { channel?: string }sessionSpace = body.channel ?? sessionSpace@@ -188,4 +203,53 @@ describe('spaceSceneLogic', () => {expect(logic.values.composerFocusRequest).toBe(1)expect(other.values.composerFocusRequest).toBe(0)})++ it.each([+ ['a preset', 14, null, 14],+ ['a custom value', 'custom', 45, 45],+ ['never', null, null, null],+ ] as [string, AutoArchiveSelection, number | null, number | null][])(+ 'saves %s as the auto-archive days',+ async (_, selection, customDays, expected) => {+ const logic = spaceSceneLogic({ id: 'space-a' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setAutoArchiveSelection(selection)+ if (selection === 'custom') {+ logic.actions.setAutoArchiveCustomDays(customDays)+ logic.actions.saveAutoArchiveCustomDays()+ }+ await expectLogic(logic).toDispatchActions(['spaceSaved'])++ expect(spacePatches).toEqual([{ auto_archive_after_days: expected }])+ expect(logic.values.space?.auto_archive_after_days).toBe(expected)+ }+ )++ it.each([0, 366, 2.5, null])('never sends a custom auto-archive value of %s', async (days) => {+ const logic = spaceSceneLogic({ id: 'space-a' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setAutoArchiveSelection('custom')+ logic.actions.setAutoArchiveCustomDays(days)+ logic.actions.saveAutoArchiveCustomDays()+ await expectLogic(logic).toFinishAllListeners()++ expect(spacePatches).toEqual([])+ expect(logic.values.autoArchiveCustomSaveDisabledReason).not.toBeNull()+ })++ it('keeps the creator when the members picker drops them', async () => {+ const logic = spaceSceneLogic({ id: 'space-a' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setMemberIds([9])+ await expectLogic(logic).toDispatchActions(['setMemberIdsSuccess'])++ expect(memberUpdates).toEqual([[7, 9]])+ expect(logic.values.members.map((member) => member.id)).toEqual([7, 9])+ })})diff --git a/products/tasks/frontend/spaces/spaceSceneLogic.ts b/products/tasks/frontend/spaces/spaceSceneLogic.tsindex b95b2ae42fdb..b65358506196 100644--- a/products/tasks/frontend/spaces/spaceSceneLogic.ts+++ b/products/tasks/frontend/spaces/spaceSceneLogic.ts@@ -4,6 +4,7 @@ import { router, urlToAction } from 'kea-router'import { toast } from '@posthog/quill'+import { OrganizationMembershipLevel } from 'lib/constants'import { Scene } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -11,7 +12,7 @@ import { urls } from 'scenes/urls'import { todaySessionMenuLogic } from '~/layout/today/todaySessionMenuLogic'import { SPACE_COMPOSE_PARAM, spaceLabel, todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { TodayWorkGroup, groupByDay, sessionItem } from '~/layout/today/todayWorkItems'-import { Breadcrumb } from '~/types'+import { Breadcrumb, TeamPublicType, TeamType } from '~/types'import type { EmbeddedTaskComposerProps } from 'products/posthog_ai/frontend/api/runner'@@ -30,6 +31,23 @@ const SPACE_FEED_LIMIT = 50export type SpaceTab = 'feed' | 'settings'+export const AUTO_ARCHIVE_PRESET_DAYS = [1, 3, 7, 14, 30]+export const AUTO_ARCHIVE_MIN_DAYS = 1+export const AUTO_ARCHIVE_MAX_DAYS = 365++/** `null` turns auto-archive off, `'custom'` shows the number field. */+export type AutoArchiveSelection = number | null | 'custom'++export function autoArchiveDaysError(days: number | null): string | null {+ if (days === null) {+ return 'Enter a number of days'+ }+ if (!Number.isInteger(days) || days < AUTO_ARCHIVE_MIN_DAYS || days > AUTO_ARCHIVE_MAX_DAYS) {+ return `Enter a whole number from ${AUTO_ARCHIVE_MIN_DAYS} to ${AUTO_ARCHIVE_MAX_DAYS}`+ }+ return null+}+export interface SpaceSceneLogicProps {id: string}@@ -38,11 +56,19 @@ export type SpaceComposerRepositoryConfig = EmbeddedTaskComposerProps['initialRe// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface spaceSceneLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogiccurrentTeamId: number | null // teamLogicactiveTab: SpaceTab+ autoArchiveCustomDays: number | null+ autoArchiveCustomError: string | null+ autoArchiveCustomOpen: boolean+ autoArchiveCustomSaveDisabledReason: string | null+ autoArchiveDisabledReason: string | null+ autoArchiveSelection: AutoArchiveSelectionbreadcrumbs: Breadcrumb[]composerFocusRequest: numbercomposerRepositoryConfig: SpaceComposerRepositoryConfig+ creatorId: number | nullfeedGroups: TodayWorkGroup[]members: TaskUserBasicInfoApi[]membersLoading: boolean@@ -121,12 +147,21 @@ export interface spaceSceneLogicActions {space: ChannelDTOApi | nullpayload?: any}+ saveAutoArchiveCustomDays: () => {+ value: true+ }savingFinished: () => {value: true}sessionStarted: (sessionId: string) => {sessionId: string}+ setAutoArchiveCustomDays: (days: number | null) => {+ days: number | null+ }+ setAutoArchiveSelection: (selection: AutoArchiveSelection) => {+ selection: AutoArchiveSelection+ }setMemberIds: (userIds: number[]) => number[]setMemberIdsFailure: (error: string,@@ -157,6 +192,19 @@ export interface spaceSceneLogicActions {export interface spaceSceneLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ creatorId: (space: ChannelDTOApi | null) => number | null+ autoArchiveSelection: (space: ChannelDTOApi | null, autoArchiveCustomOpen: boolean) => AutoArchiveSelection+ autoArchiveDisabledReason: (+ space: ChannelDTOApi | null,+ currentTeam: TeamPublicType | TeamType | null,+ savingSpace: boolean+ ) => string | null+ autoArchiveCustomError: (autoArchiveCustomDays: number | null) => string | null+ autoArchiveCustomSaveDisabledReason: (+ autoArchiveDisabledReason: string | null,+ autoArchiveCustomDays: number | null,+ space: ChannelDTOApi | null+ ) => string | nullactiveTab: (location: { hash: string; pathname: string; search: string }) => SpaceTabfeedGroups: (sessions: TaskListItemApi[]) => TodayWorkGroup[]sessionsById: (sessions: TaskListItemApi[]) => Record<string, TaskListItemApi>@@ -177,7 +225,7 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([props({} as SpaceSceneLogicProps),key((props) => props.id),connect(() => ({- values: [teamLogic, ['currentTeamId']],+ values: [teamLogic, ['currentTeam', 'currentTeamId']],actions: [todaySessionMenuLogic, ['sessionUpdated'], todaySpacesLogic, ['loadSpaces', 'loadSpacesSuccess']],})),actions({@@ -188,6 +236,9 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([savingFinished: true,sessionStarted: (sessionId: string) => ({ sessionId }),focusComposer: true,+ setAutoArchiveSelection: (selection: AutoArchiveSelection) => ({ selection }),+ setAutoArchiveCustomDays: (days: number | null) => ({ days }),+ saveAutoArchiveCustomDays: true,}),loaders(({ props, values }) => ({space: [@@ -201,8 +252,11 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([[] as TaskUserBasicInfoApi[],{loadMembers: async () => await taskChannelsMembersRetrieve(String(values.currentTeamId), props.id),+ // The creator always stays a member, whatever the picker sends.setMemberIds: async (userIds: number[]) =>- await taskChannelsMembersUpdate(String(values.currentTeamId), props.id, { user_ids: userIds }),+ await taskChannelsMembersUpdate(String(values.currentTeamId), props.id, {+ user_ids: values.creatorId === null ? userIds : [...new Set([values.creatorId, ...userIds])],+ }),},],sessions: [@@ -254,8 +308,55 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([savingFinished: () => false,},],+ autoArchiveCustomOpen: [false, { setAutoArchiveSelection: (_, { selection }) => selection === 'custom' }],+ autoArchiveCustomDays: [+ null as number | null,+ {+ setAutoArchiveCustomDays: (_, { days }) => days,+ setAutoArchiveSelection: (state, { selection }) => (typeof selection === 'number' ? selection : state),+ loadSpaceSuccess: (_, { space }) => space?.auto_archive_after_days ?? null,+ },+ ],}),selectors({+ creatorId: [(s) => [s.space], (space: ChannelDTOApi | null): number | null => space?.created_by?.id ?? null],+ // A saved value outside the presets shows as custom.+ autoArchiveSelection: [+ (s) => [s.space, s.autoArchiveCustomOpen],+ (space: ChannelDTOApi | null, customOpen: boolean): AutoArchiveSelection => {+ const days = space?.auto_archive_after_days ?? null+ return customOpen || (days !== null && !AUTO_ARCHIVE_PRESET_DAYS.includes(days)) ? 'custom' : days+ },+ ],+ // Mirrors the backend rule: only project admins change auto-archive outside a personal space.+ autoArchiveDisabledReason: [+ (s) => [s.space, s.currentTeam, s.savingSpace],+ (+ space: ChannelDTOApi | null,+ currentTeam: TeamPublicType | TeamType | null,+ savingSpace: boolean+ ): string | null => {+ const level = currentTeam?.effective_membership_level ?? null+ if (+ space?.channel_type !== 'personal' &&+ (level === null || level < OrganizationMembershipLevel.Admin)+ ) {+ return 'Only project admins can change auto-archive for shared spaces'+ }+ return savingSpace ? 'Saving your last change' : null+ },+ ],+ autoArchiveCustomError: [+ (s) => [s.autoArchiveCustomDays],+ (days: number | null): string | null => (days === null ? null : autoArchiveDaysError(days)),+ ],+ autoArchiveCustomSaveDisabledReason: [+ (s) => [s.autoArchiveDisabledReason, s.autoArchiveCustomDays, s.space],+ (disabledReason: string | null, days: number | null, space: ChannelDTOApi | null): string | null =>+ disabledReason ??+ autoArchiveDaysError(days) ??+ (days === space?.auto_archive_after_days ? 'Change the number of days first' : null),+ ],activeTab: [() => [router.selectors.location],(location: { pathname: string }): SpaceTab =>@@ -295,6 +396,20 @@ export const spaceSceneLogic = kea<spaceSceneLogicType>([sessionUpdated: () => {actions.loadSessions()},+ setAutoArchiveSelection: ({ selection }) => {+ if (+ selection !== 'custom' &&+ !values.autoArchiveDisabledReason &&+ selection !== (values.space?.auto_archive_after_days ?? null)+ ) {+ actions.updateSpace({ auto_archive_after_days: selection })+ }+ },+ saveAutoArchiveCustomDays: () => {+ if (!values.autoArchiveCustomSaveDisabledReason) {+ actions.updateSpace({ auto_archive_after_days: values.autoArchiveCustomDays })+ }+ },// Open the new session like the web's new-session composer does, and list it for when the user comes back.sessionStarted: ({ sessionId }) => {actions.loadSessions()