🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(oauth-apps): stamp last use for JWT tokens, paint list and page from a local replica (#22131)
Arvin Xu8c09fdb14957
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx b/src/features/Settings/oauth-apps/features/AppDetail/index.tsxindex 9b4918d2fe8..8086e42cc23 100644--- a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx+++ b/src/features/Settings/oauth-apps/features/AppDetail/index.tsx@@ -15,17 +15,15 @@ import {} from '@lobehub/ui';import dayjs from 'dayjs';import { ArrowLeftIcon, PowerIcon, PowerOffIcon, Trash2Icon } from 'lucide-react';-import { type FC, useEffect } from 'react';+import { type FC, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { useSearchParams } from 'react-router';import OAuthAppStats from '@/business/client/OAuthAppStats';import AsyncError from '@/components/AsyncError';-import { useClientDataSWR } from '@/libs/swr';-import { authKeys } from '@/libs/swr/keys';import { normalizeAsyncError } from '@/libs/swr/normalizeError';-import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';-import { type OAuthAppItem } from '@/types/oauthApp';+import { oauthAppSelectors, useOAuthAppStore } from '@/store/oauthApp';+import { type UpdateOAuthAppParams } from '@/types/oauthApp';import { confirmDisableOAuthApp } from '../confirmDisable';import { showClientSecretModal } from '../SecretModal';@@ -93,17 +91,21 @@ interface AppDetailProps {canEdit: boolean;id: string;onBack: () => void;- onChanged: () => void;}-const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {+const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack }) => {const { t } = useTranslation(['auth', 'common']);- const { data, error, isLoading, isValidating, mutate } = useClientDataSWR(- authKeys.oauthAppById(id),- () => lambdaClient.oauthApp.getById.query({ id }),+ const [useFetchAppDetail, updateApp, setAppEnabled, rotateSecret, deleteApp] = useOAuthAppStore(+ (s) => [s.useFetchAppDetail, s.updateApp, s.setAppEnabled, s.rotateSecret, s.deleteApp],);- const detail = data as OAuthAppItem | undefined;+ // The persisted copy paints the page on open; the network only confirms.+ const { error, isValidating, revalidate } = useFetchAppDetail(id);+ const detail = useOAuthAppStore(oauthAppSelectors.appById(id));+ const notFound = useOAuthAppStore(oauthAppSelectors.isAppNotFound(id));++ const [enabledPending, setEnabledPending] = useState(false);+ const [secretPending, setSecretPending] = useState(false);// The active tab lives in the URL so a reload or shared link keeps it.const [searchParams, setSearchParams] = useSearchParams();@@ -121,39 +123,35 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {// Only a settled "no such app" goes back to the list; a failed load stays here// with Retry instead of silently bouncing the user away.useEffect(() => {- if (!error && !isLoading && !detail) onBack();- }, [error, isLoading, detail, onBack]);+ if (notFound) onBack();+ }, [notFound, onBack]);- const revalidate = () => {- mutate();- onChanged();+ const handleUpdate = async (value: UpdateOAuthAppParams) => {+ await updateApp(id, value);+ toast.success(t('oauthApp.detail.saveSuccess'));};- const updateMutation = lambdaQuery.oauthApp.update.useMutation({- onSuccess: () => {- revalidate();- toast.success(t('oauthApp.detail.saveSuccess'));- },- });- const enabledMutation = lambdaQuery.oauthApp.setEnabled.useMutation({ onSuccess: revalidate });- const rotateSecretMutation = lambdaQuery.oauthApp.rotateSecret.useMutation({- // Minting a credential must never fail silently: the user needs to know no- // secret is waiting for them and that they can try again.- onError: () => toast.error(t('oauthApp.secret.issueFailed')),- onSuccess: ({ clientSecret }) => {- revalidate();- showClientSecretModal({ clientSecret });- },- });- const deleteMutation = lambdaQuery.oauthApp.delete.useMutation({- onSuccess: () => {- onChanged();- onBack();- },- });-- const handleUpdate = async (value: Parameters<typeof updateMutation.mutateAsync>[0]['value']) => {- await updateMutation.mutateAsync({ id, value });+ const setEnabled = async (enabled: boolean) => {+ setEnabledPending(true);+ try {+ await setAppEnabled(id, enabled);+ } finally {+ setEnabledPending(false);+ }+ };++ const issueSecret = async () => {+ setSecretPending(true);+ try {+ showClientSecretModal({ clientSecret: await rotateSecret(id) });+ } catch (error) {+ // Minting a credential must never fail silently: the user needs to know no+ // secret is waiting for them and that they can try again.+ toast.error(t('oauthApp.secret.issueFailed'));+ throw error;+ } finally {+ setSecretPending(false);+ }};const handleRotateSecret = () =>@@ -162,9 +160,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {content: t('oauthApp.secret.rotateConfirm.content'),okButtonProps: { danger: true },okText: t('oauthApp.secret.rotateConfirm.ok'),- onOk: async () => {- await rotateSecretMutation.mutateAsync({ id });- },+ onOk: issueSecret,title: t('oauthApp.secret.rotateConfirm.title'),});@@ -174,15 +170,18 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {content: t('oauthApp.deleteConfirm.content'),okButtonProps: { danger: true },okText: t('oauthApp.deleteConfirm.ok'),+ // The delete is optimistic: go back to the list, where the row is+ // already gone and comes back if the call fails.onOk: async () => {- await deleteMutation.mutateAsync({ id });+ onBack();+ await deleteApp(id);},title: t('oauthApp.deleteConfirm.title'),});- const handleEnable = () => enabledMutation.mutate({ enabled: true, id });- const handleDisable = () =>- confirmDisableOAuthApp(() => enabledMutation.mutateAsync({ enabled: false, id }));+ // A failed enable rolls the page back to disabled.+ const handleEnable = () => void setEnabled(true).catch(() => {});+ const handleDisable = () => confirmDisableOAuthApp(() => setEnabled(false));if (error && !detail)return (@@ -193,7 +192,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {<Flexbox horizontal gap={8}><Button onClick={onBack}>{t('oauthApp.detail.back')}</Button>{normalizeAsyncError(error).retryable && (- <Button loading={isValidating} onClick={() => mutate()}>+ <Button loading={isValidating} onClick={() => void revalidate()}>{t('retry', { ns: 'common' })}</Button>)}@@ -221,7 +220,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {type={'warning'}action={canEdit && (- <Button loading={enabledMutation.isPending} size={'small'} onClick={handleEnable}>+ <Button loading={enabledPending} size={'small'} onClick={handleEnable}>{t('oauthApp.actions.enable')}</Button>)@@ -254,8 +253,8 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {<CredentialsCardcanEdit={canEdit}detail={detail}- secretPending={rotateSecretMutation.isPending}- onGenerateSecret={() => rotateSecretMutation.mutate({ id })}+ secretPending={secretPending}+ onGenerateSecret={() => void issueSecret().catch(() => {})}onRotateSecret={handleRotateSecret}/>{isWebApp && (@@ -286,7 +285,7 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {<Buttondisabled={!canEdit}icon={isDisabled ? <PowerIcon size={16} /> : <PowerOffIcon size={16} />}- loading={enabledMutation.isPending}+ loading={enabledPending}style={{ flex: 'none' }}onClick={isDisabled ? handleEnable : handleDisable}>@@ -306,7 +305,6 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {dangerdisabled={!canEdit}icon={<Trash2Icon size={16} />}- loading={deleteMutation.isPending}style={{ flex: 'none' }}onClick={handleDelete}>diff --git a/src/features/Settings/oauth-apps/features/AppItem/index.tsx b/src/features/Settings/oauth-apps/features/AppItem/index.tsxindex b51f4e2e75e..d8e3e8176f3 100644--- a/src/features/Settings/oauth-apps/features/AppItem/index.tsx+++ b/src/features/Settings/oauth-apps/features/AppItem/index.tsx@@ -15,7 +15,7 @@ import { MoreVerticalIcon, PowerIcon, PowerOffIcon, Trash2Icon } from 'lucide-reimport { memo } from 'react';import { useTranslation } from 'react-i18next';-import { lambdaQuery } from '@/libs/trpc/client';+import { useOAuthAppStore } from '@/store/oauthApp';import { type OAuthAppItem } from '@/types/oauthApp';import { appTypeLabelKey } from '../../appList';@@ -51,16 +51,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface AppItemProps {app: OAuthAppItem;canEdit: boolean;- onChanged: () => void;- onDeleted: () => void;onOpen: () => void;}-const AppItem = memo<AppItemProps>(({ app, canEdit, onChanged, onDeleted, onOpen }) => {+const AppItem = memo<AppItemProps>(({ app, canEdit, onOpen }) => {const { t } = useTranslation(['auth', 'common']);- const setEnabled = lambdaQuery.oauthApp.setEnabled.useMutation({ onSuccess: onChanged });- const deleteApp = lambdaQuery.oauthApp.delete.useMutation({ onSuccess: onDeleted });+ const [setAppEnabled, deleteApp] = useOAuthAppStore((s) => [s.setAppEnabled, s.deleteApp]);const handleDelete = () =>confirmModal({@@ -69,7 +66,7 @@ const AppItem = memo<AppItemProps>(({ app, canEdit, onChanged, onDeleted, onOpenokButtonProps: { danger: true },okText: t('oauthApp.deleteConfirm.ok'),onOk: async () => {- await deleteApp.mutateAsync({ id: app.id });+ await deleteApp(app.id);},title: t('oauthApp.deleteConfirm.title'),});@@ -124,16 +121,14 @@ const AppItem = memo<AppItemProps>(({ app, canEdit, onChanged, onDeleted, onOpenicon: <Icon icon={PowerOffIcon} />,key: 'disable',label: t('oauthApp.actions.disable'),- onClick: () =>- confirmDisableOAuthApp(() =>- setEnabled.mutateAsync({ enabled: false, id: app.id }),- ),+ onClick: () => confirmDisableOAuthApp(() => setAppEnabled(app.id, false)),}: {icon: <Icon icon={PowerIcon} />,key: 'enable',label: t('oauthApp.actions.enable'),- onClick: () => setEnabled.mutate({ enabled: true, id: app.id }),+ // A failed call rolls the row back to disabled.+ onClick: () => void setAppEnabled(app.id, true).catch(() => {}),},{danger: true,diff --git a/src/features/Settings/oauth-apps/features/CreateAppButton.tsx b/src/features/Settings/oauth-apps/features/CreateAppButton.tsxindex 881a2a8e9c5..ab144b31a69 100644--- a/src/features/Settings/oauth-apps/features/CreateAppButton.tsx+++ b/src/features/Settings/oauth-apps/features/CreateAppButton.tsx@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';-import { lambdaClient } from '@/libs/trpc/client';+import { useOAuthAppStore } from '@/store/oauthApp';import { createOAuthAppModal } from './CreateAppModal';import { showClientSecretModal } from './SecretModal';@@ -20,13 +20,14 @@ const CreateAppButton = () => {const { allowed: canManageWorkspaceApps } = usePermission('manage_settings');const canEdit = hasEditPermission && (!activeWorkspaceId || canManageWorkspaceApps);const navigate = useWorkspaceAwareNavigate();+ const createApp = useOAuthAppStore((s) => s.createApp);const handleCreate = () => {if (!canEdit) return;createOAuthAppModal({onSubmit: async (values) => {// The secret is generated on demand on the app page, not at creation.- const created = await lambdaClient.oauthApp.create.mutate({+ const created = await createApp({...values,issueSecret: false,});diff --git a/src/features/Settings/oauth-apps/features/OAuthApps.tsx b/src/features/Settings/oauth-apps/features/OAuthApps.tsxindex ba18dafc47c..a68935c7760 100644--- a/src/features/Settings/oauth-apps/features/OAuthApps.tsx+++ b/src/features/Settings/oauth-apps/features/OAuthApps.tsx@@ -34,9 +34,11 @@ const OAuthApps: FC<OAuthAppsProps> = ({ canEdit }) => {const navigate = useWorkspaceAwareNavigate();const params = useParams<{ sub?: string }>();- const { data: apps, error, isLoading, isValidating, mutate } = useOAuthAppList();+ const { data: apps, error, isLoading, isValidating, revalidate } = useOAuthAppList();- const reload = () => mutate();+ const reload = () => {+ void revalidate();+ };if (params.sub)return (@@ -45,7 +47,6 @@ const OAuthApps: FC<OAuthAppsProps> = ({ canEdit }) => {id={params.sub}key={params.sub}onBack={() => navigate('/settings/oauth-apps')}- onChanged={reload}/>);@@ -78,8 +79,6 @@ const OAuthApps: FC<OAuthAppsProps> = ({ canEdit }) => {app={app}canEdit={canEdit}key={app.id}- onChanged={reload}- onDeleted={reload}onOpen={() => navigate(`/settings/oauth-apps/${app.id}`)}/>));diff --git a/src/features/Settings/oauth-apps/features/useOAuthAppList.ts b/src/features/Settings/oauth-apps/features/useOAuthAppList.tsindex 2ab9aeb861e..341c74998d1 100644--- a/src/features/Settings/oauth-apps/features/useOAuthAppList.ts+++ b/src/features/Settings/oauth-apps/features/useOAuthAppList.ts@@ -1,14 +1,14 @@-import { useClientDataSWR } from '@/libs/swr';-import { authKeys } from '@/libs/swr/keys';-import { lambdaClient } from '@/libs/trpc/client';-import { type OAuthAppItem } from '@/types/oauthApp';+import { oauthAppSelectors, useOAuthAppStore } from '@/store/oauthApp';/*** The app list, shared by the list body and the page header (which hides its- * Create button while the empty state shows its own). SWR dedupes the request.+ * Create button while the empty state shows its own). The persisted copy+ * paints on open; the network only confirms.*/-export const useOAuthAppList = (enabled = true) =>- useClientDataSWR(enabled ? authKeys.oauthAppList() : null, async () => {- const list = await lambdaClient.oauthApp.list.query();- return list as OAuthAppItem[];- });+export const useOAuthAppList = (enabled = true) => {+ const useFetchAppList = useOAuthAppStore((s) => s.useFetchAppList);+ const { error, isValidating, revalidate } = useFetchAppList(enabled);+ const data = useOAuthAppStore(oauthAppSelectors.appList);++ return { data, error, isLoading: !data && !error, isValidating, revalidate };+};diff --git a/src/libs/oidc-provider/adapter.ts b/src/libs/oidc-provider/adapter.tsindex 854df0c30a3..bcf7d009cac 100644--- a/src/libs/oidc-provider/adapter.ts+++ b/src/libs/oidc-provider/adapter.ts@@ -14,6 +14,8 @@ import { eq, sql } from 'drizzle-orm';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { stampClientLastUsed } from './clientLastUsed';+// Create adapter logging namespaceconst log = debug('lobe-oidc:adapter');@@ -285,8 +287,10 @@ class OIDCAdapter {});log('[%s] Successfully upserted record: %s', this.name, id);+ // Only opaque access tokens reach the adapter; JWT ones (the API audience+ // default) are stamped from the provider's `access_token.issued` event.if (this.name === 'AccessToken' || this.name === 'DeviceCode') {- this.stampClientLastUsed(payload.clientId);+ stampClientLastUsed(this.db, payload.clientId);}} catch (error) {log('[%s] ERROR upserting record: %O', this.name, error);@@ -295,20 +299,6 @@ class OIDCAdapter {}}- private stampClientLastUsed(clientId?: string): void {- if (!clientId || !clientId.startsWith('lca_')) return;-- // last_used_at is a best-effort UX signal for user-created OAuth clients;- // a failed stamp must never break token issuance, so swallow all errors.- void this.db- .update(oidcClients)- .set({ lastUsedAt: new Date() })- .where(eq(oidcClients.id, clientId))- .then(undefined, (error: unknown) => {- log('[%s] Failed to stamp last_used_at for client %s: %O', this.name, clientId, error);- });- }-/*** Find model instance*/diff --git a/src/libs/oidc-provider/clientLastUsed.test.ts b/src/libs/oidc-provider/clientLastUsed.test.tsnew file mode 100644index 00000000000..c3687299c6e--- /dev/null+++ b/src/libs/oidc-provider/clientLastUsed.test.ts@@ -0,0 +1,90 @@+/**+ * @vitest-environment node+ */+import Provider from 'oidc-provider';+import { describe, expect, it, vi } from 'vitest';++import { stampClientLastUsed } from './clientLastUsed';++const createDb = ({ rejects = false } = {}) => {+ const chain = {+ set: vi.fn().mockReturnThis(),+ where: vi.fn(() => (rejects ? Promise.reject(new Error('db down')) : Promise.resolve())),+ };+ const db = { update: vi.fn(() => chain) };+ return { chain, db };+};++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++describe('stampClientLastUsed', () => {+ it('stamps a user-created (lca_) client', async () => {+ const { chain, db } = createDb();++ stampClientLastUsed(db as any, 'lca_client_1');+ await flush();++ expect(db.update).toHaveBeenCalledTimes(1);+ expect(chain.set).toHaveBeenCalledWith({ lastUsedAt: expect.any(Date) });+ });++ it('ignores static first-party clients and missing ids', () => {+ const { db } = createDb();++ stampClientLastUsed(db as any, 'lobehub-cli');+ stampClientLastUsed(db as any, undefined);++ expect(db.update).not.toHaveBeenCalled();+ });++ it('swallows a failed update', async () => {+ const { db } = createDb({ rejects: true });++ expect(() => stampClientLastUsed(db as any, 'lca_client_2')).not.toThrow();+ await flush();+ });+});++/**+ * Why the provider listens to `access_token.issued`: a JWT access token, which+ * every token for the API audience is, is never written through the adapter,+ * so the adapter's AccessToken upsert alone left web apps "never used".+ */+describe('oidc-provider JWT access tokens', () => {+ it('emit access_token.issued without touching the adapter', async () => {+ const upsert = vi.fn();+ class SpyAdapter {+ upsert = upsert;+ find = vi.fn();+ findByUid = vi.fn();+ findByUserCode = vi.fn();+ consume = vi.fn();+ destroy = vi.fn();+ revokeByGrantId = vi.fn();+ }+ const provider = new Provider('https://example.com/oidc', {+ adapter: SpyAdapter as any,+ clients: [+ {+ client_id: 'lca_web',+ client_secret: 'secret',+ redirect_uris: ['https://app.example.com/callback'],+ },+ ],+ });+ const issued = vi.fn();+ provider.on('access_token.issued', issued);++ const client = await provider.Client.find('lca_web');+ const token = new provider.AccessToken({+ accountId: 'user-1',+ client,+ grantId: 'grant-1',+ resourceServer: { accessTokenFormat: 'jwt', audience: 'urn:lobehub:chat' },+ } as any);+ await token.save();++ expect(upsert).not.toHaveBeenCalled();+ expect(issued).toHaveBeenCalledWith(expect.objectContaining({ clientId: 'lca_web' }));+ });+});diff --git a/src/libs/oidc-provider/clientLastUsed.ts b/src/libs/oidc-provider/clientLastUsed.tsnew file mode 100644index 00000000000..f2b0b6d6c31--- /dev/null+++ b/src/libs/oidc-provider/clientLastUsed.ts@@ -0,0 +1,25 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { oidcClients } from '@lobechat/database/schemas';+import debug from 'debug';+import { eq } from 'drizzle-orm';++const log = debug('lobe-oidc:client-last-used');++/**+ * Record that a user-created OAuth client (`lca_` id) was just issued a token.+ *+ * `last_used_at` is a best-effort UX signal on the OAuth Apps page; a failed+ * stamp must never break token issuance, so the update is not awaited and all+ * errors are swallowed.+ */+export const stampClientLastUsed = (db: LobeChatDatabase, clientId?: string): void => {+ if (!clientId || !clientId.startsWith('lca_')) return;++ void db+ .update(oidcClients)+ .set({ lastUsedAt: new Date() })+ .where(eq(oidcClients.id, clientId))+ .then(undefined, (error: unknown) => {+ log('Failed to stamp last_used_at for client %s: %O', clientId, error);+ });+};diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.tsindex a4ed54537c0..7ef911a69e7 100644--- a/src/libs/oidc-provider/provider.ts+++ b/src/libs/oidc-provider/provider.ts@@ -15,6 +15,7 @@ import { findSiteForOrigin } from '@/server/services/projectReview/sites';import { accessTokenTTL, isAcceptanceReviewClient, reviewResourceServer } from './acceptanceReview';import { isOIDCUserBanned } from './access-control';import { DrizzleAdapter } from './adapter';+import { stampClientLastUsed } from './clientLastUsed';import { defaultClaims, defaultClients, defaultScopes } from './config';import { getOIDCCookieKeys } from './cookies';import { createInteractionPolicy } from './interaction-policy';@@ -353,6 +354,10 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Providerconsole.error('OIDC Provider Error:', err);});+ // JWT access tokens (every token for the API audience) are self-contained and+ // never written through the adapter, so its upsert never sees them.+ provider.on('access_token.issued', (token) => stampClientLastUsed(db, token.clientId));+provider.on('authorization.success', (ctx) => {logProvider('Authorization successful for client: %s', ctx.oidc.client?.clientId); // Use logProvider});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 1dbf9aad852..94672807785 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -927,8 +927,6 @@ export const ollamaKeys = {downloadModel: def('ollama:downloadModel', (model: string) => ['ollama:downloadModel', model]),};export const authKeys = {- oauthAppById: def('auth:oauthAppById', (id: string) => ['auth:oauthAppById', id]),- oauthAppList: def('auth:oauthAppList', () => ['auth:oauthAppList']),oidcClientMetadata: def('auth:oidcClientMetadata', (clientId: string) => ['auth:oidcClientMetadata',clientId,diff --git a/src/services/oauthApp.ts b/src/services/oauthApp.tsnew file mode 100644index 00000000000..266f7e30f0d--- /dev/null+++ b/src/services/oauthApp.ts@@ -0,0 +1,28 @@+import { lambdaClient } from '@/libs/trpc/client';+import {+ type CreateOAuthAppParams,+ type OAuthAppItem,+ type UpdateOAuthAppParams,+} from '@/types/oauthApp';++class OAuthAppService {+ create = (params: CreateOAuthAppParams) => lambdaClient.oauthApp.create.mutate(params);++ delete = (id: string) => lambdaClient.oauthApp.delete.mutate({ id });++ /** `undefined` when the app does not exist or is not visible to the caller. */+ getById = async (id: string) =>+ (await lambdaClient.oauthApp.getById.query({ id })) as OAuthAppItem | undefined;++ list = async () => (await lambdaClient.oauthApp.list.query()) as OAuthAppItem[];++ rotateSecret = (id: string) => lambdaClient.oauthApp.rotateSecret.mutate({ id });++ setEnabled = (id: string, enabled: boolean) =>+ lambdaClient.oauthApp.setEnabled.mutate({ enabled, id });++ update = (id: string, value: UpdateOAuthAppParams) =>+ lambdaClient.oauthApp.update.mutate({ id, value });+}++export const oauthAppService = new OAuthAppService();diff --git a/src/store/oauthApp/action.ts b/src/store/oauthApp/action.tsnew file mode 100644index 00000000000..7d17d547142--- /dev/null+++ b/src/store/oauthApp/action.ts@@ -0,0 +1,159 @@+import isEqual from 'fast-deep-equal';++import {+ arrayEntity,+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaSyncResult,+ singleEntity,+} from '@/libs/replica';+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';+import { oauthAppService } from '@/services/oauthApp';+import { type StoreSetter } from '@/store/types';+import {+ type CreateOAuthAppParams,+ type OAuthAppItem,+ type UpdateOAuthAppParams,+} from '@/types/oauthApp';+import { setNamespace } from '@/utils/storeDebug';++import { oauthAppDetailResource, oauthAppListResource } from './projection';+import { type OAuthAppStore } from './store';++const n = setNamespace('oauthApp');++const LIST_PARAMS = {} as Record<string, never>;++type Setter = StoreSetter<OAuthAppStore>;++export const createOAuthAppAction = (set: Setter, get: () => OAuthAppStore, _api?: unknown) =>+ new OAuthAppActionImpl(set, get, _api);++export class OAuthAppActionImpl {+ readonly #get: () => OAuthAppStore;+ readonly #set: Setter;+ readonly #list;+ readonly #detail;+ /** The same app as a list row and as its page. */+ readonly #apps;++ constructor(set: Setter, get: () => OAuthAppStore, _api?: unknown) {+ void _api;+ this.#get = get;+ this.#set = set;+ this.#list = createReplicaSlice(oauthAppListResource, {+ actionPrefix: n('appList'),+ entity: arrayEntity<OAuthAppItem>((app) => app.id),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'appListReplica',+ view: recordLens<OAuthAppStore, OAuthAppItem[]>('appListMap'),+ });+ this.#detail = createReplicaSlice(oauthAppDetailResource, {+ actionPrefix: n('appDetail'),+ effects: {+ onApplied: (_detail, id) => this.#setNotFound(id, false),+ // A settled "no such app" (deleted elsewhere, or a workspace without+ // access): drop it from the list too, and let the page go back.+ onMissing: (id) => {+ this.#apps.remove(id);+ this.#setNotFound(id, true);+ },+ },+ entity: singleEntity<OAuthAppItem>((app) => app.id),+ get,+ isMissing: (incoming) => !incoming,+ merge: (incoming, confirmed) =>+ !incoming || isEqual(incoming, confirmed) ? undefined : incoming,+ set,+ stateKey: 'appDetailReplica',+ view: recordLens<OAuthAppStore, OAuthAppItem>('appDetailMap'),+ });+ this.#apps = linkReplicaEntity<OAuthAppItem>([this.#list, this.#detail]);++ // A settled "no such app" belongs to the workspace that observed it. The two+ // replica views reset themselves on a scope switch (`useSync` re-runs), but+ // this map is not a replica: left alone, opening the same app in the workspace+ // that owns it would read the previous scope's flag and send the page back+ // before the new scope's answer lands.+ subscribeCacheScope(this.#forgetMissingOnScopeChange);+ }++ createApp = async (params: CreateOAuthAppParams) => {+ const created = await oauthAppService.create(params);+ void this.#list.fetch(LIST_PARAMS, { fresh: true });+ return created;+ };++ /** Optimistic: the row and the page drop at once and come back if the call fails. */+ deleteApp = async (id: string) => {+ await this.#apps.optimistic(id, 'remove', () => oauthAppService.delete(id));+ };++ refreshAppDetail = async (id: string) => {+ await this.#detail.fetch(id, { fresh: true });+ };++ refreshAppList = async () => {+ await this.#list.fetch(LIST_PARAMS, { fresh: true });+ };++ /** Returns the only plaintext copy of the new secret; the app then reports `hasSecret`. */+ rotateSecret = async (id: string) => {+ const result = await this.#apps.optimistic(+ id,+ (app) => ({ ...app, hasSecret: true }),+ () => oauthAppService.rotateSecret(id),+ );+ return result.clientSecret;+ };++ setAppEnabled = async (id: string, enabled: boolean) => {+ await this.#apps.optimistic(+ id,+ (app) => ({ ...app, enabled }),+ () => oauthAppService.setEnabled(id, enabled),+ );+ };++ updateApp = async (id: string, value: UpdateOAuthAppParams) => {+ await this.#apps.optimistic(+ id,+ (app) => ({ ...app, ...value }),+ () => oauthAppService.update(id, value),+ );+ // The server normalizes some fields (redirect URIs), so confirm its copy.+ void this.#detail.fetch(id, { fresh: true });+ void this.#list.fetch(LIST_PARAMS, { fresh: true });+ };++ /**+ * One app's page: the persisted copy paints the first frame and the network+ * only confirms. Read the app with `oauthAppSelectors.appById`.+ */+ useFetchAppDetail = (id: string | undefined): ReplicaSyncResult =>+ this.#detail.useSync(id ?? null);++ /** The app list; read it with `oauthAppSelectors.appList`. */+ useFetchAppList = (enabled = true): ReplicaSyncResult =>+ this.#list.useSync(enabled ? LIST_PARAMS : null);++ #setNotFound = (id: string, notFound: boolean) => {+ if (!!this.#get().appNotFoundMap[id] === notFound) return;+ this.#set(+ (state) => ({ appNotFoundMap: { ...state.appNotFoundMap, [id]: notFound } }),+ false,+ n('setNotFound'),+ );+ };++ /** The store is an app-lifetime singleton, so the subscription is never torn down. */+ #forgetMissingOnScopeChange = (): void => {+ if (Object.keys(this.#get().appNotFoundMap).length === 0) return;+ this.#set({ appNotFoundMap: {} }, false, n('scopeChanged'));+ };+}++export type OAuthAppAction = Pick<OAuthAppActionImpl, keyof OAuthAppActionImpl>;diff --git a/src/store/oauthApp/index.ts b/src/store/oauthApp/index.tsnew file mode 100644index 00000000000..8e70ed234f4--- /dev/null+++ b/src/store/oauthApp/index.ts@@ -0,0 +1,3 @@+export { oauthAppSelectors } from './selectors';+export type { OAuthAppStore } from './store';+export { useOAuthAppStore } from './store';diff --git a/src/store/oauthApp/initialState.ts b/src/store/oauthApp/initialState.tsnew file mode 100644index 00000000000..1b00f6397d1--- /dev/null+++ b/src/store/oauthApp/initialState.ts@@ -0,0 +1,23 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import { type OAuthAppItem } from '@/types/oauthApp';++export interface OAuthAppState {+ /** Apps by id. Replica view of `appDetailReplica`. */+ appDetailMap: Record<string, OAuthAppItem>;+ /** Replica bookkeeping for `appDetailMap`. */+ appDetailReplica: ReplicaState<OAuthAppItem>;+ /** The app list under the `all` key. Replica view of `appListReplica`. */+ appListMap: Record<string, OAuthAppItem[]>;+ /** Replica bookkeeping for `appListMap`. */+ appListReplica: ReplicaState<OAuthAppItem[]>;+ /** Ids the server settled as gone or not visible; the page goes back to the list. */+ appNotFoundMap: Record<string, boolean>;+}++export const initialOAuthAppState: OAuthAppState = {+ appDetailMap: {},+ appDetailReplica: createReplicaState(),+ appListMap: {},+ appListReplica: createReplicaState(),+ appNotFoundMap: {},+};diff --git a/src/store/oauthApp/projection.ts b/src/store/oauthApp/projection.tsnew file mode 100644index 00000000000..052629eb9c0--- /dev/null+++ b/src/store/oauthApp/projection.ts@@ -0,0 +1,28 @@+import { defineReplica } from '@/libs/replica';+import { oauthAppService } from '@/services/oauthApp';+import { type OAuthAppItem } from '@/types/oauthApp';++/**+ * The OAuth apps of the active scope (user + workspace), keyed `all`.+ *+ * Persisted so the settings page paints the last-known rows on open and the+ * network only confirms. Responses never carry a client secret (the router+ * strips it to `hasSecret`), so the rows are safe to keep in IndexedDB.+ */+export const oauthAppListResource = defineReplica<Record<string, never>, OAuthAppItem[]>({+ fetcher: () => oauthAppService.list(),+ key: () => 'all',+ name: 'oauthAppList',+ storage: 'indexedDB',+ version: 1,+});++/** One app's page, keyed by its client id; a `null` answer means gone. */+export const oauthAppDetailResource = defineReplica<string, OAuthAppItem, OAuthAppItem | null>({+ // `null`, not `undefined`: an `undefined` answer never settles the sync as missing.+ fetcher: async (id) => (await oauthAppService.getById(id)) ?? null,+ key: (id) => id,+ name: 'oauthAppDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/oauthApp/replica.test.ts b/src/store/oauthApp/replica.test.tsnew file mode 100644index 00000000000..9c29c03adf1--- /dev/null+++ b/src/store/oauthApp/replica.test.ts@@ -0,0 +1,182 @@+/**+ * @vitest-environment happy-dom+ *+ * The OAuth Apps settings page reads its list and each app's page through+ * `local-replica`: reopening paints the persisted copy while the network+ * confirms, a row and its page change together, and a settled "no such app"+ * is reported instead of loading forever.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';+import { setScopedMutate } from '@/libs/swr/mutate';+import { oauthAppService } from '@/services/oauthApp';+import { type OAuthAppItem } from '@/types/oauthApp';++import { initialOAuthAppState } from './initialState';+import { oauthAppDetailResource, oauthAppListResource } from './projection';+import { oauthAppSelectors } from './selectors';+import { useOAuthAppStore } from './store';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};+const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** Never-resolving fetch: what the store holds can only have come from storage. */+const pending = () => new Promise<never>(() => {});++const app = (overrides: Partial<OAuthAppItem> = {}): OAuthAppItem => ({+ applicationType: 'web',+ createdAt: new Date('2026-10-01T00:00:00Z'),+ enabled: true,+ hasSecret: true,+ id: 'lca_app_1',+ lastUsedAt: null,+ name: 'Internal Console',+ ...overrides,+});++const state = () => useOAuthAppStore.getState();++describe('oauthApp replicas', () => {+ const scopes = new Set<string>();+ let scope = '';++ beforeEach(() => {+ resetCacheScopeBroadcast();+ scope = `oauth-user-${randomUUID()}:ws-1`;+ scopes.add(scope);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ useOAuthAppStore.setState({ ...initialOAuthAppState });+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ oauthAppListResource.storage!.remove({ queryKey: 'all', scope: value }),+ oauthAppDetailResource.storage!.remove({ queryKey: 'lca_app_1', scope: value }),+ ]),+ );+ scopes.clear();+ resetCacheScopeBroadcast();+ vi.restoreAllMocks();+ });++ it('paints the persisted list and page before the network answers', async () => {+ await oauthAppListResource.storage!.set(+ { queryKey: 'all', scope },+ { data: [app()], updatedAt: 1 },+ );+ await oauthAppDetailResource.storage!.set(+ { queryKey: 'lca_app_1', scope },+ { data: app(), updatedAt: 1 },+ );+ vi.spyOn(oauthAppService, 'list').mockImplementation(pending);+ vi.spyOn(oauthAppService, 'getById').mockImplementation(pending);++ renderHook(+ () => {+ state().useFetchAppList();+ state().useFetchAppDetail('lca_app_1');+ },+ { wrapper },+ );++ await waitFor(() => {+ expect(oauthAppSelectors.appList(state())).toEqual([app()]);+ expect(oauthAppSelectors.appById('lca_app_1')(state())?.name).toBe('Internal Console');+ });+ });++ it('applies the server answer over the persisted copy', async () => {+ await oauthAppListResource.storage!.set(+ { queryKey: 'all', scope },+ { data: [app()], updatedAt: 1 },+ );+ const used = new Date('2026-11-02T00:00:00Z');+ vi.spyOn(oauthAppService, 'list').mockResolvedValue([app({ lastUsedAt: used })]);++ renderHook(() => state().useFetchAppList(), { wrapper });++ await waitFor(() => expect(oauthAppSelectors.appList(state())?.[0].lastUsedAt).toEqual(used));+ await waitFor(async () =>+ expect(+ (await oauthAppListResource.storage!.get({ queryKey: 'all', scope }))?.data[0].lastUsedAt,+ ).toEqual(used),+ );+ });++ it('disables a row and its page together and rolls both back on failure', async () => {+ vi.spyOn(oauthAppService, 'list').mockResolvedValue([app()]);+ vi.spyOn(oauthAppService, 'getById').mockResolvedValue(app());+ renderHook(+ () => {+ state().useFetchAppList();+ state().useFetchAppDetail('lca_app_1');+ },+ { wrapper },+ );+ await waitFor(() => expect(oauthAppSelectors.appById('lca_app_1')(state())).toBeDefined());++ let reject!: (error: Error) => void;+ vi.spyOn(oauthAppService, 'setEnabled').mockImplementation(+ () => new Promise((_, r) => (reject = r)),+ );++ let call!: Promise<void>;+ act(() => {+ call = state().setAppEnabled('lca_app_1', false);+ });+ expect(oauthAppSelectors.appList(state())?.[0].enabled).toBe(false);+ expect(oauthAppSelectors.appById('lca_app_1')(state())?.enabled).toBe(false);++ await act(async () => {+ reject(new Error('boom'));+ await call.catch(() => {});+ });+ expect(oauthAppSelectors.appList(state())?.[0].enabled).toBe(true);+ expect(oauthAppSelectors.appById('lca_app_1')(state())?.enabled).toBe(true);+ });++ it('marks an app the server no longer returns as not found', async () => {+ vi.spyOn(oauthAppService, 'getById').mockResolvedValue(undefined);++ renderHook(() => state().useFetchAppDetail('lca_app_1'), { wrapper });++ await waitFor(() => expect(oauthAppSelectors.isAppNotFound('lca_app_1')(state())).toBe(true));+ expect(oauthAppSelectors.appById('lca_app_1')(state())).toBeUndefined();+ });++ it('forgets a settled missing app when the cache scope changes', async () => {+ vi.spyOn(oauthAppService, 'getById').mockResolvedValue(undefined);++ renderHook(() => state().useFetchAppDetail('lca_app_1'), { wrapper });+ await waitFor(() => expect(oauthAppSelectors.isAppNotFound('lca_app_1')(state())).toBe(true));++ const next = `oauth-user-${randomUUID()}:ws-2`;+ scopes.add(next);+ act(() => broadcastCacheScope(next));++ // The owning workspace must not inherit the previous scope's "gone" verdict+ // and bounce the page back before its own answer lands.+ expect(oauthAppSelectors.isAppNotFound('lca_app_1')(state())).toBe(false);+ });+});diff --git a/src/store/oauthApp/selectors.ts b/src/store/oauthApp/selectors.tsnew file mode 100644index 00000000000..bef4f948624--- /dev/null+++ b/src/store/oauthApp/selectors.ts@@ -0,0 +1,17 @@+import { type OAuthAppStore } from './store';++const LIST_KEY = 'all';++/** `undefined` until the list has hydrated or answered. */+const appList = (s: OAuthAppStore) => s.appListMap[LIST_KEY];++/** `undefined` while loading, and for an app that does not exist (see `isAppNotFound`). */+const appById = (id: string) => (s: OAuthAppStore) => s.appDetailMap[id];++const isAppNotFound = (id: string) => (s: OAuthAppStore) => !!s.appNotFoundMap[id];++export const oauthAppSelectors = {+ appById,+ appList,+ isAppNotFound,+};diff --git a/src/store/oauthApp/store.ts b/src/store/oauthApp/store.tsnew file mode 100644index 00000000000..98594fb5a77--- /dev/null+++ b/src/store/oauthApp/store.ts@@ -0,0 +1,25 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import { type StateCreator } from 'zustand/vanilla';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { flattenActions } from '../utils/flattenActions';+import { createOAuthAppAction, type OAuthAppAction } from './action';+import { initialOAuthAppState, type OAuthAppState } from './initialState';++export type OAuthAppStore = OAuthAppState & OAuthAppAction;++const createStore: StateCreator<OAuthAppStore, [['zustand/devtools', never]]> = (+ ...parameters: Parameters<StateCreator<OAuthAppStore, [['zustand/devtools', never]]>>+) => ({+ ...initialOAuthAppState,+ ...flattenActions<OAuthAppAction>([createOAuthAppAction(...parameters)]),+});++export const useOAuthAppStore = createWithEqualityFn<OAuthAppStore>()(+ createDevtools('oauthApp')(createStore),+ shallow,+);++expose('oauthApp', useOAuthAppStore);