|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `useLauncherApps` — the apps a launcher surface offers, as the SERVER filters |
| 5 | + * them for this user (objectstack#26838). |
| 6 | + * |
| 7 | + * `GET /api/v1/meta/app` serves every app the caller may open, routing |
| 8 | + * included: a permission set's `tabPermissions: { <app>: 'hidden' }` does not |
| 9 | + * withhold an app there, and must not — a hidden app keeps opening from a |
| 10 | + * direct URL (UI visibility, not access control). The hide is applied in one |
| 11 | + * place, `GET /api/v1/me/apps`, which merges the caller's sets (most visible |
| 12 | + * wins) and drops the hidden ones. Home read the first list and drew a tile |
| 13 | + * for an app the member's set hides; the app switcher and the `app:launcher` |
| 14 | + * page block read the same list and offered it too. |
| 15 | + * |
| 16 | + * So every launcher surface narrows its `/meta/app` list through this hook, |
| 17 | + * and the hook through ONE read of `/me/apps` per user, held by |
| 18 | + * {@link LauncherAppsProvider}. Three surfaces, one answer: they cannot |
| 19 | + * disagree about which app is offered. |
| 20 | + * |
| 21 | + * What the answer narrows, and what it leaves: |
| 22 | + * |
| 23 | + * - The list keeps `/meta/app`'s entries — their labels, icons, package ids |
| 24 | + * and publish state are that route's. `/me/apps` contributes NAMES only. |
| 25 | + * - An app the answer was never asked about is not hidden by it. The provider |
| 26 | + * records the active app names it asked with; an app that arrives later (an |
| 27 | + * install, a publish) passes until the re-read it triggers lands, rather |
| 28 | + * than vanishing from the launcher it was just installed into. |
| 29 | + * - No provider mounted, a `404` (no security plugin serves the route), or a |
| 30 | + * failed read: nothing narrows, and the surface shows the `/meta/app` list |
| 31 | + * as it always did. That is the server's own posture — `/me/apps` fails open |
| 32 | + * without the security plugin — and the same "cosmetic, never fail-closed" |
| 33 | + * one the console's other personal reads take. A failure other than `404` |
| 34 | + * says so once on the console. |
| 35 | + * - `pending` is true only while the FIRST read is out. Home waits on it, so a |
| 36 | + * hidden tile is never drawn and then taken away; a re-read keeps serving |
| 37 | + * the answer it replaces. |
| 38 | + * |
| 39 | + * `default_off` is not read here: it is not a hide. |
| 40 | + * |
| 41 | + * @module |
| 42 | + */ |
| 43 | + |
| 44 | +import * as React from 'react'; |
| 45 | +import { createContext, useContext, useEffect, useRef, useState } from 'react'; |
| 46 | +import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; |
| 47 | +import { useMetadata } from '../providers/MetadataProvider.js'; |
| 48 | +import { filterActiveApps } from '../utils/appRoute.js'; |
| 49 | +import { resolveRuntimeApiBase } from './storageUsageEndpoint.js'; |
| 50 | + |
| 51 | +type LauncherAppLike = { name?: unknown } & Record<string, unknown>; |
| 52 | + |
| 53 | +/** One `/me/apps` answer, and the app names it speaks for. */ |
| 54 | +interface LauncherAnswer { |
| 55 | + /** The app names `/me/apps` listed. */ |
| 56 | + served: ReadonlySet<string>; |
| 57 | + /** The active `/meta/app` names when the read went out. */ |
| 58 | + asked: ReadonlySet<string>; |
| 59 | +} |
| 60 | + |
| 61 | +type LauncherAppsState = |
| 62 | + | { status: 'idle' } |
| 63 | + | { status: 'pending' } |
| 64 | + | { status: 'ready'; answer: LauncherAnswer } |
| 65 | + | { status: 'unavailable' }; |
| 66 | + |
| 67 | +const LauncherAppsContext = createContext<LauncherAppsState | null>(null); |
| 68 | + |
| 69 | +/** The provider's state, and the user it belongs to. */ |
| 70 | +interface HeldAnswer { |
| 71 | + owner: string | null; |
| 72 | + state: LauncherAppsState; |
| 73 | +} |
| 74 | + |
| 75 | +const NOTHING_HELD: HeldAnswer = { owner: null, state: { status: 'idle' } }; |
| 76 | + |
| 77 | +/** A non-2xx answer, kept apart so `404` (route not served) reads as absence. */ |
| 78 | +class LauncherAppsReadError extends Error { |
| 79 | + constructor(readonly httpStatus: number) { |
| 80 | + super(`GET /me/apps returned ${httpStatus}`); |
| 81 | + this.name = 'LauncherAppsReadError'; |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +async function readServedAppNames(url: string, doFetch: typeof fetch): Promise<Set<string>> { |
| 86 | + const res = await doFetch(url, { |
| 87 | + method: 'GET', |
| 88 | + headers: { Accept: 'application/json' }, |
| 89 | + credentials: 'include', |
| 90 | + }); |
| 91 | + if (!res.ok) throw new LauncherAppsReadError(res.status); |
| 92 | + const body = (await res.json()) as { apps?: unknown } | null; |
| 93 | + if (!Array.isArray(body?.apps)) throw new Error('GET /me/apps answered without an `apps` array'); |
| 94 | + const names = new Set<string>(); |
| 95 | + for (const app of body.apps as Array<{ name?: unknown } | null>) { |
| 96 | + if (typeof app?.name === 'string') names.add(app.name); |
| 97 | + } |
| 98 | + return names; |
| 99 | +} |
| 100 | + |
| 101 | +function activeAppNames(apps: readonly LauncherAppLike[] | null | undefined): string[] { |
| 102 | + const names = new Set<string>(); |
| 103 | + for (const app of filterActiveApps(apps)) { |
| 104 | + if (typeof app?.name === 'string') names.add(app.name); |
| 105 | + } |
| 106 | + return [...names].sort(); |
| 107 | +} |
| 108 | + |
| 109 | +export interface LauncherAppsProviderProps { |
| 110 | + children?: React.ReactNode; |
| 111 | + /** Defaults to `{VITE_SERVER_URL}/api/v1/me/apps`. */ |
| 112 | + endpoint?: string; |
| 113 | + /** |
| 114 | + * Defaults to a fresh `createAuthenticatedFetch()` per read: the console's |
| 115 | + * `/api/v1/*` lane carries a Bearer token and no session cookie. |
| 116 | + */ |
| 117 | + fetcher?: typeof fetch; |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Holds the signed-in user's `/me/apps` answer for every launcher surface |
| 122 | + * below it. Mount it once, where Home and the apps share an ancestor — the |
| 123 | + * console mounts it beside the `/auth/me/permissions` provider. |
| 124 | + * |
| 125 | + * Reads when there is a user and an app list to narrow, and again when the |
| 126 | + * app list gains a name the held answer was not asked about. |
| 127 | + */ |
| 128 | +export function LauncherAppsProvider({ children, endpoint, fetcher }: LauncherAppsProviderProps) { |
| 129 | + const { user } = useAuth(); |
| 130 | + const { apps, loading } = useMetadata(); |
| 131 | + const owner = user?.id != null ? String(user.id) : null; |
| 132 | + // The effect keys on the names' VALUE, never on the list's identity. |
| 133 | + const namesKey = JSON.stringify(activeAppNames(apps as LauncherAppLike[] | undefined)); |
| 134 | + |
| 135 | + const [held, setHeld] = useState<HeldAnswer>(NOTHING_HELD); |
| 136 | + // The effect's reading of the current answer, without keying on it. |
| 137 | + const heldRef = useRef<HeldAnswer>(NOTHING_HELD); |
| 138 | + // Owners whose server answered `404`: the route is not served, so the same |
| 139 | + // question is not asked again for them. |
| 140 | + const notServed = useRef(new Set<string>()); |
| 141 | + |
| 142 | + useEffect(() => { |
| 143 | + const names = JSON.parse(namesKey) as string[]; |
| 144 | + const publish = (next: HeldAnswer) => { |
| 145 | + heldRef.current = next; |
| 146 | + setHeld(next); |
| 147 | + }; |
| 148 | + if (!owner || loading || names.length === 0 || notServed.current.has(owner)) return; |
| 149 | + const current = heldRef.current.owner === owner ? heldRef.current.state : null; |
| 150 | + const answer = current?.status === 'ready' ? current.answer : null; |
| 151 | + if (answer && names.every((name) => answer.asked.has(name))) return; |
| 152 | + |
| 153 | + let cancelled = false; |
| 154 | + const asked = new Set(names); |
| 155 | + if (!current || current.status === 'idle') publish({ owner, state: { status: 'pending' } }); |
| 156 | + const url = endpoint ?? `${resolveRuntimeApiBase()}/me/apps`; |
| 157 | + readServedAppNames(url, fetcher ?? createAuthenticatedFetch()) |
| 158 | + .then((served) => { |
| 159 | + if (cancelled) return; |
| 160 | + publish({ owner, state: { status: 'ready', answer: { served, asked } } }); |
| 161 | + }) |
| 162 | + .catch((err: unknown) => { |
| 163 | + if (cancelled) return; |
| 164 | + if (err instanceof LauncherAppsReadError && err.httpStatus === 404) { |
| 165 | + notServed.current.add(owner); |
| 166 | + } else { |
| 167 | + console.warn( |
| 168 | + '[app-shell] Could not read the apps your permission sets show (`GET /me/apps`); ' + |
| 169 | + 'the launcher lists every app you can open instead:', |
| 170 | + err, |
| 171 | + ); |
| 172 | + } |
| 173 | + // A failed re-read keeps the answer it would have replaced. |
| 174 | + publish({ owner, state: answer ? { status: 'ready', answer } : { status: 'unavailable' } }); |
| 175 | + }); |
| 176 | + return () => { |
| 177 | + cancelled = true; |
| 178 | + }; |
| 179 | + }, [owner, loading, namesKey, endpoint, fetcher]); |
| 180 | + |
| 181 | + const state: LauncherAppsState = held.owner === owner ? held.state : { status: 'idle' }; |
| 182 | + return <LauncherAppsContext.Provider value={state}>{children}</LauncherAppsContext.Provider>; |
| 183 | +} |
| 184 | + |
| 185 | +export interface LauncherApps<T> { |
| 186 | + /** The apps to offer: `filterActiveApps(apps)`, narrowed by `/me/apps`. */ |
| 187 | + apps: T[]; |
| 188 | + /** The first `/me/apps` read is still out; nothing is narrowed yet. */ |
| 189 | + pending: boolean; |
| 190 | +} |
| 191 | + |
| 192 | +/** |
| 193 | + * The apps a launcher surface offers: `filterActiveApps(apps)`, minus every |
| 194 | + * app the user's `/me/apps` answer was asked about and did not list. Outside |
| 195 | + * a {@link LauncherAppsProvider}, or when the read is absent or failed, that |
| 196 | + * is `filterActiveApps(apps)` unchanged. |
| 197 | + */ |
| 198 | +export function useLauncherApps<T extends LauncherAppLike>( |
| 199 | + apps: readonly T[] | null | undefined, |
| 200 | +): LauncherApps<T> { |
| 201 | + const state = useContext(LauncherAppsContext); |
| 202 | + const openable = filterActiveApps(apps); |
| 203 | + if (state?.status !== 'ready') return { apps: openable, pending: state?.status === 'pending' }; |
| 204 | + const { served, asked } = state.answer; |
| 205 | + return { |
| 206 | + apps: openable.filter((app) => { |
| 207 | + const name = app?.name; |
| 208 | + return typeof name !== 'string' || served.has(name) || !asked.has(name); |
| 209 | + }), |
| 210 | + pending: false, |
| 211 | + }; |
| 212 | +} |
0 commit comments