import { ApiError, patchSettingsGroup, readAuth, readSettingsGroup, type LoginTerms, type ProviderSettings, } from './api'; import type { components } from './api.gen'; type UISettings = components['schemas']['UISettings']; /** * What a first message on a profile owes: the terms warning its sign-in * carries, until someone dismisses it on any client. A read that fails shows * no warning rather than holding the message. */ class Terms { #byExtension = new Map(); #profiles: ProviderSettings | null = null; #dismissed = new Set(); #loading: Promise | null = null; #readAt = -Infinity; /** * Reads the sign-ins, profiles and dismissals again, one read at a time and * at most once a minute: every chat that opens asks. */ refresh(): Promise { if (performance.now() - this.#readAt < 60_000) return Promise.resolve(); this.#loading ??= this.#read().finally(() => (this.#loading = null)); return this.#loading; } async #read() { try { const [auth, profiles, ui] = await Promise.all([ readAuth(), readSettingsGroup('providers'), readSettingsGroup('ui'), ]); this.#byExtension = new Map( auth.providers.flatMap((login) => login.terms ? [[login.id, login.terms] as const] : [], ), ); this.#profiles = profiles.value; this.#dismissed = new Set(ui.value.dismissed_notices); this.#readAt = performance.now(); } catch { // Keep what the last read found. } } /** The warning a message on profile (null: the default) still owes. */ owed(profile: string | null | undefined): LoginTerms | null { const name = profile ?? this.#profiles?.default_profile; const settings = name ? this.#profiles?.profiles[name] : undefined; if (!settings || settings.has_key) return null; const terms = this.#byExtension.get(settings.extension); return terms && !this.#dismissed.has(terms.id) ? terms : null; } /** * Records id as dismissed for every client. A list another client changed * first is read again, so neither dismissal is lost; a save that fails * leaves other pages to ask once more. */ async dismiss(id: string) { this.#dismissed.add(id); for (let attempt = 0; attempt < 2; attempt++) { try { const ui = await readSettingsGroup('ui'); if (ui.value.dismissed_notices.includes(id)) return; await patchSettingsGroup('ui', ui.etag, { dismissed_notices: [...ui.value.dismissed_notices, id], }); return; } catch (error) { if (!(error instanceof ApiError && error.status === 412)) return; } } } } export const terms = new Terms();