: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
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { toast } from '@posthog/quill'
import { OrganizationMembershipLevel } from 'lib/constants'
import { writeToClipboard } from 'lib/utils/writeToClipboard'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { recentSourceOptions } from '~/layout/today/todayRecentFilters'
import { TodayRecentSort } from '~/layout/today/todayRecentOrder'
import { todaySessionMenuLogic } from '~/layout/today/todaySessionMenuLogic'
import { spaceLabel, todaySpacesLogic } from '~/layout/today/todaySpacesLogic'
import { TodayWorkItem, sessionItem } from '~/layout/today/todayWorkItems'
import { Breadcrumb, TeamPublicType, TeamType, UserType } from '~/types'
import { canvasesDestroy, canvasesList, canvasesPartialUpdate } from 'products/canvas/frontend/generated/api'
import type { CanvasApi } from 'products/canvas/frontend/generated/api.schemas'
import { ComposerSeed, composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'
import type { EmbeddedTaskComposerProps } from 'products/posthog_ai/frontend/api/runner'
import { type ArtifactPreviewKind, captureArtifactChipClicked } from 'products/posthog_ai/frontend/api/taskArtifacts'
import {
taskChannelsDestroy,
taskChannelsMembersRetrieve,
taskChannelsMembersUpdate,
taskChannelsPartialUpdate,
taskChannelsRetrieve,
taskChannelsStarCreate,
tasksList,
tasksPullRequestTitlesCreate,
} from '../generated/api'
import { ChannelDTOApi, PatchedChannelUpdateApi, TaskListItemApi, TaskUserBasicInfoApi } from '../generated/api.schemas'
import { SpaceCanvasSections, spaceCanvasSections } from './spaceCanvasDisplay'
import {
SpaceFeedFilters,
SpaceFeedGrouping,
SpaceFeedSection,
SpaceFeedType,
filterSpaceFeedCanvases,
filterSpaceFeedItems,
spaceFeedSections,
} from './spaceFeedEntries'
import { spaceFeedViewLogic } from './spaceFeedViewLogic'
import { sessionIdsWithPullRequests, spacePullRequests } from './taskPullRequests'
const SPACE_FEED_LIMIT = 50
export const SPACE_CANVASES_MAX = 200
export type SpaceTab = 'feed' | 'canvases' | 'settings'
export type SpaceFeedSourceStatus = 'hidden' | 'loading' | 'failed' | 'ready'
export interface SpaceFeedStatus {
sessions: SpaceFeedSourceStatus
canvases: SpaceFeedSourceStatus
}
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
}
const SPACE_NAME_MAX_LENGTH = 128
export function spaceNameError(name: string): string | null {
if (!name) {
return 'Enter a name'
}
if (name.length > SPACE_NAME_MAX_LENGTH) {
return `Use ${SPACE_NAME_MAX_LENGTH} characters or fewer`
}
return null
}
export interface SpaceSceneLogicProps {
id: string
}
export type SpaceComposerRepositoryConfig = EmbeddedTaskComposerProps['initialRepositoryConfig']
export function spaceComposerPanelId(spaceId: string): string {
return `space-${spaceId}`
}
/** A new session starts on the space's first repository. */
export function spaceComposerRepositoryConfig(space: ChannelDTOApi | null): SpaceComposerRepositoryConfig {
return space?.repositories.length
? { integrationId: space.github_integration ?? undefined, repository: space.repositories[0] }
: undefined
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceSceneLogicValues {
filters: SpaceFeedFilters // spaceFeedViewLogic
grouping: SpaceFeedGrouping // spaceFeedViewLogic
sort: TodayRecentSort // spaceFeedViewLogic
types: SpaceFeedType[] // spaceFeedViewLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamId: number | null // teamLogic
pinnedItems: TodayWorkItem[] // todaySpacesLogic
unreadSessionIds: Set<string> // todaySpacesLogic
user: UserType | null // userLogic
accessConfirmOpen: boolean
activeTab: SpaceTab
autoArchiveCustomDays: number | null
autoArchiveCustomError: string | null
autoArchiveCustomOpen: boolean
autoArchiveCustomSaveDisabledReason: string | null
autoArchiveDisabledReason: string | null
autoArchiveSelection: AutoArchiveSelection
breadcrumbs: Breadcrumb[]
canvasDeleteTarget: CanvasApi | null
canvasDeleting: boolean
canvasSections: SpaceCanvasSections
canvases: CanvasApi[] | null
canvasesLoading: boolean
canvasesUnavailable: boolean
composerFocusRequest: number
composerRepositoryConfig: SpaceComposerRepositoryConfig
creatorId: number | null
deleteDisabledReason: string | null
dominantRepository: string | null
feedItems: TodayWorkItem[]
feedRepositories: Record<string, string | null>
feedSections: SpaceFeedSection[]
feedSourceOptions: string[]
feedStatus: SpaceFeedStatus
filteredCanvases: CanvasApi[]
filteredFeedItems: TodayWorkItem[]
members: TaskUserBasicInfoApi[]
membersLoading: boolean
membersUnavailable: boolean
nameDraft: string | null
nameError: string | null
pendingCanvasIds: string[]
pendingName: string | null
pullRequestTitles: Record<string, string>
pullRequestTitlesLoading: boolean
renameDisabledReason: string | null
savingSpace: boolean
sessions: TaskListItemApi[]
sessionsById: Record<string, TaskListItemApi>
sessionsLoaded: boolean
sessionsLoading: boolean
sessionsUnavailable: boolean
space: ChannelDTOApi | null
spaceLoading: boolean
spaceMissing: boolean
spaceUnavailable: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceSceneLogicActions {
setSeed: (seed: ComposerSeed) => {
seed: ComposerSeed
} // composerSeedLogic
setTypes: (types: SpaceFeedType[]) => {
types: SpaceFeedType[]
} // spaceFeedViewLogic
sessionUpdated: (sessionId: string) => {
sessionId: string
} // todaySessionMenuLogic
loadPullRequestStates: (sessionIds: string[]) => {
sessionIds: string[]
} // todaySpacesLogic
loadSpaces: () => any // todaySpacesLogic
loadSpacesSuccess: (
spaces: ChannelDTOApi[],
payload?: any
) => {
payload?: any
spaces: ChannelDTOApi[]
} // todaySpacesLogic
loadTaskActivity: (_?: void | undefined) => void // todaySpacesLogic
applySuggestion: (prompt: string) => {
prompt: string
}
canvasDeleteFailed: () => {
value: true
}
canvasDeleteStarted: () => {
value: true
}
canvasDeleted: (canvasId: string) => {
canvasId: string
}
canvasPinFailed: (
canvasId: string,
pinnedAt: string | null
) => {
canvasId: string
pinnedAt: string | null
}
canvasPinRequested: (
canvasId: string,
pinned: boolean
) => {
canvasId: string
pinned: boolean
}
canvasSaved: (canvas: CanvasApi) => {
canvas: CanvasApi
}
commitName: () => {
value: true
}
confirmCanvasDelete: () => {
value: true
}
copyCanvasLink: (canvas: CanvasApi) => {
canvas: CanvasApi
}
deleteSpace: () => {
value: true
}
ensureCanvases: () => {
value: true
}
focusComposer: () => {
value: true
}
loadCanvases: () => any
loadCanvasesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadCanvasesSuccess: (
canvases: CanvasApi[],
payload?: any
) => {
canvases: CanvasApi[]
payload?: any
}
loadMembers: () => any
loadMembersFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadMembersSuccess: (
members: TaskUserBasicInfoApi[],
payload?: any
) => {
members: TaskUserBasicInfoApi[]
payload?: any
}
loadPullRequestTitles: () => any
loadPullRequestTitlesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPullRequestTitlesSuccess: (
pullRequestTitles: Record<string, string>,
payload?: any
) => {
pullRequestTitles: Record<string, string>
payload?: any
}
loadSessions: () => any
loadSessionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSessionsSuccess: (
sessions: TaskListItemApi[],
payload?: any
) => {
sessions: TaskListItemApi[]
payload?: any
}
loadSpace: () => any
loadSpaceFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSpaceSuccess: (
space: ChannelDTOApi | null,
payload?: any
) => {
space: ChannelDTOApi | null
payload?: any
}
reportArtifactChipClicked: (
kind: ArtifactPreviewKind,
inOverflow: boolean,
fileCount: number
) => {
fileCount: number
inOverflow: boolean
kind: ArtifactPreviewKind
}
saveAutoArchiveCustomDays: () => {
value: true
}
savingFinished: () => {
value: true
}
sessionStarted: (sessionId: string) => {
sessionId: string
}
setAccessConfirmOpen: (open: boolean) => {
open: boolean
}
setAutoArchiveCustomDays: (days: number | null) => {
days: number | null
}
setAutoArchiveSelection: (selection: AutoArchiveSelection) => {
selection: AutoArchiveSelection
}
setCanvasDeleteTarget: (canvas: CanvasApi | null) => {
canvas: CanvasApi | null
}
setMemberIds: (userIds: number[]) => number[]
setMemberIdsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
setMemberIdsSuccess: (
members: TaskUserBasicInfoApi[],
payload?: number[]
) => {
members: TaskUserBasicInfoApi[]
payload?: number[]
}
setNameDraft: (name: string | null) => {
name: string | null
}
setStarred: (starred: boolean) => {
starred: boolean
}
spaceSaved: (space: ChannelDTOApi) => {
space: ChannelDTOApi
}
toggleCanvasPinned: (canvasId: string) => {
canvasId: string
}
updateSpace: (patch: PatchedChannelUpdateApi) => {
patch: PatchedChannelUpdateApi
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface spaceSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
creatorId: (space: ChannelDTOApi | null) => number | null
nameError: (nameDraft: string | null) => string | null
renameDisabledReason: (space: ChannelDTOApi | null) => string | null
deleteDisabledReason: (space: ChannelDTOApi | null, savingSpace: boolean) => string | 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 | null
activeTab: (location: { hash: string; pathname: string; search: string }) => SpaceTab
canvasSections: (canvases: CanvasApi[] | null) => SpaceCanvasSections
feedItems: (sessions: TaskListItemApi[]) => TodayWorkItem[]
feedSourceOptions: (feedItems: TodayWorkItem[], filters: SpaceFeedFilters) => string[]
filteredFeedItems: (
feedItems: TodayWorkItem[],
filters: SpaceFeedFilters,
user: UserType | null,
unreadSessionIds: Set<string>,
pinnedItems: TodayWorkItem[]
) => TodayWorkItem[]
filteredCanvases: (
canvases: CanvasApi[] | null,
filters: SpaceFeedFilters,
user: UserType | null
) => CanvasApi[]
feedSections: (
filteredFeedItems: TodayWorkItem[],
filteredCanvases: CanvasApi[],
types: SpaceFeedType[],
sort: TodayRecentSort,
grouping: SpaceFeedGrouping
) => SpaceFeedSection[]
feedStatus: (
types: SpaceFeedType[],
sessionsLoaded: boolean,
sessionsUnavailable: boolean,
canvases: CanvasApi[] | null,
canvasesUnavailable: boolean
) => SpaceFeedStatus
dominantRepository: (sessions: TaskListItemApi[]) => string | null
feedRepositories: (
sessions: TaskListItemApi[],
dominantRepository: string | null
) => Record<string, string | null>
sessionsById: (sessions: TaskListItemApi[]) => Record<string, TaskListItemApi>
breadcrumbs: (space: ChannelDTOApi | null, arg: any) => Breadcrumb[]
composerRepositoryConfig: (space: ChannelDTOApi | null) => SpaceComposerRepositoryConfig
}
}
export type spaceSceneLogicType = MakeLogicType<
spaceSceneLogicValues,
spaceSceneLogicActions,
SpaceSceneLogicProps,
spaceSceneLogicMeta
>
export const spaceSceneLogic = kea<spaceSceneLogicType>([
path((id) => ['products', 'tasks', 'spaces', 'spaceSceneLogic', id]),
props({} as SpaceSceneLogicProps),
key((props) => props.id),
connect((props: SpaceSceneLogicProps) => ({
values: [
teamLogic,
['currentTeam', 'currentTeamId'],
todaySpacesLogic,
['pinnedItems', 'unreadSessionIds'],
userLogic,
['user'],
spaceFeedViewLogic,
['filters', 'grouping', 'sort', 'types'],
],
actions: [
spaceFeedViewLogic,
['setTypes'],
todaySessionMenuLogic,
['sessionUpdated'],
todaySpacesLogic,
['loadSpaces', 'loadSpacesSuccess', 'loadTaskActivity', 'loadPullRequestStates'],
composerSeedLogic({ panelId: spaceComposerPanelId(props.id) }),
['setSeed'],
],
})),
actions({
updateSpace: (patch: PatchedChannelUpdateApi) => ({ patch }),
setStarred: (starred: boolean) => ({ starred }),
deleteSpace: true,
spaceSaved: (space: ChannelDTOApi) => ({ space }),
savingFinished: true,
sessionStarted: (sessionId: string) => ({ sessionId }),
focusComposer: true,
applySuggestion: (prompt: string) => ({ prompt }),
setAutoArchiveSelection: (selection: AutoArchiveSelection) => ({ selection }),
setAutoArchiveCustomDays: (days: number | null) => ({ days }),
saveAutoArchiveCustomDays: true,
setNameDraft: (name: string | null) => ({ name }),
commitName: true,
ensureCanvases: true,
setAccessConfirmOpen: (open: boolean) => ({ open }),
copyCanvasLink: (canvas: CanvasApi) => ({ canvas }),
toggleCanvasPinned: (canvasId: string) => ({ canvasId }),
canvasPinRequested: (canvasId: string, pinned: boolean) => ({ canvasId, pinned }),
canvasPinFailed: (canvasId: string, pinnedAt: string | null) => ({ canvasId, pinnedAt }),
canvasSaved: (canvas: CanvasApi) => ({ canvas }),
setCanvasDeleteTarget: (canvas: CanvasApi | null) => ({ canvas }),
confirmCanvasDelete: true,
canvasDeleteStarted: true,
canvasDeleted: (canvasId: string) => ({ canvasId }),
canvasDeleteFailed: true,
reportArtifactChipClicked: (kind: ArtifactPreviewKind, inOverflow: boolean, fileCount: number) => ({
kind,
inOverflow,
fileCount,
}),
}),
loaders(({ props, values }) => ({
space: [
null as ChannelDTOApi | null,
{
loadSpace: async () =>
values.currentTeamId ? await taskChannelsRetrieve(String(values.currentTeamId), props.id) : null,
},
],
members: [
[] 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: values.creatorId === null ? userIds : [...new Set([values.creatorId, ...userIds])],
}),
},
],
sessions: [
[] as TaskListItemApi[],
{
loadSessions: async () => {
if (!values.currentTeamId) {
return []
}
const response = await tasksList(String(values.currentTeamId), {
channel: props.id,
ordering: '-last_activity_at',
basic: true,
limit: SPACE_FEED_LIMIT,
})
return response.results
},
},
],
pullRequestTitles: [
{} as Record<string, string>,
{
loadPullRequestTitles: async () => {
const sessionIds = [
...new Set(
spacePullRequests(values.feedItems)
.filter(({ pullRequest }) => !(pullRequest.url in values.pullRequestTitles))
.map(({ session }) => session.id)
),
]
if (!values.types.includes('pr') || !sessionIds.length || !values.currentTeamId) {
return values.pullRequestTitles
}
try {
const { titles } = await tasksPullRequestTitlesCreate(String(values.currentTeamId), {
ids: sessionIds,
})
return { ...values.pullRequestTitles, ...titles }
} catch {
return values.pullRequestTitles
}
},
},
],
// `null` until the first load, which waits until the Canvases type or tab shows.
canvases: [
null as CanvasApi[] | null,
{
loadCanvases: async () => {
if (!values.currentTeamId) {
return []
}
const canvases: CanvasApi[] = []
while (canvases.length < SPACE_CANVASES_MAX) {
const response = await canvasesList(String(values.currentTeamId), {
channel: props.id,
limit: Math.min(SPACE_FEED_LIMIT, SPACE_CANVASES_MAX - canvases.length),
offset: canvases.length,
})
canvases.push(...response.results)
if (!response.next || !response.results.length) {
break
}
}
return canvases
},
},
],
})),
reducers({
accessConfirmOpen: [false, { setAccessConfirmOpen: (_, { open }) => open, spaceSaved: () => false }],
sessionsUnavailable: [false, { loadSessions: () => false, loadSessionsFailure: () => true }],
sessionsLoaded: [false, { loadSessionsSuccess: () => true }],
canvasesUnavailable: [false, { loadCanvases: () => false, loadCanvasesFailure: () => true }],
membersUnavailable: [false, { loadMembers: () => false, loadMembersFailure: () => true }],
spaceUnavailable: [false, { loadSpace: () => false, loadSpaceFailure: () => true }],
spaceMissing: [
false,
{
loadSpace: () => false,
loadSpaceFailure: (_, { errorObject }) => errorObject?.status === 404,
},
],
space: {
spaceSaved: (_, { space }) => space,
setStarred: (state, { starred }) => (state ? { ...state, starred } : state),
// The sidebar can star or unstar this space too, so follow the shared list.
loadSpacesSuccess: (state, { spaces }) => {
const listed = state && spaces.find((space) => space.id === state.id)
return state && listed ? { ...state, starred: listed.starred } : state
},
},
canvases: {
canvasPinRequested: (state, { canvasId, pinned }) =>
state?.map((canvas) =>
canvas.id === canvasId ? { ...canvas, pinned_at: pinned ? new Date().toISOString() : null } : canvas
) ?? state,
canvasPinFailed: (state, { canvasId, pinnedAt }) =>
state?.map((canvas) => (canvas.id === canvasId ? { ...canvas, pinned_at: pinnedAt } : canvas)) ?? state,
canvasSaved: (state, { canvas: saved }) =>
state?.map((canvas) => (canvas.id === saved.id ? saved : canvas)) ?? state,
canvasDeleted: (state, { canvasId }) => state?.filter((canvas) => canvas.id !== canvasId) ?? state,
},
pendingCanvasIds: [
[] as string[],
{
canvasPinRequested: (state, { canvasId }) => [...state, canvasId],
canvasPinFailed: (state, { canvasId }) => state.filter((id) => id !== canvasId),
canvasSaved: (state, { canvas }) => state.filter((id) => id !== canvas.id),
},
],
canvasDeleteTarget: [
null as CanvasApi | null,
{ setCanvasDeleteTarget: (_, { canvas }) => canvas, canvasDeleted: () => null },
],
canvasDeleting: [
false,
{ canvasDeleteStarted: () => true, canvasDeleted: () => false, canvasDeleteFailed: () => false },
],
// Each request bumps the counter, so the composer focuses again even when it is already mounted.
composerFocusRequest: [0, { focusComposer: (state) => state + 1 }],
savingSpace: [
false,
{
updateSpace: () => true,
setStarred: () => true,
deleteSpace: () => true,
spaceSaved: () => false,
savingFinished: () => false,
},
],
// `null` shows the saved name. The draft stays after a failed rename, so the user can try again.
nameDraft: [null as string | null, { setNameDraft: (_, { name }) => name, loadSpaceSuccess: () => null }],
pendingName: [
null as string | null,
{
updateSpace: (state, { patch }) => patch.name ?? state,
spaceSaved: () => null,
savingFinished: () => null,
},
],
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],
nameError: [
(s) => [s.nameDraft],
(nameDraft: string | null): string | null => (nameDraft === null ? null : spaceNameError(nameDraft.trim())),
],
renameDisabledReason: [
(s) => [s.space],
(space: ChannelDTOApi | null): string | null =>
space?.system_role === 'general'
? 'The general space can’t be renamed.'
: space?.system_role === 'personal'
? 'Your personal space can’t be renamed.'
: null,
],
deleteDisabledReason: [
(s) => [s.space, s.savingSpace],
(space: ChannelDTOApi | null, savingSpace: boolean): string | null =>
space?.system_role === 'general'
? 'The general space can’t be deleted'
: space?.system_role === 'personal'
? 'Your personal space can’t be deleted'
: savingSpace
? 'Saving your last change'
: 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 =>
location.pathname.endsWith('/settings')
? 'settings'
: location.pathname.endsWith('/canvases')
? 'canvases'
: 'feed',
],
canvasSections: [
(s) => [s.canvases],
(canvases: CanvasApi[] | null): SpaceCanvasSections => spaceCanvasSections(canvases ?? []),
],
feedItems: [
(s) => [s.sessions],
(sessions: TaskListItemApi[]): TodayWorkItem[] =>
sessions.filter((task) => !task.archived).map(sessionItem),
],
feedSourceOptions: [
(s) => [s.feedItems, s.filters],
(feedItems: TodayWorkItem[], filters: SpaceFeedFilters): string[] =>
recentSourceOptions(feedItems, filters.sources),
],
filteredFeedItems: [
(s) => [s.feedItems, s.filters, s.user, s.unreadSessionIds, s.pinnedItems],
(
feedItems: TodayWorkItem[],
filters: SpaceFeedFilters,
user: UserType | null,
unreadSessionIds: Set<string>,
pinnedItems: TodayWorkItem[]
): TodayWorkItem[] =>
filterSpaceFeedItems(feedItems, filters, {
userId: user?.id ?? null,
unreadIds: unreadSessionIds,
pinnedIds: new Set(pinnedItems.map((item) => item.id)),
}),
],
filteredCanvases: [
(s) => [s.canvases, s.filters, s.user],
(canvases: CanvasApi[] | null, filters: SpaceFeedFilters, user: UserType | null): CanvasApi[] =>
filterSpaceFeedCanvases(canvases ?? [], filters, user?.id ?? null),
],
feedSections: [
(s) => [s.filteredFeedItems, s.filteredCanvases, s.types, s.sort, s.grouping],
(
filteredFeedItems: TodayWorkItem[],
filteredCanvases: CanvasApi[],
types: SpaceFeedType[],
sort: TodayRecentSort,
grouping: SpaceFeedGrouping
): SpaceFeedSection[] => spaceFeedSections(filteredFeedItems, filteredCanvases, types, sort, grouping),
],
feedStatus: [
(s) => [s.types, s.sessionsLoaded, s.sessionsUnavailable, s.canvases, s.canvasesUnavailable],
(
types: SpaceFeedType[],
sessionsLoaded: boolean,
sessionsUnavailable: boolean,
canvases: CanvasApi[] | null,
canvasesUnavailable: boolean
): SpaceFeedStatus => ({
sessions: !types.some((type) => type !== 'canvas')
? 'hidden'
: sessionsUnavailable
? 'failed'
: sessionsLoaded
? 'ready'
: 'loading',
canvases: !types.includes('canvas')
? 'hidden'
: canvasesUnavailable
? 'failed'
: canvases !== null
? 'ready'
: 'loading',
}),
],
// Like PostHog Desktop, a card names its repository only when it differs from the space's most used one.
// A tie goes to the repository of the most recently active session.
dominantRepository: [
(s) => [s.sessions],
(sessions: TaskListItemApi[]): string | null => {
const counts = new Map<string, number>()
for (const task of sessions) {
if (!task.archived && task.repository) {
counts.set(task.repository, (counts.get(task.repository) ?? 0) + 1)
}
}
let dominant: string | null = null
for (const [repository, count] of counts) {
if (dominant === null || count > (counts.get(dominant) ?? 0)) {
dominant = repository
}
}
return dominant
},
],
feedRepositories: [
(s) => [s.sessions, s.dominantRepository],
(sessions: TaskListItemApi[], dominantRepository: string | null): Record<string, string | null> =>
Object.fromEntries(
sessions.map((task) => [
task.id,
task.repository && task.repository !== dominantRepository ? task.repository : null,
])
),
],
sessionsById: [
(s) => [s.sessions],
(sessions: TaskListItemApi[]): Record<string, TaskListItemApi> =>
Object.fromEntries(sessions.map((task) => [task.id, task])),
],
breadcrumbs: [
(s) => [s.space, (_, props) => props],
(space: ChannelDTOApi | null, props: SpaceSceneLogicProps): Breadcrumb[] => [
{
key: [Scene.TaskSpace, props.id],
name: space ? spaceLabel(space) : 'Space',
path: urls.taskSpace(props.id),
iconType: 'task',
},
],
],
composerRepositoryConfig: [
(s) => [s.space],
(space: ChannelDTOApi | null): SpaceComposerRepositoryConfig => spaceComposerRepositoryConfig(space),
],
}),
listeners(({ actions, props, values }) => ({
loadSessions: () => {
actions.loadTaskActivity()
},
loadSessionsSuccess: ({ sessions }) => {
actions.loadPullRequestStates(sessionIdsWithPullRequests(sessions))
actions.loadPullRequestTitles()
},
sessionUpdated: () => {
actions.loadSessions()
},
applySuggestion: ({ prompt }) => {
actions.setSeed({ prompt, autoSubmit: false })
actions.focusComposer()
},
reportArtifactChipClicked: ({ kind, inOverflow, fileCount }) => {
captureArtifactChipClicked({ kind, inOverflow, fileCount, surface: 'space_feed' })
},
setTypes: () => {
actions.ensureCanvases()
actions.loadPullRequestTitles()
},
// A failed load leaves `null`, so showing the type or the tab again retries it.
ensureCanvases: () => {
const shown = values.types.includes('canvas') || values.activeTab === 'canvases'
if (shown && values.canvases === null && !values.canvasesLoading) {
actions.loadCanvases()
}
},
copyCanvasLink: async ({ canvas }) => {
const outcome = await writeToClipboard(canvas.url)
if (outcome === 'copied') {
toast.success({ title: 'Link copied' })
} else {
toast.error({ title: 'Couldn’t copy the link. Open the canvas and copy it from the address bar.' })
}
},
toggleCanvasPinned: async ({ canvasId }) => {
const canvas = values.canvases?.find(({ id }) => id === canvasId)
if (!canvas || values.pendingCanvasIds.includes(canvasId)) {
return
}
const pinned = !canvas.pinned_at
actions.canvasPinRequested(canvasId, pinned)
try {
actions.canvasSaved(await canvasesPartialUpdate(String(values.currentTeamId), canvasId, { pinned }))
} catch {
toast.error({ title: `Couldn’t ${pinned ? 'pin' : 'unpin'} this canvas. Try again.` })
actions.canvasPinFailed(canvasId, canvas.pinned_at ?? null)
}
},
confirmCanvasDelete: async () => {
const target = values.canvasDeleteTarget
if (!target || values.canvasDeleting) {
return
}
actions.canvasDeleteStarted()
try {
await canvasesDestroy(String(values.currentTeamId), target.id)
actions.canvasDeleted(target.id)
toast.success({ title: 'Canvas deleted' })
} catch (error) {
toast.error({
title: (error as { detail?: string }).detail ?? 'Couldn’t delete this canvas. Try again.',
})
actions.canvasDeleteFailed()
}
},
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 })
}
},
// Runs on blur and on Enter, so a rename that is already in flight is not sent twice.
commitName: () => {
const { nameDraft, nameError, pendingName, renameDisabledReason, space } = values
if (nameDraft === null || nameError || renameDisabledReason || !space) {
return
}
const name = nameDraft.trim()
if (name === pendingName) {
return
}
if (name === space.name) {
actions.setNameDraft(null)
return
}
actions.updateSpace({ name })
},
// 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()
router.actions.push(urls.aiTask(sessionId))
},
loadSpaceSuccess: ({ space }) => {
if (space?.channel_type === 'private') {
actions.loadMembers()
}
},
spaceSaved: ({ space }) => {
if (space.channel_type === 'private') {
actions.loadMembers()
}
},
setMemberIdsFailure: ({ errorObject }) => {
toast.error({
title: (errorObject as { detail?: string })?.detail ?? 'Couldn’t update the members. Try again.',
})
actions.loadMembers()
},
updateSpace: async ({ patch }) => {
try {
actions.spaceSaved(await taskChannelsPartialUpdate(String(values.currentTeamId), props.id, patch))
if (patch.name !== undefined) {
// The backend normalizes the name, so show what it saved.
actions.setNameDraft(null)
}
actions.loadSpaces()
} catch (error) {
toast.error({ title: (error as { detail?: string }).detail ?? 'Couldn’t save this change. Try again.' })
actions.savingFinished()
}
},
setStarred: async ({ starred }) => {
try {
await taskChannelsStarCreate(String(values.currentTeamId), props.id, { starred })
actions.savingFinished()
actions.loadSpaces()
} catch {
toast.error({ title: `Couldn’t ${starred ? 'star' : 'unstar'} this space. Try again.` })
actions.loadSpace()
actions.savingFinished()
}
},
deleteSpace: async () => {
try {
await taskChannelsDestroy(String(values.currentTeamId), props.id)
toast.success({ title: 'Space deleted' })
actions.loadSpaces()
router.actions.push(urls.projectHomepage())
} catch (error) {
toast.error({
title: (error as { detail?: string }).detail ?? 'Couldn’t delete this space. Try again.',
})
actions.savingFinished()
}
},
})),
urlToAction(({ actions, props }) => ({
[urls.taskSpaceCanvases(':id')]: ({ id }) => {
if (id === props.id) {
actions.ensureCanvases()
}
},
})),
afterMount(({ actions }) => {
actions.loadSpace()
actions.loadSessions()
actions.ensureCanvases()
}),
])