Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, ref, shallowRef, watch } from 'vue'
3 :
4 : import { useCurrentUserAccess } from '@/platform/auth/currentUserAccess'
5 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
6 : import {
7 : desktopHostUser,
8 : isDesktopHostSignedIn,
9 : requestDesktopHostWorkspaceSwitch
10 : } from '@/platform/auth/desktopHost/desktopHostSession'
11 : import { SessionRevokedError } from '@/platform/auth/session/sessionRevokedError'
12 : import { trackSsoWorkspaceLanded } from '@/platform/auth/sso/ssoTelemetry'
13 : import { ensureSessionCookie } from '@/platform/auth/session/sessionCookieAccess'
14 : import { isCloud } from '@/platform/distribution/types'
15 : import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants'
16 : import { clearPreservedQuery } from '@/platform/navigation/preservedQueryManager'
17 : import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces'
18 : import { reportError } from '@comfyorg/telemetry/reportError'
19 : import {
20 : clearWorkflowRestoreState,
21 : prepareWorkflowWorkspaceTransition
22 : } from '@/platform/workflow/persistence/base/storageIO'
23 : import { provideTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStoreAccess'
24 : import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore'
25 :
26 : import type {
27 : CurrentWorkspaceResponse,
28 : ListMembersParams,
29 : ListWorkspacesResponse,
30 : Member,
31 : PendingInvite as ApiPendingInvite,
32 : WorkspaceWithRole
33 : } from '@/platform/workspace/api/workspaceApi'
34 : import { workspaceApi } from '@/platform/workspace/api/workspaceApi'
35 : import {
36 : NoWorkspaceAccessError,
37 : WorkspaceApiError
38 : } from '@/platform/remote/ingest/ingestApiError'
39 :
40 : export interface WorkspaceMember {
41 : id: string
42 : name: string
43 : email: string
44 : joinDate: Date
45 : role: 'owner' | 'member'
46 : isOriginalOwner: boolean
47 : creditsUsedThisMonth?: number
48 : monthlyCreditLimit?: number | null
49 : }
50 :
51 : export interface WorkspacePendingInvite {
52 : id: string
53 : email: string
54 : inviteDate: Date
55 : expiryDate: Date
56 : /**
57 : * Invite token for building shareable invite links.
58 : * Absent/empty for expired invites (the backend omits it).
59 : */
60 : token?: string
61 : }
62 :
63 : interface WorkspaceState extends WorkspaceWithRole {
64 : members: WorkspaceMember[]
65 : membersLoaded: boolean
66 : totalMembers?: number
67 : pendingInvites: WorkspacePendingInvite[]
68 : pendingInvitesLoaded: boolean
69 : }
70 :
71 : type InitState = 'uninitialized' | 'loading' | 'ready' | 'error'
72 :
73 0 : function mapApiMemberToWorkspaceMember(member: Member): WorkspaceMember {
74 0 : return {
75 : id: member.id,
76 : name: member.name,
77 : email: member.email,
78 : joinDate: new Date(member.joined_at),
79 : role: member.role,
80 : isOriginalOwner: member.is_original_owner,
81 : creditsUsedThisMonth: member.credits_used_this_month,
82 : monthlyCreditLimit: member.monthly_credit_limit
83 : }
84 : }
85 :
86 0 : function mapApiInviteToPendingInvite(
87 : invite: ApiPendingInvite
88 : ): WorkspacePendingInvite {
89 0 : return {
90 : id: invite.id,
91 : email: invite.email,
92 : inviteDate: new Date(invite.invited_at),
93 : expiryDate: new Date(invite.expires_at),
94 : token: invite.token
95 : }
96 : }
97 :
98 49 : function createWorkspaceState(workspace: WorkspaceWithRole): WorkspaceState {
99 49 : return {
100 : ...workspace,
101 : members: [],
102 : membersLoaded: false,
103 : pendingInvites: [],
104 : pendingInvitesLoaded: false
105 : }
106 : }
107 :
108 : /**
109 : * Builds workspace state from GET /api/workspaces/current — the single
110 : * workspace bound to an API-key credential. The response carries no
111 : * membership timestamps (only sortWorkspaces reads them, and a one-entry list
112 : * never sorts) and may omit role, which fails closed to member so owner-only
113 : * billing actions stay hidden rather than 403 on click.
114 : */
115 0 : function createWorkspaceStateFromCredential(
116 : current: CurrentWorkspaceResponse
117 : ): WorkspaceState {
118 0 : return createWorkspaceState({
119 : id: current.id,
120 : name: current.name,
121 : type: current.type,
122 : role: current.role ?? 'member',
123 : created_at: '',
124 : joined_at: ''
125 : })
126 : }
127 :
128 17 : export function sortWorkspaces<T extends WorkspaceWithRole>(list: T[]): T[] {
129 17 : return [...list].sort((a, b) => {
130 32 : if (a.type === 'personal') return -1
131 32 : if (b.type === 'personal') return 1
132 32 : const dateA = a.role === 'owner' ? a.created_at : a.joined_at
133 32 : const dateB = b.role === 'owner' ? b.created_at : b.joined_at
134 32 : return dateA.localeCompare(dateB)
135 : })
136 : }
137 :
138 4 : function getLastWorkspaceId(): string | null {
139 4 : try {
140 4 : return localStorage.getItem(WORKSPACE_STORAGE_KEYS.LAST_WORKSPACE_ID)
141 : } catch {
142 0 : return null
143 : }
144 : }
145 :
146 6 : function setLastWorkspaceId(workspaceId: string): void {
147 6 : try {
148 6 : localStorage.setItem(WORKSPACE_STORAGE_KEYS.LAST_WORKSPACE_ID, workspaceId)
149 : } catch {
150 0 : console.warn('Failed to persist last workspace ID to localStorage')
151 : }
152 : }
153 :
154 : /** The workspace a switch reloads into, read once by the next initialization. */
155 : function setSwitchTargetId(workspaceId: string): void {
156 : try {
157 : sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.SWITCH_TARGET_ID, workspaceId)
158 : } catch {
159 : console.warn('Failed to persist the workspace switch target')
160 : }
161 : }
162 :
163 18 : function takeSwitchTargetId(): string | null {
164 18 : try {
165 18 : const id = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.SWITCH_TARGET_ID)
166 18 : sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.SWITCH_TARGET_ID)
167 18 : return id
168 : } catch {
169 0 : return null
170 : }
171 : }
172 :
173 0 : function clearLastWorkspaceId(): void {
174 0 : try {
175 0 : localStorage.removeItem(WORKSPACE_STORAGE_KEYS.LAST_WORKSPACE_ID)
176 : } catch {
177 0 : console.warn('Failed to clear last workspace ID from localStorage')
178 : }
179 : }
180 :
181 : /** An ingest deployed before `can_create_workspace` omits it; only an explicit false refuses. */
182 : type ListedWorkspaces = Omit<ListWorkspacesResponse, 'can_create_workspace'> &
183 : Partial<Pick<ListWorkspacesResponse, 'can_create_workspace'>> & {
184 : /** The SSO organization's workspace a sign-in opens (cloud#12614). */
185 : default_workspace_id?: string
186 : }
187 :
188 : type CreationDeniedReason = NonNullable<
189 : NonNullable<ListWorkspacesResponse['denied_reasons']>['can_create_workspace']
190 : >
191 :
192 2356 : const CREATION_DENIED_REASONS: Record<CreationDeniedReason, true> = {
193 : organization_managed: true,
194 : owned_workspace_limit: true
195 : }
196 :
197 0 : function isCreationDeniedReason(
198 : reason: string
199 : ): reason is CreationDeniedReason {
200 0 : return Object.hasOwn(CREATION_DENIED_REASONS, reason)
201 : }
202 :
203 17 : function parseCreationDeniedReason(
204 : reason: string | undefined
205 : ): CreationDeniedReason | undefined {
206 17 : return reason !== undefined && isCreationDeniedReason(reason)
207 : ? reason
208 : : undefined
209 : }
210 :
211 4 : function reportSsoLanding(
212 : { default_workspace_id }: ListedWorkspaces,
213 : workspaceId: string
214 : ): void {
215 4 : trackSsoWorkspaceLanded(
216 : !!default_workspace_id && workspaceId === default_workspace_id
217 : )
218 : }
219 :
220 2356 : const MAX_INIT_RETRIES = 3
221 2356 : const BASE_RETRY_DELAY_MS = 1000
222 2356 : const INIT_READ_WITHOUT_STATUS_RETRY = { skipStatusRetry: true }
223 :
224 2356 : const MAX_SESSION_REVOKED_RETRIES = 1
225 :
226 13 : function initRetryDelay(
227 : error: unknown,
228 : attempt: number,
229 : sessionRevokedRetries: number
230 : ): number | null {
231 13 : if (attempt >= MAX_INIT_RETRIES) return null
232 13 : if (!(error instanceof SessionRevokedError)) {
233 13 : return BASE_RETRY_DELAY_MS * Math.pow(2, attempt)
234 : }
235 0 : if (error.code === 'TOKEN_REVOKED') return null
236 0 : if (sessionRevokedRetries >= MAX_SESSION_REVOKED_RETRIES) return null
237 0 : return BASE_RETRY_DELAY_MS
238 : }
239 :
240 2356 : export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => {
241 2355 : const { flags } = useFeatureFlags()
242 2355 : const initState = ref<InitState>('uninitialized')
243 2355 : const workspaces = shallowRef<WorkspaceState[]>([])
244 2355 : const mutableActiveWorkspaceId = ref<string | null>(null)
245 2355 : const activeWorkspaceId = computed(() => mutableActiveWorkspaceId.value)
246 2355 : const error = ref<Error | null>(null)
247 :
248 2355 : const isCreating = ref(false)
249 2355 : const isDeleting = ref(false)
250 2355 : const isSwitching = ref(false)
251 2355 : const isFetchingWorkspaces = ref(false)
252 2355 : const mutableWorkspaceTransitionGeneration = ref(0)
253 2355 : const workspaceTransitionGeneration = computed(
254 : () => mutableWorkspaceTransitionGeneration.value
255 : )
256 2355 : const identityGeneration = ref(0)
257 2355 : let initializationPromise: Promise<void> | null = null
258 2355 : let hostChangedWhileLoading = false
259 2355 : let pendingWorkspaceSwitch: Promise<void> | null = null
260 :
261 70 : function isStaleIdentity(generation: number): boolean {
262 70 : return generation !== identityGeneration.value
263 : }
264 :
265 14 : function isStaleWorkspace(generation: number, workspaceId: string): boolean {
266 14 : return (
267 : isStaleIdentity(generation) || activeWorkspaceId.value !== workspaceId
268 : )
269 : }
270 :
271 2355 : const activeWorkspace = computed(
272 : () => workspaces.value.find((w) => w.id === activeWorkspaceId.value) ?? null
273 : )
274 :
275 2355 : const personalWorkspace = computed(
276 : () => workspaces.value.find((w) => w.type === 'personal') ?? null
277 : )
278 :
279 2355 : const isInPersonalWorkspace = computed(
280 : () => activeWorkspace.value?.type === 'personal'
281 : )
282 :
283 2355 : const sharedWorkspaces = computed(() =>
284 : workspaces.value.filter((w) => w.type !== 'personal')
285 : )
286 :
287 2355 : const serverRefusesCreation = ref(false)
288 2355 : const creationDeniedReason = ref<CreationDeniedReason>()
289 2355 : const maxOwnedWorkspaces = ref<number>()
290 :
291 2355 : const canCreateWorkspace = computed(() => !serverRefusesCreation.value)
292 :
293 2355 : const createWorkspaceRefusal = computed<
294 : CreationDeniedReason | 'unknown' | null
295 : >(() =>
296 : serverRefusesCreation.value
297 : ? (creationDeniedReason.value ?? 'unknown')
298 : : null
299 : )
300 :
301 17 : function applyWorkspaceList(response: ListedWorkspaces): void {
302 17 : workspaces.value = sortWorkspaces(
303 : response.workspaces.map(createWorkspaceState)
304 : )
305 17 : serverRefusesCreation.value = response.can_create_workspace === false
306 17 : creationDeniedReason.value = parseCreationDeniedReason(
307 : response.denied_reasons?.can_create_workspace
308 : )
309 17 : maxOwnedWorkspaces.value = response.max_owned_workspaces
310 : }
311 :
312 2355 : const members = computed<WorkspaceMember[]>(
313 : () => activeWorkspace.value?.members ?? []
314 : )
315 :
316 2355 : const membersLoaded = computed(
317 : () => activeWorkspace.value?.membersLoaded ?? false
318 : )
319 :
320 : // The active workspace's original owner (creator). Prefers the
321 : // `is_original_owner` flag; without it, falls back to the earliest-joined
322 : // owner — never a plain member, who must stay role-changeable.
323 2355 : const originalOwnerId = computed<string | null>(() => {
324 0 : const flagged = members.value.find((m) => m.isOriginalOwner)
325 0 : if (flagged) return flagged.id
326 0 : const owners = members.value.filter((m) => m.role === 'owner')
327 0 : if (owners.length === 0) return null
328 0 : return owners.reduce((earliest, m) =>
329 : m.joinDate < earliest.joinDate ? m : earliest
330 : ).id
331 : })
332 :
333 2355 : const pendingInvites = computed<WorkspacePendingInvite[]>(
334 : () => activeWorkspace.value?.pendingInvites ?? []
335 : )
336 :
337 2355 : const pendingInvitesLoaded = computed(
338 : () => activeWorkspace.value?.pendingInvitesLoaded ?? false
339 : )
340 :
341 2355 : const workspaceId = computed(() => activeWorkspace.value?.id ?? null)
342 :
343 2355 : const workspaceName = computed(() => activeWorkspace.value?.name ?? '')
344 :
345 7 : function updateWorkspace(
346 : workspaceId: string,
347 : updates: Partial<WorkspaceState>
348 : ) {
349 7 : const index = workspaces.value.findIndex((w) => w.id === workspaceId)
350 7 : if (index === -1) return
351 :
352 : const current = workspaces.value[index]
353 7 : const updated = { ...current, ...updates }
354 7 : workspaces.value = [
355 : ...workspaces.value.slice(0, index),
356 : updated,
357 : ...workspaces.value.slice(index + 1)
358 : ]
359 : }
360 :
361 0 : function updateActiveWorkspace(updates: Partial<WorkspaceState>) {
362 0 : if (!activeWorkspaceId.value) return
363 0 : updateWorkspace(activeWorkspaceId.value, updates)
364 : }
365 :
366 : /**
367 : * Initialize the workspace store.
368 : * Fetches workspaces and resolves the active workspace from session/localStorage.
369 : * Delegates token management to workspaceAuthStore.
370 : * Retries on transient failures with exponential backoff.
371 : * Call once on app boot.
372 : */
373 18 : async function performInitialization(): Promise<void> {
374 18 : const generation = identityGeneration.value
375 18 : initState.value = 'loading'
376 18 : isFetchingWorkspaces.value = true
377 18 : error.value = null
378 :
379 18 : const workspaceAuthStore = useWorkspaceAuthStore()
380 18 : const isApiKeySession = useCurrentUserAccess().isApiKeyLogin.value
381 18 : const switchTargetId = takeSwitchTargetId()
382 18 : const tabWorkspaceId = workspaceAuthStore.bootTabWorkspaceId
383 :
384 18 : let sessionRevokedRetries = 0
385 18 : for (let attempt = 0; attempt <= MAX_INIT_RETRIES; attempt++) {
386 31 : try {
387 31 : if (isDesktopHostSignedIn()) {
388 26 : const response = await workspaceApi.list(
389 : INIT_READ_WITHOUT_STATUS_RETRY
390 : )
391 26 : if (isStaleIdentity(generation)) return
392 13 : applyWorkspaceList(response)
393 26 : const hostWorkspaceId = desktopHostUser.value?.workspaceId
394 26 : if (!workspaces.value.some((w) => w.id === hostWorkspaceId)) {
395 0 : throw new NoWorkspaceAccessError('Desktop workspace not available')
396 : }
397 26 : mutableActiveWorkspaceId.value = hostWorkspaceId ?? null
398 26 : initState.value = 'ready'
399 26 : isFetchingWorkspaces.value = false
400 26 : return
401 : }
402 :
403 7 : if (isApiKeySession) {
404 0 : const current = await workspaceApi.getCurrentWorkspace(
405 : INIT_READ_WITHOUT_STATUS_RETRY
406 : )
407 0 : if (isStaleIdentity(generation)) return
408 0 : workspaces.value = [createWorkspaceStateFromCredential(current)]
409 0 : mutableActiveWorkspaceId.value = current.id
410 0 : initState.value = 'ready'
411 0 : isFetchingWorkspaces.value = false
412 0 : return
413 : }
414 :
415 5 : await ensureSessionCookie()
416 7 : if (isStaleIdentity(generation)) return
417 :
418 : const hasValidSession = workspaceAuthStore.initializeFromSession()
419 :
420 31 : if (hasValidSession && workspaceAuthStore.currentWorkspace) {
421 0 : const response = await workspaceApi.list(
422 : INIT_READ_WITHOUT_STATUS_RETRY
423 : )
424 0 : if (isStaleIdentity(generation)) return
425 0 : applyWorkspaceList(response)
426 :
427 0 : if (workspaces.value.length === 0) {
428 0 : throw new NoWorkspaceAccessError('No workspaces available')
429 : }
430 :
431 0 : const sessionWorkspaceId = workspaceAuthStore.currentWorkspace.id
432 : const sessionWorkspaceExists = workspaces.value.some(
433 : (w) => w.id === sessionWorkspaceId
434 : )
435 :
436 0 : if (sessionWorkspaceExists) {
437 0 : mutableActiveWorkspaceId.value = sessionWorkspaceId
438 0 : reportSsoLanding(response, sessionWorkspaceId)
439 0 : initState.value = 'ready'
440 0 : isFetchingWorkspaces.value = false
441 0 : return
442 : }
443 :
444 : if (isCloud) clearWorkflowRestoreState()
445 0 : workspaceAuthStore.clearWorkspaceContext()
446 :
447 : const personal = workspaces.value.find((w) => w.type === 'personal')
448 0 : const fallbackWorkspaceId = personal?.id ?? workspaces.value[0].id
449 :
450 0 : await workspaceAuthStore.switchWorkspace(fallbackWorkspaceId)
451 :
452 0 : if (isStaleIdentity(generation)) return
453 :
454 0 : mutableActiveWorkspaceId.value = fallbackWorkspaceId
455 0 : setLastWorkspaceId(fallbackWorkspaceId)
456 0 : reportSsoLanding(response, fallbackWorkspaceId)
457 0 : initState.value = 'ready'
458 0 : isFetchingWorkspaces.value = false
459 0 : return
460 : }
461 :
462 5 : const response: ListedWorkspaces = await workspaceApi.list(
463 : INIT_READ_WITHOUT_STATUS_RETRY
464 : )
465 4 : if (isStaleIdentity(generation)) return
466 4 : applyWorkspaceList(response)
467 :
468 4 : if (workspaces.value.length === 0) {
469 0 : throw new NoWorkspaceAccessError('No workspaces available')
470 : }
471 :
472 4 : const listed = (id: string | null | undefined): id is string =>
473 : !!id && workspaces.value.some((w) => w.id === id)
474 31 : let targetWorkspaceId: string | null =
475 : [
476 : switchTargetId,
477 : tabWorkspaceId,
478 : response.default_workspace_id,
479 : getLastWorkspaceId()
480 : ].find(listed) ?? null
481 :
482 31 : if (!targetWorkspaceId) {
483 : const personal = workspaces.value.find((w) => w.type === 'personal')
484 4 : targetWorkspaceId = personal?.id ?? workspaces.value[0].id
485 : }
486 :
487 4 : await workspaceAuthStore.switchWorkspace(targetWorkspaceId)
488 :
489 4 : if (isStaleIdentity(generation)) return
490 :
491 4 : mutableActiveWorkspaceId.value = targetWorkspaceId
492 4 : setLastWorkspaceId(targetWorkspaceId)
493 4 : reportSsoLanding(response, targetWorkspaceId)
494 :
495 4 : initState.value = 'ready'
496 4 : isFetchingWorkspaces.value = false
497 4 : return
498 : } catch (e) {
499 13 : if (isStaleIdentity(generation)) return
500 13 : const isNoWorkspacesError =
501 : e instanceof NoWorkspaceAccessError &&
502 : (e.status === undefined || flags.ssoEnabled)
503 13 : const isPermanentCredentialError =
504 : isApiKeySession &&
505 : e instanceof WorkspaceApiError &&
506 : e.status !== undefined &&
507 : e.status >= 400 &&
508 : e.status < 500 &&
509 : e.status !== 408 &&
510 : e.status !== 429
511 :
512 13 : const delay = initRetryDelay(e, attempt, sessionRevokedRetries)
513 13 : if (
514 : isNoWorkspacesError ||
515 : isPermanentCredentialError ||
516 : delay === null
517 : ) {
518 0 : error.value = e instanceof Error ? e : new Error('Unknown error')
519 0 : initState.value = 'error'
520 0 : isFetchingWorkspaces.value = false
521 0 : throw e
522 : }
523 :
524 13 : if (e instanceof SessionRevokedError) sessionRevokedRetries++
525 13 : const errorMessage = e instanceof Error ? e.message : String(e)
526 13 : console.warn(
527 : `[teamWorkspaceStore] Init failed (attempt ${attempt + 1}/${MAX_INIT_RETRIES + 1}), retrying in ${delay}ms: ${errorMessage}`
528 : )
529 13 : await new Promise((resolve) => setTimeout(resolve, delay))
530 13 : if (isStaleIdentity(generation)) return
531 : }
532 : }
533 :
534 14 : if (isStaleIdentity(generation)) return
535 0 : isFetchingWorkspaces.value = false
536 : }
537 :
538 31 : function initialize(): Promise<void> {
539 31 : if (initializationPromise) return initializationPromise
540 31 : if (initState.value !== 'uninitialized' && initState.value !== 'error') {
541 0 : return Promise.resolve()
542 : }
543 :
544 18 : const promise = performInitialization()
545 18 : initializationPromise = promise
546 18 : void promise.then(
547 : () => {
548 17 : if (initializationPromise !== promise) return
549 17 : initializationPromise = null
550 17 : hostChangedWhileLoading = false
551 : },
552 : () => {
553 0 : if (initializationPromise !== promise) return
554 0 : initializationPromise = null
555 0 : retryIfHostChangedWhileLoading()
556 : }
557 : )
558 18 : return promise
559 : }
560 :
561 : /**
562 : * Re-fetch workspaces from API without changing active workspace.
563 : */
564 0 : async function refreshWorkspaces(): Promise<void> {
565 0 : const generation = identityGeneration.value
566 0 : isFetchingWorkspaces.value = true
567 0 : try {
568 0 : const response = await workspaceApi.list()
569 0 : if (isStaleIdentity(generation)) return
570 0 : applyWorkspaceList(response)
571 : } finally {
572 0 : if (!isStaleIdentity(generation)) {
573 0 : isFetchingWorkspaces.value = false
574 : }
575 : }
576 : }
577 :
578 : /** Returns whether the revoked workspace was handled, with or without reload. */
579 0 : function forgetRevokedActiveWorkspace(workspaceId: string): boolean {
580 0 : if (activeWorkspaceId.value !== workspaceId) return false
581 :
582 : const revoked = workspaces.value.find((w) => w.id === workspaceId)
583 0 : if (revoked?.type === 'personal') return true
584 :
585 : if (!isCloud) {
586 0 : const personal = workspaces.value.find((w) => w.type === 'personal')
587 0 : workspaces.value = workspaces.value.filter((w) => w.id !== workspaceId)
588 0 : mutableActiveWorkspaceId.value = personal?.id ?? null
589 0 : if (personal) {
590 0 : setLastWorkspaceId(personal.id)
591 : } else {
592 0 : clearLastWorkspaceId()
593 : }
594 0 : return true
595 : }
596 :
597 : prepareWorkflowWorkspaceTransition()
598 : clearLastWorkspaceId()
599 : window.location.reload()
600 : return true
601 : }
602 :
603 : /**
604 : * Switch to a different workspace.
605 : * Clears workspace context and reloads the page.
606 : */
607 2 : async function executeWorkspaceSwitch(workspaceId: string): Promise<void> {
608 2 : const generation = identityGeneration.value
609 2 : const workspaceAuthStore = useWorkspaceAuthStore()
610 :
611 2 : mutableWorkspaceTransitionGeneration.value++
612 2 : isSwitching.value = true
613 :
614 2 : try {
615 : // Verify workspace exists in our list (user has access)
616 : const workspace = workspaces.value.find((w) => w.id === workspaceId)
617 2 : if (!workspace) {
618 : // Workspace not in list - try refetching in case it was added
619 0 : await refreshWorkspaces()
620 0 : if (isStaleIdentity(generation)) return
621 : const refreshedWorkspace = workspaces.value.find(
622 : (w) => w.id === workspaceId
623 : )
624 0 : if (!refreshedWorkspace) {
625 0 : throw new Error('Workspace not found or access denied')
626 : }
627 : }
628 :
629 2 : if (isStaleIdentity(generation)) return
630 :
631 : if (!isCloud) {
632 2 : const switched = isDesktopHostSignedIn()
633 : ? await requestDesktopHostWorkspaceSwitch(workspaceId)
634 : : await workspaceAuthStore
635 : .switchWorkspace(workspaceId)
636 : .then(
637 : () => workspaceAuthStore.currentWorkspace?.id === workspaceId
638 : )
639 2 : if (isStaleIdentity(generation)) return
640 2 : if (!switched) {
641 0 : throw new Error('Workspace authentication did not switch')
642 : }
643 2 : mutableActiveWorkspaceId.value = workspaceId
644 2 : setLastWorkspaceId(workspaceId)
645 2 : isSwitching.value = false
646 2 : return
647 : }
648 :
649 : prepareWorkflowWorkspaceTransition()
650 : workspaceAuthStore.clearWorkspaceContext()
651 : setLastWorkspaceId(workspaceId)
652 : setSwitchTargetId(workspaceId)
653 :
654 : // Reload to reinitialize with new workspace
655 : window.location.reload()
656 : // Code after this won't run (page reloads)
657 : } catch (e) {
658 0 : if (!isStaleIdentity(generation)) {
659 0 : isSwitching.value = false
660 : }
661 0 : throw e
662 : }
663 : }
664 :
665 2 : async function switchWorkspace(workspaceId: string): Promise<void> {
666 2 : if (workspaceId === activeWorkspaceId.value) return
667 2 : if (!isCloud && isSwitching.value) {
668 0 : console.error('Workspace switch already in progress')
669 0 : return
670 : }
671 :
672 2 : const workspaceSwitch = executeWorkspaceSwitch(workspaceId)
673 2 : pendingWorkspaceSwitch = workspaceSwitch
674 2 : try {
675 2 : await workspaceSwitch
676 : } finally {
677 2 : if (pendingWorkspaceSwitch === workspaceSwitch) {
678 2 : pendingWorkspaceSwitch = null
679 : }
680 : }
681 : }
682 :
683 193 : function waitForWorkspaceSwitch(): Promise<void> {
684 193 : return pendingWorkspaceSwitch ?? Promise.resolve()
685 : }
686 :
687 : /**
688 : * Create a new workspace and switch to it.
689 : */
690 0 : async function createWorkspace(name: string): Promise<WorkspaceState> {
691 0 : const generation = identityGeneration.value
692 0 : const workspaceAuthStore = useWorkspaceAuthStore()
693 :
694 0 : isCreating.value = true
695 :
696 0 : try {
697 0 : const newWorkspace = await workspaceApi.create({ name })
698 0 : const workspaceState = createWorkspaceState(newWorkspace)
699 0 : if (isStaleIdentity(generation)) return workspaceState
700 :
701 : // Add to local list
702 0 : workspaces.value = [...workspaces.value, workspaceState]
703 :
704 : // Clear context and switch to new workspace
705 0 : prepareWorkflowWorkspaceTransition()
706 0 : workspaceAuthStore.clearWorkspaceContext()
707 : // Clear any preserved invite query to prevent stale invites from being
708 : // processed after the reload (prevents owner adding themselves as member)
709 0 : clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.INVITE)
710 0 : setLastWorkspaceId(newWorkspace.id)
711 0 : window.location.reload()
712 :
713 : // Code after this won't run (page reloads)
714 0 : return workspaceState
715 : } catch (e) {
716 0 : if (!isStaleIdentity(generation)) {
717 0 : isCreating.value = false
718 : }
719 0 : throw e
720 : }
721 : }
722 :
723 : /**
724 : * Delete a workspace.
725 : * If deleting active workspace, switches to personal.
726 : */
727 0 : async function deleteWorkspace(workspaceId?: string): Promise<void> {
728 0 : const generation = identityGeneration.value
729 0 : const targetId = workspaceId ?? activeWorkspaceId.value
730 0 : if (!targetId) throw new Error('No workspace to delete')
731 :
732 0 : const workspace = workspaces.value.find((w) => w.id === targetId)
733 0 : if (!workspace) throw new Error('Workspace not found')
734 0 : if (workspace.type === 'personal') {
735 0 : throw new Error('Cannot delete personal workspace')
736 : }
737 :
738 0 : const workspaceAuthStore = useWorkspaceAuthStore()
739 :
740 0 : isDeleting.value = true
741 :
742 0 : try {
743 0 : await workspaceApi.delete(targetId)
744 0 : if (isStaleIdentity(generation)) return
745 :
746 0 : if (targetId === activeWorkspaceId.value) {
747 : // Sorted personal-first, so this is personal or the next team.
748 0 : const fallback = workspaces.value.find((w) => w.id !== targetId)
749 0 : prepareWorkflowWorkspaceTransition()
750 0 : workspaceAuthStore.clearWorkspaceContext()
751 0 : if (fallback) setLastWorkspaceId(fallback.id)
752 0 : else clearLastWorkspaceId()
753 0 : window.location.reload()
754 : // Code after this won't run (page reloads)
755 : } else {
756 : // Deleted non-active workspace - just update local list
757 0 : workspaces.value = workspaces.value.filter((w) => w.id !== targetId)
758 0 : isDeleting.value = false
759 : }
760 : } catch (e) {
761 0 : if (!isStaleIdentity(generation)) {
762 0 : isDeleting.value = false
763 : }
764 0 : throw e
765 : }
766 : }
767 :
768 : /**
769 : * Rename a workspace. No reload needed.
770 : */
771 0 : async function renameWorkspace(
772 : workspaceId: string,
773 : newName: string
774 : ): Promise<void> {
775 0 : const generation = identityGeneration.value
776 0 : const updated = await workspaceApi.update(workspaceId, { name: newName })
777 0 : if (isStaleIdentity(generation)) return
778 0 : updateWorkspace(workspaceId, { name: updated.name })
779 : }
780 :
781 : /**
782 : * Update workspace name (convenience for current workspace).
783 : */
784 0 : async function updateWorkspaceName(name: string): Promise<void> {
785 0 : if (!activeWorkspaceId.value) {
786 0 : throw new Error('No active workspace')
787 : }
788 0 : await renameWorkspace(activeWorkspaceId.value, name)
789 : }
790 :
791 0 : async function leaveWorkspace(): Promise<void> {
792 0 : const generation = identityGeneration.value
793 0 : const current = activeWorkspace.value
794 0 : if (!current) throw new Error('No active workspace')
795 :
796 0 : const workspaceAuthStore = useWorkspaceAuthStore()
797 :
798 0 : await workspaceApi.leave()
799 0 : if (isStaleIdentity(generation)) return
800 :
801 0 : const personal = workspaces.value.find(
802 : (workspace) =>
803 : workspace.type === 'personal' && workspace.id !== current.id
804 : )
805 0 : prepareWorkflowWorkspaceTransition()
806 0 : workspaceAuthStore.clearWorkspaceContext()
807 0 : if (personal) {
808 0 : setLastWorkspaceId(personal.id)
809 : } else {
810 0 : clearLastWorkspaceId()
811 : }
812 0 : window.location.reload()
813 : // Code after this won't run (page reloads)
814 : }
815 :
816 2355 : let latestMembersRequest = 0
817 :
818 : /**
819 : * Fetch members for the current workspace.
820 : */
821 7 : async function fetchMembers(
822 : params: ListMembersParams = {}
823 : ): Promise<WorkspaceMember[]> {
824 7 : const request = ++latestMembersRequest
825 7 : const generation = identityGeneration.value
826 7 : const workspaceId = activeWorkspaceId.value
827 7 : if (!workspaceId) return []
828 :
829 7 : const response = await workspaceApi.listMembers({
830 : ...params,
831 : limit: params.limit ?? 100
832 : })
833 7 : const members = response.members.map(mapApiMemberToWorkspaceMember)
834 7 : if (
835 : request === latestMembersRequest &&
836 : !isStaleWorkspace(generation, workspaceId)
837 : ) {
838 7 : updateWorkspace(workspaceId, {
839 : members,
840 : membersLoaded: true,
841 : totalMembers: response.pagination.total
842 : })
843 : }
844 7 : return members
845 : }
846 :
847 : // Tracks which workspaces have already loaded their members so the
848 : // lifecycle gate resolves without redundant or duplicate fetches.
849 2355 : const loadedMemberWorkspaceIds = new Set<string>()
850 2355 : let inFlightMembersRequest: {
851 : generation: number
852 : workspaceId: string
853 : } | null = null
854 :
855 : /**
856 : * Load the active workspace's members once. No-ops for already-loaded
857 : * workspaces and dedupes concurrent calls. A failed request is logged and
858 : * leaves the workspace unloaded so a later call retries.
859 : */
860 8 : async function ensureMembersLoaded(): Promise<void> {
861 8 : const workspaceId = activeWorkspaceId.value
862 8 : const generation = identityGeneration.value
863 8 : if (!workspaceId) return
864 8 : if (loadedMemberWorkspaceIds.has(workspaceId)) return
865 8 : if (
866 : inFlightMembersRequest?.generation === generation &&
867 : inFlightMembersRequest.workspaceId === workspaceId
868 : ) {
869 0 : return
870 : }
871 :
872 7 : const request = { generation, workspaceId }
873 7 : inFlightMembersRequest = request
874 8 : try {
875 7 : await fetchMembers()
876 8 : if (
877 : !isStaleWorkspace(generation, workspaceId) &&
878 : activeWorkspace.value?.membersLoaded
879 : ) {
880 7 : loadedMemberWorkspaceIds.add(workspaceId)
881 : }
882 : } catch (e) {
883 0 : if (!isStaleIdentity(generation)) {
884 0 : console.error('Failed to load workspace members', e)
885 : }
886 : } finally {
887 7 : if (inFlightMembersRequest === request) {
888 7 : inFlightMembersRequest = null
889 : }
890 : }
891 : }
892 :
893 : /**
894 : * Remove a member from the current workspace.
895 : */
896 0 : async function removeMember(userId: string): Promise<void> {
897 0 : const generation = identityGeneration.value
898 0 : const workspaceId = activeWorkspaceId.value
899 0 : if (!workspaceId) return
900 :
901 0 : await workspaceApi.removeMember(userId)
902 0 : if (isStaleWorkspace(generation, workspaceId)) {
903 0 : return
904 : }
905 0 : const current = workspaces.value.find((w) => w.id === workspaceId)
906 0 : if (current) {
907 0 : updateWorkspace(workspaceId, {
908 : members: current.members.filter((m) => m.id !== userId),
909 : totalMembers:
910 : current.totalMembers === undefined
911 : ? undefined
912 : : Math.max(0, current.totalMembers - 1)
913 : })
914 : }
915 : }
916 :
917 : /**
918 : * Change a member's role in the current workspace.
919 : */
920 0 : async function changeMemberRole(
921 : userId: string,
922 : role: WorkspaceMember['role']
923 : ): Promise<void> {
924 0 : const generation = identityGeneration.value
925 0 : const workspaceId = activeWorkspaceId.value
926 0 : if (!workspaceId) return
927 0 : if (
928 : activeWorkspace.value?.type === 'personal' &&
929 : userId === originalOwnerId.value
930 : ) {
931 0 : throw new Error("Cannot change the workspace creator's role")
932 : }
933 : // Only the role changes; merge it onto the existing row rather than trusting
934 : // the PATCH response to echo a full Member (a 204/partial body would
935 : // otherwise drop joined_at / is_original_owner).
936 0 : await workspaceApi.updateMemberRole(userId, role)
937 0 : if (isStaleWorkspace(generation, workspaceId)) {
938 0 : return
939 : }
940 0 : const current = workspaces.value.find((w) => w.id === workspaceId)
941 0 : if (current) {
942 0 : updateWorkspace(workspaceId, {
943 : members: current.members.map((m) =>
944 : m.id === userId ? { ...m, role } : m
945 : )
946 : })
947 : }
948 : }
949 :
950 : /**
951 : * Set or clear a member's monthly credit limit. Local-only until backend
952 : * persistence lands in FE-1278; `null` removes the cap.
953 : */
954 0 : function setMemberCreditLimit(userId: string, limit: number | null): void {
955 0 : const current = activeWorkspace.value
956 0 : if (!current) return
957 0 : updateActiveWorkspace({
958 : members: current.members.map((m) =>
959 : m.id === userId ? { ...m, monthlyCreditLimit: limit } : m
960 : )
961 : })
962 : }
963 :
964 2355 : let latestInvitesRequest = 0
965 :
966 : /**
967 : * Fetch pending invites for the current workspace.
968 : */
969 0 : async function fetchPendingInvites(): Promise<WorkspacePendingInvite[]> {
970 0 : const request = ++latestInvitesRequest
971 0 : const generation = identityGeneration.value
972 0 : const workspaceId = activeWorkspaceId.value
973 0 : if (!workspaceId) return []
974 :
975 : const response = await workspaceApi.listInvites()
976 0 : const invites = response.invites.map(mapApiInviteToPendingInvite)
977 0 : if (
978 : request === latestInvitesRequest &&
979 : !isStaleWorkspace(generation, workspaceId)
980 : ) {
981 0 : updateWorkspace(workspaceId, {
982 : pendingInvites: invites,
983 : pendingInvitesLoaded: true
984 : })
985 : }
986 0 : return invites
987 : }
988 :
989 : /**
990 : * Create an invite for the current workspace.
991 : */
992 0 : async function createInvite(email: string): Promise<WorkspacePendingInvite> {
993 0 : const generation = identityGeneration.value
994 0 : const workspaceId = activeWorkspaceId.value
995 : const response = await workspaceApi.createInvite({ email })
996 0 : const invite = mapApiInviteToPendingInvite(response)
997 :
998 0 : if (!workspaceId || isStaleWorkspace(generation, workspaceId)) {
999 0 : return invite
1000 : }
1001 0 : const current = workspaces.value.find((w) => w.id === workspaceId)
1002 0 : if (current) {
1003 0 : updateWorkspace(workspaceId, {
1004 : pendingInvites: [...current.pendingInvites, invite]
1005 : })
1006 : }
1007 :
1008 0 : return invite
1009 : }
1010 :
1011 : /**
1012 : * Revoke a pending invite.
1013 : */
1014 0 : async function revokeInvite(inviteId: string): Promise<void> {
1015 0 : const generation = identityGeneration.value
1016 0 : const workspaceId = activeWorkspaceId.value
1017 0 : await workspaceApi.revokeInvite(inviteId)
1018 0 : if (!workspaceId || isStaleWorkspace(generation, workspaceId)) {
1019 0 : return
1020 : }
1021 0 : const current = workspaces.value.find((w) => w.id === workspaceId)
1022 0 : if (current) {
1023 0 : updateWorkspace(workspaceId, {
1024 : pendingInvites: current.pendingInvites.filter((i) => i.id !== inviteId)
1025 : })
1026 : }
1027 : }
1028 :
1029 2355 : const resendingInviteIds = new Set<string>()
1030 :
1031 0 : async function resendInvite(
1032 : inviteId: string
1033 : ): Promise<WorkspacePendingInvite> {
1034 0 : const generation = identityGeneration.value
1035 0 : const resendKey = `${generation}:${inviteId}`
1036 0 : const workspace = activeWorkspace.value
1037 0 : const invite = workspace?.pendingInvites.find(
1038 : (invite) => invite.id === inviteId
1039 : )
1040 0 : if (resendingInviteIds.has(resendKey)) {
1041 0 : console.error('Invite resend already in progress')
1042 0 : if (invite) return invite
1043 : }
1044 0 : if (!workspace || !invite) {
1045 0 : throw new Error('Invite not found')
1046 : }
1047 0 : resendingInviteIds.add(resendKey)
1048 0 : try {
1049 0 : const refreshed = mapApiInviteToPendingInvite(
1050 : await workspaceApi.resendInvite(inviteId)
1051 : )
1052 0 : if (isStaleIdentity(generation)) return refreshed
1053 0 : const currentWorkspace = workspaces.value.find(
1054 : (candidate) => candidate.id === workspace.id
1055 : )
1056 0 : if (currentWorkspace) {
1057 0 : updateWorkspace(workspace.id, {
1058 : pendingInvites: currentWorkspace.pendingInvites.map((invite) =>
1059 : invite.id === inviteId ? refreshed : invite
1060 : )
1061 : })
1062 : }
1063 0 : return refreshed
1064 : } finally {
1065 0 : resendingInviteIds.delete(resendKey)
1066 : }
1067 : }
1068 :
1069 : /**
1070 : * Accept a workspace invite.
1071 : * Returns workspace info so UI can offer "View Workspace" button.
1072 : */
1073 0 : async function acceptInvite(
1074 : token: string
1075 : ): Promise<{ workspaceId: string; workspaceName: string }> {
1076 0 : const generation = identityGeneration.value
1077 0 : const response = await workspaceApi.acceptInvite(token)
1078 :
1079 : // Refresh workspace list to include newly joined workspace. The invite is
1080 : // already consumed at this point, so a refresh failure must not surface
1081 : // as an accept failure — the next workspace fetch reconciles the list.
1082 0 : if (!isStaleIdentity(generation)) {
1083 0 : try {
1084 0 : await refreshWorkspaces()
1085 : } catch (error) {
1086 0 : reportError(error, {
1087 : errorType: 'error_refreshing_workspaces_after_invite_accept',
1088 : surface: 'workspace'
1089 : })
1090 : }
1091 : }
1092 :
1093 0 : return {
1094 : workspaceId: response.workspace_id,
1095 : workspaceName: response.workspace_name
1096 : }
1097 : }
1098 :
1099 : /**
1100 : * Clean up store resources.
1101 : * Delegates to workspaceAuthStore for token cleanup.
1102 : */
1103 0 : function destroy(): void {
1104 : const workspaceAuthStore = useWorkspaceAuthStore()
1105 0 : workspaceAuthStore.destroy()
1106 : }
1107 :
1108 : // A switch made in Desktop (its chooser, or another view) re-scopes this
1109 : // view's credential. The tab drops its old scope at once and takes the new
1110 : // workspace only once the account's list confirms it.
1111 0 : async function followDesktopHostWorkspace(
1112 : hostWorkspaceId: string
1113 : ): Promise<void> {
1114 0 : const generation = identityGeneration.value
1115 0 : mutableActiveWorkspaceId.value = null
1116 0 : const isListed = () =>
1117 : workspaces.value.some((w) => w.id === hostWorkspaceId)
1118 0 : if (!isListed()) {
1119 0 : await refreshWorkspaces().catch((error: unknown) =>
1120 : reportError(error, {
1121 : errorType: 'error_refreshing_workspaces_for_desktop_host',
1122 : surface: 'workspace'
1123 : })
1124 : )
1125 0 : if (
1126 : isStaleIdentity(generation) ||
1127 : desktopHostUser.value?.workspaceId !== hostWorkspaceId
1128 : ) {
1129 0 : return
1130 : }
1131 : }
1132 0 : if (isListed()) mutableActiveWorkspaceId.value = hostWorkspaceId
1133 : }
1134 :
1135 0 : function retryInitializationForHost(): void {
1136 0 : initialize().catch((error: unknown) =>
1137 : reportError(error, {
1138 : errorType: 'error_reinitializing_workspaces_for_desktop_host',
1139 : surface: 'workspace'
1140 : })
1141 : )
1142 : }
1143 :
1144 2355 : watch(desktopHostUser, (hostUser) => {
1145 1 : if (!hostUser) return
1146 0 : if (initState.value === 'loading') hostChangedWhileLoading = true
1147 0 : if (initState.value === 'error') retryInitializationForHost()
1148 : })
1149 :
1150 0 : function retryIfHostChangedWhileLoading(): void {
1151 0 : const retry = hostChangedWhileLoading && desktopHostUser.value !== null
1152 0 : hostChangedWhileLoading = false
1153 0 : if (retry) retryInitializationForHost()
1154 : }
1155 :
1156 2355 : watch(
1157 : () => desktopHostUser.value?.workspaceId,
1158 : (hostWorkspaceId) => {
1159 1 : if (
1160 : !hostWorkspaceId ||
1161 : initState.value !== 'ready' ||
1162 : hostWorkspaceId === mutableActiveWorkspaceId.value
1163 : ) {
1164 1 : return
1165 : }
1166 0 : void followDesktopHostWorkspace(hostWorkspaceId)
1167 : }
1168 : )
1169 :
1170 2 : function resetForIdentityChange(): void {
1171 2 : identityGeneration.value++
1172 2 : mutableWorkspaceTransitionGeneration.value++
1173 2 : pendingWorkspaceSwitch = null
1174 2 : initializationPromise = null
1175 2 : hostChangedWhileLoading = false
1176 2 : initState.value = 'uninitialized'
1177 2 : workspaces.value = []
1178 2 : serverRefusesCreation.value = false
1179 2 : creationDeniedReason.value = undefined
1180 2 : maxOwnedWorkspaces.value = undefined
1181 2 : mutableActiveWorkspaceId.value = null
1182 2 : error.value = null
1183 2 : isCreating.value = false
1184 2 : isDeleting.value = false
1185 2 : isSwitching.value = false
1186 2 : isFetchingWorkspaces.value = false
1187 2 : loadedMemberWorkspaceIds.clear()
1188 2 : inFlightMembersRequest = null
1189 2 : resendingInviteIds.clear()
1190 : }
1191 :
1192 2355 : return {
1193 : // State
1194 : initState,
1195 : workspaces,
1196 : activeWorkspaceId,
1197 : workspaceTransitionGeneration,
1198 : identityGeneration: computed(() => identityGeneration.value),
1199 : error,
1200 : isCreating,
1201 : isDeleting,
1202 : isSwitching,
1203 : isFetchingWorkspaces,
1204 :
1205 : // Computed
1206 : activeWorkspace,
1207 : personalWorkspace,
1208 : isInPersonalWorkspace,
1209 : sharedWorkspaces,
1210 : canCreateWorkspace,
1211 : serverRefusesCreation,
1212 : creationDeniedReason,
1213 : maxOwnedWorkspaces,
1214 : createWorkspaceRefusal,
1215 : members,
1216 : membersLoaded,
1217 : pendingInvites,
1218 : pendingInvitesLoaded,
1219 : originalOwnerId,
1220 : workspaceId,
1221 : workspaceName,
1222 :
1223 : // Initialization & Cleanup
1224 : initialize,
1225 : destroy,
1226 : resetForIdentityChange,
1227 : refreshWorkspaces,
1228 :
1229 : // Workspace Actions
1230 : switchWorkspace,
1231 : waitForWorkspaceSwitch,
1232 : forgetRevokedActiveWorkspace,
1233 : createWorkspace,
1234 : deleteWorkspace,
1235 : renameWorkspace,
1236 : updateWorkspaceName,
1237 : leaveWorkspace,
1238 :
1239 : // Member Actions
1240 : fetchMembers,
1241 : ensureMembersLoaded,
1242 : removeMember,
1243 : changeMemberRole,
1244 : setMemberCreditLimit,
1245 :
1246 : // Invite Actions
1247 : fetchPendingInvites,
1248 : createInvite,
1249 : revokeInvite,
1250 : resendInvite,
1251 : acceptInvite,
1252 :
1253 : updateActiveWorkspace
1254 : }
1255 : })
1256 :
1257 2356 : provideTeamWorkspaceStore(useTeamWorkspaceStore)
|