From 55222c31b3019bb5a84f49e75a51c68617aae517 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 17:55:59 +0000 Subject: [PATCH 1/3] feat(console): Home offers Connect an AI Assistant until the person has connected one; the first-run checklist gains its row Co-Authored-By: Claude --- .../src/pages/settings/FirstRunChecklist.tsx | 39 ++++++++- .../console/connect/connectAssistantPath.ts | 37 ++++++++ .../src/console/connect/connectedAccess.ts | 14 +++- .../src/console/home/ConnectAssistantCard.tsx | 84 +++++++++++++++++++ .../app-shell/src/console/home/HomePage.tsx | 4 + .../console/home/connectAssistantCardGate.ts | 49 +++++++++++ ui/packages/app-shell/src/index.ts | 10 +++ .../app-shell/src/layout/AppHeader.tsx | 25 +----- ui/packages/i18n/src/locales/ar.ts | 12 +++ ui/packages/i18n/src/locales/de.ts | 12 +++ ui/packages/i18n/src/locales/en.ts | 12 +++ ui/packages/i18n/src/locales/es.ts | 12 +++ ui/packages/i18n/src/locales/fr.ts | 12 +++ ui/packages/i18n/src/locales/ja.ts | 12 +++ ui/packages/i18n/src/locales/ko.ts | 12 +++ ui/packages/i18n/src/locales/pt-BR.ts | 12 +++ ui/packages/i18n/src/locales/ru.ts | 12 +++ ui/packages/i18n/src/locales/zh-Hans.ts | 12 +++ ui/packages/i18n/src/locales/zh-Hant.ts | 12 +++ 19 files changed, 370 insertions(+), 24 deletions(-) create mode 100644 ui/packages/app-shell/src/console/connect/connectAssistantPath.ts create mode 100644 ui/packages/app-shell/src/console/home/ConnectAssistantCard.tsx create mode 100644 ui/packages/app-shell/src/console/home/connectAssistantCardGate.ts diff --git a/ui/apps/console/src/pages/settings/FirstRunChecklist.tsx b/ui/apps/console/src/pages/settings/FirstRunChecklist.tsx index 7069a8b187e..705c457cf4e 100644 --- a/ui/apps/console/src/pages/settings/FirstRunChecklist.tsx +++ b/ui/apps/console/src/pages/settings/FirstRunChecklist.tsx @@ -33,6 +33,11 @@ * Only for a session that may write mail. * 6. Invite colleagues: a second member or a pending invitation; links to * Setup → Users, where Invite User is. + * 7. Connect an AI assistant: done once this administrator has authorized an + * AI assistant or holds an API key that still works, read from those + * records by `useConnectedAccess` (the read Connect an AI Assistant's + * Connected line uses), never from a click; links to that page. Only + * where the served Account app carries the page (MCP turned on). * * A row whose state cannot be read is left out rather than shown as not done. * Once every row shown is done the checklist draws nothing; it comes back on @@ -63,7 +68,7 @@ import { Link } from 'react-router-dom'; import { toast } from 'sonner'; import { CheckCircle2, Circle, Loader2, X } from 'lucide-react'; import { Button, cn } from '@object-ui/components'; -import { useMetadata, resolveSetupAppPath } from '@object-ui/app-shell'; +import { connectAssistantPath, resolveSetupAppPath, useConnectedAccess, useMetadata } from '@object-ui/app-shell'; import { useAuth } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -403,6 +408,10 @@ export function FirstRunChecklist() { const colleagues = invited && invited.identity === identity ? invited.colleagues : undefined; const dismissed = recordKey !== null && (hiddenKey === recordKey || wasDismissed(deviceStorage(), recordKey)); + // Connect an AI Assistant: the row reads whether this administrator has + // connected one only once the checklist is going to draw. + const assistantPath = connectAssistantPath(apps); + const assistant = useConnectedAccess({ enabled: Boolean(settings && !dismissed && assistantPath) }); const setSettings = (update: (prev: ChecklistSettingsState) => ChecklistSettingsState) => setLoaded((prev) => (prev ? { identity: prev.identity, settings: update(prev.settings) } : prev)); @@ -546,6 +555,34 @@ export function FirstRunChecklist() { }); } + if (assistantPath && assistant.state === 'ready') { + const done = assistant.connected; + rows.push({ + id: 'connect_assistant', + done, + node: ( + + } + /> + ), + }); + } + const doneCount = rows.filter((row) => row.done).length; if (rows.length === 0 || doneCount === rows.length) return null; diff --git a/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts b/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts new file mode 100644 index 00000000000..3967205f095 --- /dev/null +++ b/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Where Connect an AI Assistant opens, for every entry that leads to it: the + * avatar menu item, the Home card and the administrator's first-run checklist + * row. + * + * The page is `@objectstack/mcp`'s `connect_agent`, reached through the served + * Account app. `@objectstack/mcp` contributes the Account nav entry exactly + * when it registers the page, so a deployment with MCP turned off answers + * `undefined` here and no entry draws a dead link. + */ + +import { appAddressSegment } from '../../utils/appRoute.js'; + +/** The page the Connect an AI Assistant entries open (`@objectstack/mcp`). */ +export const CONNECT_ASSISTANT_PAGE = 'connect_agent'; + +/** + * Whether a served navigation tree carries a `page` entry for `pageName`, + * groups included. The tree is the server's, already folded and filtered for + * this caller, so a hit means the page is registered and reachable. + */ +export function navCarriesPage(items: unknown, pageName: string): boolean { + if (!Array.isArray(items)) return false; + return items.some((item: any) => + (item?.type === 'page' && item?.pageName === pageName) + || navCarriesPage(item?.children, pageName)); +} + +/** The Console path of Connect an AI Assistant, or `undefined` while the served Account app does not carry it. */ +export function connectAssistantPath(apps: readonly any[] | null | undefined): string | undefined { + const accountApp = (apps || []).find((a: any) => a?.name === 'account'); + return accountApp && navCarriesPage((accountApp as any).navigation, CONNECT_ASSISTANT_PAGE) + ? `/apps/${appAddressSegment(apps, accountApp)}/page/${CONNECT_ASSISTANT_PAGE}` + : undefined; +} diff --git a/ui/packages/app-shell/src/console/connect/connectedAccess.ts b/ui/packages/app-shell/src/console/connect/connectedAccess.ts index 29964ac193f..9d5dca3dd0b 100644 --- a/ui/packages/app-shell/src/console/connect/connectedAccess.ts +++ b/ui/packages/app-shell/src/console/connect/connectedAccess.ts @@ -26,6 +26,10 @@ * found a connection: a failed read is never reported as "nothing connected". * `unknown` also covers a render without an adapter or a signed-in person. * + * Its readers: the Connected line on Connect an AI Assistant, the Home card + * that offers connecting one (hidden once connected), and the administrator's + * first-run checklist row (done once connected). + * * It reads again when either record changes on this page: the adapter's * mutation event (or the mint's `notifyDataChanged`) for `sys_api_key`, and the * assistants list's withdraw, which announces `sys_oauth_consent`. @@ -111,10 +115,16 @@ export function combineConnectedReads( return { state: 'loading' }; } -export function useConnectedAccess(): ConnectedAccess { +/** + * `enabled: false` reads nothing and answers `unknown`: a caller that may not + * need the answer (a dismissed Home card, a member's Home with no checklist) + * costs no request. Hooks cannot be called conditionally, so this is how a + * caller skips the read. + */ +export function useConnectedAccess({ enabled = true }: { enabled?: boolean } = {}): ConnectedAccess { const adapter = useAdapter(); const { user } = useAuth(); - const userId = user?.id ?? null; + const userId = enabled ? user?.id ?? null : null; const consentsNonce = useDataInvalidation('sys_oauth_consent'); const keysNonce = useDataInvalidation('sys_api_key'); diff --git a/ui/packages/app-shell/src/console/home/ConnectAssistantCard.tsx b/ui/packages/app-shell/src/console/home/ConnectAssistantCard.tsx new file mode 100644 index 00000000000..6bdd8fed8ef --- /dev/null +++ b/ui/packages/app-shell/src/console/home/ConnectAssistantCard.tsx @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Home's "Connect an AI Assistant" card: one plain sentence that this system + * can be worked from Claude, Doubao and similar AI assistants, and one button + * to Connect an AI Assistant. For every signed-in person. + * + * Drawn only when all of these hold: + * - the served Account app carries the page (`connectAssistantPath`; a + * deployment with MCP turned off has nowhere to send the button); + * - the person has not hidden it on this browser (`connectAssistantCardGate`); + * - `useConnectedAccess` answered that the person has connected nothing: no + * authorized assistant and no API key that still works. While that read is + * out, or when it cannot be read, the card stays away rather than offering + * a connection the person may already have. + * + * Once the person connects one it is gone on the next read, and it does not + * come back after a dismissal. + */ + +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { useAuth } from '@object-ui/auth'; +import { Button } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { Bot, X } from 'lucide-react'; +import { useMetadata } from '../../providers/MetadataProvider.js'; +import { connectAssistantPath } from '../connect/connectAssistantPath.js'; +import { useConnectedAccess } from '../connect/connectedAccess.js'; +import { cardStorage, markCardDismissed, wasCardDismissed } from './connectAssistantCardGate.js'; + +export function ConnectAssistantCard() { + const { t } = useObjectTranslation(); + const navigate = useNavigate(); + const { user } = useAuth(); + const { apps } = useMetadata(); + const userId = user?.id ?? null; + const path = connectAssistantPath(apps); + // Hidden in this mount by the close button; an earlier visit's record is read below. + const [hiddenFor, setHiddenFor] = useState(null); + const dismissed = userId !== null && (hiddenFor === userId || wasCardDismissed(cardStorage(), userId)); + const access = useConnectedAccess({ enabled: Boolean(path && userId && !dismissed) }); + + if (!path || !userId || dismissed) return null; + if (access.state !== 'ready' || access.connected) return null; + + const dismiss = () => { + markCardDismissed(cardStorage(), userId); + setHiddenFor(userId); + }; + + return ( +
+
+
+ +
+

+ {t('home.connectAssistant.title')} +

+

{t('home.connectAssistant.body')}

+
+ + +
+
+
+ ); +} diff --git a/ui/packages/app-shell/src/console/home/HomePage.tsx b/ui/packages/app-shell/src/console/home/HomePage.tsx index 793910bc76a..a6d7a220d97 100644 --- a/ui/packages/app-shell/src/console/home/HomePage.tsx +++ b/ui/packages/app-shell/src/console/home/HomePage.tsx @@ -35,6 +35,7 @@ import { HomeAppsStrip } from './HomeAppsStrip.js'; import { appSegmentOf, lastOpenedByApp } from './appLastOpened.js'; import { recentItemObject, recentItemTypeLabel } from './recentItemTypeLabel.js'; import { RecoveryPasswordReminder } from './RecoveryPasswordReminder.js'; +import { ConnectAssistantCard } from './ConnectAssistantCard.js'; import { DeploymentNotice } from '../deployment-notice/DeploymentNotice.js'; import { HomeActionCenter, HomeContinue, HomeActivity, HomePendingDraftsRow, type RecentItemContext } from './HomeRail.js'; import { resolveI18nLabel } from '@objectstack/spec/ui'; @@ -575,6 +576,7 @@ export function HomePage() { one person's; this is the deployment's. */} +
{/* Role-aware empty state. ADMINS get the AI-first magic moment as the @@ -662,6 +664,8 @@ export function HomePage() { {/* objectstack#30120 — see the empty-state branch above. */} + {/* objectstack#30895 — every person: connect an AI assistant, until they have or hide it. */} + {/* The content column (objectui#12601): 1120 px, centred, 28 px above the first section and 28 px between sections. No bordered card around the diff --git a/ui/packages/app-shell/src/console/home/connectAssistantCardGate.ts b/ui/packages/app-shell/src/console/home/connectAssistantCardGate.ts new file mode 100644 index 00000000000..31f5c14afa5 --- /dev/null +++ b/ui/packages/app-shell/src/console/home/connectAssistantCardGate.ts @@ -0,0 +1,49 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Whether the person hid Home's "Connect an AI Assistant" card. Kept apart + * from `ConnectAssistantCard.tsx` so that module exports a component only. + * + * Home keeps no server-side preference; its other dismissible items (the + * recovery-password reminder, the first-run checklist) remember a dismissal in + * this browser's `localStorage`, and so does this card. The key carries the + * person, so on a shared browser one person's dismissal does not hide the card + * for the next. A storage that cannot be read answers "not hidden"; one that + * cannot be written hides the card for this page only. + */ + +export type CardStorage = Pick; + +const DISMISS_PREFIX = 'os:home:connect-assistant-dismissed'; + +/** The record that this person hid the card on this browser. */ +export function connectAssistantCardKey(userId: string): string { + return `${DISMISS_PREFIX}:${userId}`; +} + +/** The browser's `localStorage`, or `undefined` where reading it throws (a private window). */ +export function cardStorage(): CardStorage | undefined { + try { + return typeof localStorage !== 'undefined' ? localStorage : undefined; + } catch { + return undefined; + } +} + +export function wasCardDismissed(storage: CardStorage | undefined, userId: string): boolean { + if (!storage) return false; + try { + return storage.getItem(connectAssistantCardKey(userId)) !== null; + } catch { + return false; + } +} + +export function markCardDismissed(storage: CardStorage | undefined, userId: string): void { + if (!storage) return; + try { + storage.setItem(connectAssistantCardKey(userId), new Date().toISOString()); + } catch { + // Not kept: the card stays hidden for this page only. + } +} diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index 594b8f09b4b..2746b6c3b0f 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -316,6 +316,16 @@ export { useInvitationSignUpJoin, type InvitationSignUpJoin } from './console/au export { ForgotPasswordPage as DefaultForgotPasswordPage } from './console/auth/ForgotPasswordPage.js'; export { HomeLayout as DefaultHomeLayout, HomeLayout } from './console/home/HomeLayout.js'; export { HomePage as DefaultHomePage, HomePage } from './console/home/HomePage.js'; +// Whether the signed-in person has connected an AI assistant (or holds a +// working API key), and where Connect an AI Assistant opens: the one read and +// the one path the Connect page, Home's card and the first-run checklist share +// (#30898, #30895). +export { + useConnectedAccess, + type ConnectedAccess, + type ConnectedEntry, +} from './console/connect/connectedAccess.js'; +export { connectAssistantPath } from './console/connect/connectAssistantPath.js'; export { OrganizationsLayout as DefaultOrganizationsLayout } from './console/organizations/OrganizationsLayout.js'; export { OrganizationsPage as DefaultOrganizationsPage } from './console/organizations/OrganizationsPage.js'; diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index c9bc0aec960..58464aba442 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -93,6 +93,7 @@ import { useBundledReads } from '../providers/bundledReads.js'; import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { preferLocal, matchAppBySegment, appStudioRoutePath } from '../utils/index.js'; import { appAddressSegment } from '../utils/appRoute.js'; +import { connectAssistantPath } from '../console/connect/connectAssistantPath.js'; import { getIcon } from '../utils/getIcon.js'; import { useNavigationContext } from '../context/NavigationContext.js'; import { useCommandPalette, useCommandPaletteProviderMounted } from '../context/CommandPaletteProvider.js'; @@ -366,21 +367,6 @@ function matchesShortcutChord( return e.key.toLowerCase() === chord.key; } -/** The page the Connect an AI Assistant entries open (`@objectstack/mcp`). */ -const CONNECT_ASSISTANT_PAGE = 'connect_agent'; - -/** - * Whether a served navigation tree carries a `page` entry for `pageName`, - * groups included. The tree is the server's, already folded and filtered for - * this caller, so a hit means the page is registered and reachable. - */ -function navCarriesPage(items: unknown, pageName: string): boolean { - if (!Array.isArray(items)) return false; - return items.some((item: any) => - (item?.type === 'page' && item?.pageName === pageName) - || navCarriesPage(item?.children, pageName)); -} - /** * A keydown aimed at something the user types into: a text field, a select, * a content-editable region (rich-text and code editors), or an ARIA textbox. @@ -647,10 +633,7 @@ export function AppHeader({ // Drawn only while the served Account app carries the page: `@objectstack/mcp` // contributes that entry exactly when it registers the page, so a deployment // with MCP turned off shows no dead item. - const accountApp = (metadataApps || []).find((a: any) => a?.name === 'account'); - const connectAssistantPath = accountApp && navCarriesPage((accountApp as any).navigation, CONNECT_ASSISTANT_PAGE) - ? `/apps/${appAddressSegment(metadataApps, accountApp)}/page/${CONNECT_ASSISTANT_PAGE}` - : undefined; + const connectAssistantHref = connectAssistantPath(metadataApps); // The app the route is in. const appNameKey = activeAppName || currentAppName || appNameFromRoute; @@ -1296,9 +1279,9 @@ export function AppHeader({ {t('user.profile', { defaultValue: 'Profile' })} - {connectAssistantPath && ( + {connectAssistantHref && ( leaveTo(connectAssistantPath)} + onClick={() => leaveTo(connectAssistantHref)} className="cursor-pointer" data-testid="header-connect-ai-assistant" > diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 630942ef48a..8ed177a498c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2505,6 +2505,12 @@ const ar = { done: "انضم زملاء أو تمت دعوتهم.", action: "دعوة", }, + connectAssistant: { + title: 'ربط مساعد ذكاء اصطناعي', + todo: 'استخدم هذا النظام من Claude وDoubao والمساعدين المشابهين باسمك أنت.', + done: 'تم ربط مساعد ذكاء اصطناعي أو مفتاح API خاص بك.', + action: 'ربط', + }, }, error: { connectionFailed: "تعذّر الاتصال بالخادم", @@ -3489,6 +3495,12 @@ const ar = { cta: "تعيين كلمة المرور", dismiss: "تجاهل", }, + connectAssistant: { + title: 'استخدم هذا النظام من مساعد الذكاء الاصطناعي', + body: 'يمكنك عرض سجلاتك وتغييرها من Claude وDoubao ومساعدي الذكاء الاصطناعي المشابهين. يتصرف كل منهم باسمك وبصلاحياتك أنت.', + action: 'ربط مساعد ذكاء اصطناعي', + dismiss: 'إخفاء', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index b18287bab88..6698720ba2a 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2266,6 +2266,12 @@ const de = { done: "Kollegen sind beigetreten oder wurden eingeladen.", action: "Einladen", }, + connectAssistant: { + title: 'KI-Assistenten verbinden', + todo: 'Arbeiten Sie in diesem System aus Claude, Doubao und ähnlichen Assistenten, als Sie selbst.', + done: 'Ein KI-Assistent oder API-Schlüssel von Ihnen ist verbunden.', + action: 'Verbinden', + }, }, error: { connectionFailed: "Verbindung zum Server nicht möglich", @@ -3235,6 +3241,12 @@ const de = { cta: "Passwort festlegen", dismiss: "Ausblenden", }, + connectAssistant: { + title: 'Arbeiten Sie hier mit Ihrem KI-Assistenten', + body: 'Sie können Ihre Datensätze aus Claude, Doubao und ähnlichen KI-Assistenten abrufen und ändern. Jeder handelt in Ihrem Namen, mit Ihren eigenen Berechtigungen.', + action: 'KI-Assistenten verbinden', + dismiss: 'Ausblenden', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 37b81f8f545..602df912334 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2442,6 +2442,12 @@ const en = { done: 'Colleagues have joined or been invited.', action: 'Invite', }, + connectAssistant: { + title: 'Connect an AI assistant', + todo: 'Work in this system from Claude, Doubao and similar assistants, as yourself.', + done: 'An AI assistant or API key of yours is connected.', + action: 'Connect', + }, }, error: { connectionFailed: 'Cannot connect to server', @@ -3896,6 +3902,12 @@ const en = { cta: 'Set password', dismiss: 'Dismiss', }, + connectAssistant: { + title: 'Work here from your AI assistant', + body: 'You can look up and change your records from Claude, Doubao and similar AI assistants. Each one acts as you, with your own permissions.', + action: 'Connect an AI Assistant', + dismiss: 'Hide', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 25e0ac36c55..60828da210b 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2328,6 +2328,12 @@ const es = { done: "Hay compañeros que se han unido o han sido invitados.", action: "Invitar", }, + connectAssistant: { + title: 'Conectar un asistente de IA', + todo: 'Trabaja en este sistema desde Claude, Doubao y asistentes similares, como tú mismo.', + done: 'Tienes conectado un asistente de IA o una clave de API.', + action: 'Conectar', + }, }, error: { connectionFailed: "No se puede conectar al servidor", @@ -3300,6 +3306,12 @@ const es = { cta: "Establecer contraseña", dismiss: "Descartar", }, + connectAssistant: { + title: 'Trabaja aquí desde tu asistente de IA', + body: 'Puedes consultar y cambiar tus registros desde Claude, Doubao y asistentes de IA similares. Cada uno actúa como tú, con tus propios permisos.', + action: 'Conectar un asistente de IA', + dismiss: 'Ocultar', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d6bab9e4a1a..83cbf94afcd 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2324,6 +2324,12 @@ const fr = { done: "Des collègues ont rejoint l’organisation ou ont été invités.", action: "Inviter", }, + connectAssistant: { + title: 'Connecter un assistant IA', + todo: "Travaillez dans ce système depuis Claude, Doubao et d'autres assistants, en votre nom.", + done: "Un assistant IA ou une clé d'API à vous est connecté.", + action: 'Connecter', + }, }, error: { connectionFailed: "Impossible de se connecter au serveur", @@ -3296,6 +3302,12 @@ const fr = { cta: "Définir le mot de passe", dismiss: "Ignorer", }, + connectAssistant: { + title: 'Travaillez ici depuis votre assistant IA', + body: "Vous pouvez consulter et modifier vos enregistrements depuis Claude, Doubao et d'autres assistants IA. Chacun agit en votre nom, avec vos propres autorisations.", + action: 'Connecter un assistant IA', + dismiss: 'Masquer', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index c2c07a31fe5..71494689c22 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2268,6 +2268,12 @@ const ja = { done: "同僚が参加済みか、招待済みです。", action: "招待", }, + connectAssistant: { + title: 'AI アシスタントを接続', + todo: 'Claude や Doubao などのアシスタントから、あなた自身としてこのシステムを使えます。', + done: 'あなたの AI アシスタントまたは API キーが接続されています。', + action: '接続', + }, }, error: { connectionFailed: "サーバーに接続できません", @@ -3237,6 +3243,12 @@ const ja = { cta: "パスワードを設定", dismiss: "閉じる", }, + connectAssistant: { + title: 'AI アシスタントからこのシステムを使う', + body: 'Claude や Doubao などの AI アシスタントから、レコードの参照や変更ができます。アシスタントは常にあなたとして、あなたの権限で動作します。', + action: 'AI アシスタントを接続', + dismiss: '非表示', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index eaf8905118b..94d141feaa2 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2266,6 +2266,12 @@ const ko = { done: "동료가 참여했거나 초대되었습니다.", action: "초대", }, + connectAssistant: { + title: 'AI 어시스턴트 연결', + todo: 'Claude, Doubao 같은 어시스턴트에서 본인으로서 이 시스템을 사용하세요.', + done: 'AI 어시스턴트 또는 API 키가 연결되어 있습니다.', + action: '연결', + }, }, error: { connectionFailed: "서버에 연결할 수 없습니다", @@ -3235,6 +3241,12 @@ const ko = { cta: "비밀번호 설정", dismiss: "닫기", }, + connectAssistant: { + title: 'AI 어시스턴트에서 이 시스템 사용하기', + body: 'Claude, Doubao 같은 AI 어시스턴트에서 레코드를 조회하고 변경할 수 있습니다. 어시스턴트는 항상 사용자 본인으로서, 본인의 권한으로 동작합니다.', + action: 'AI 어시스턴트 연결', + dismiss: '숨기기', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0202006d085..cb6dc97c463 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2323,6 +2323,12 @@ const pt = { done: "Há colegas que entraram ou foram convidados.", action: "Convidar", }, + connectAssistant: { + title: 'Conectar um assistente de IA', + todo: 'Trabalhe neste sistema pelo Claude, Doubao e assistentes semelhantes, como você mesmo.', + done: 'Um assistente de IA ou uma chave de API sua está conectada.', + action: 'Conectar', + }, }, error: { connectionFailed: "Não é possível conectar ao servidor", @@ -3295,6 +3301,12 @@ const pt = { cta: "Definir senha", dismiss: "Dispensar", }, + connectAssistant: { + title: 'Trabalhe aqui pelo seu assistente de IA', + body: 'Você pode consultar e alterar seus registros pelo Claude, Doubao e assistentes de IA semelhantes. Cada um age como você, com suas próprias permissões.', + action: 'Conectar um assistente de IA', + dismiss: 'Ocultar', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4fecf7b21a2..e233970e853 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2392,6 +2392,12 @@ const ru = { done: "Коллеги присоединились или приглашены.", action: "Пригласить", }, + connectAssistant: { + title: 'Подключить ИИ-ассистента', + todo: 'Работайте в этой системе из Claude, Doubao и похожих ассистентов от своего имени.', + done: 'Ваш ИИ-ассистент или API-ключ подключён.', + action: 'Подключить', + }, }, error: { connectionFailed: "Не удаётся подключиться к серверу", @@ -3370,6 +3376,12 @@ const ru = { cta: "Задать пароль", dismiss: "Закрыть", }, + connectAssistant: { + title: 'Работайте здесь через ИИ-ассистента', + body: 'Вы можете просматривать и изменять свои записи из Claude, Doubao и похожих ИИ-ассистентов. Каждый действует от вашего имени, с вашими правами.', + action: 'Подключить ИИ-ассистента', + dismiss: 'Скрыть', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 91109e6c060..2287cd1faae 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2040,6 +2040,12 @@ const zh = { done: '已有同事加入或已发出邀请。', action: '邀请', }, + connectAssistant: { + title: '连接 AI 助手', + todo: '在 Claude、豆包等助手里以你自己的身份使用本系统。', + done: '你已连接了 AI 助手或 API 密钥。', + action: '连接', + }, }, error: { connectionFailed: '无法连接到服务器', @@ -3351,6 +3357,12 @@ const zh = { cta: '设置密码', dismiss: '关闭', }, + connectAssistant: { + title: '在 AI 助手里使用本系统', + body: '你可以在 Claude、豆包等 AI 助手里查询和修改你的记录。助手始终以你的身份、按你的权限操作。', + action: '连接 AI 助手', + dismiss: '隐藏', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index bb870db0ca1..b2f5332d5fd 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2040,6 +2040,12 @@ const zhHant = { done: '已有同事加入或已發出邀請。', action: '邀請', }, + connectAssistant: { + title: '連線 AI 助手', + todo: '在 Claude、豆包等助手裡以你自己的身份使用本系統。', + done: '你已連線了 AI 助手或 API 金鑰。', + action: '連線', + }, }, error: { connectionFailed: '無法連線到伺服器', @@ -3351,6 +3357,12 @@ const zhHant = { cta: '設定密碼', dismiss: '關閉', }, + connectAssistant: { + title: '在 AI 助手裡使用本系統', + body: '你可以在 Claude、豆包等 AI 助手裡查詢和修改你的記錄。助手始終以你的身份、按你的權限操作。', + action: '連線 AI 助手', + dismiss: '隱藏', + }, pendingDrafts: { // objectui#12602 — the drafts row in Home's "My work" section: the // count, then the first draft names joined by `nameSeparator`, in From e95b3a8a3a3941d4d73b69ad8a19c857cd9be30a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 18:08:20 +0000 Subject: [PATCH 2/3] test(console): Home's Connect an AI Assistant card and the checklist row, through the real router and data bus Co-Authored-By: Claude --- .changeset/30895-home-connect-assistant.md | 14 ++ .../__tests__/FirstRunChecklist.test.tsx | 96 +++++++- .../src/console/connect/connectedAccess.ts | 7 +- .../ConnectAssistantCard-30895.test.tsx | 209 ++++++++++++++++++ 4 files changed, 321 insertions(+), 5 deletions(-) create mode 100644 .changeset/30895-home-connect-assistant.md create mode 100644 ui/packages/app-shell/src/console/home/__tests__/ConnectAssistantCard-30895.test.tsx diff --git a/.changeset/30895-home-connect-assistant.md b/.changeset/30895-home-connect-assistant.md new file mode 100644 index 00000000000..d7be1d0594b --- /dev/null +++ b/.changeset/30895-home-connect-assistant.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/console': patch +--- + +feat(console): Home offers Connect an AI Assistant until the person has connected one; the first-run checklist gains its row + +Clause-②: yes (widening) +Metadata-protocol: none + +- **`@object-ui/app-shell`**: Home shows a card to every signed-in person who has connected nothing yet: they can work in this system from Claude, Doubao and similar AI assistants, as themselves, with one button to Connect an AI Assistant. It is hidden once they have authorized an assistant or hold an API key that still works (read by `useConnectedAccess`, the same read as the Connect page's Connected line), and once they close it (remembered for that person on that browser, like Home's other dismissible items). While the read is out or fails, and where MCP is turned off, it is not shown. `useConnectedAccess` and `connectAssistantPath` are now exported, and the avatar menu item reads its path from `connectAssistantPath`. +- **`@object-ui/console`**: the administrator's first-run checklist gains "Connect an AI assistant", done once that administrator has authorized an assistant or holds a working API key (never from a click), with a link to the page; left out when that cannot be read or MCP is turned off. +- **`@object-ui/i18n`**: `home.connectAssistant.title`, `body`, `action`, `dismiss` and `console.firstRunChecklist.connectAssistant.title`, `todo`, `done`, `action` added in all eleven packs. diff --git a/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx b/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx index 4774d50af00..9888d6459c2 100644 --- a/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx @@ -27,7 +27,10 @@ import { type MePermissionsResponse, } from '@object-ui/permissions'; -const { AUTH, toastError, toastSuccess } = vi.hoisted(() => ({ +const { AUTH, toastError, toastSuccess, SHELL } = vi.hoisted(() => ({ + // What the Connect an AI Assistant row reads: the served apps (for the page's + // path) and the adapter (for what this administrator has connected). + SHELL: { apps: [] as unknown[], adapter: null as unknown }, AUTH: { user: { id: 'u_admin' }, activeOrganization: { id: 'org_1', name: 'Default Organization' } as { id: string; name: string }, @@ -47,10 +50,15 @@ vi.mock('sonner', () => ({ toast: { error: toastError, success: toastSuccess } } // provider; the real surface is inherited and only that read is stubbed. vi.mock('@object-ui/app-shell', async (importOriginal) => ({ ...(await importOriginal>()), - useMetadata: () => ({ apps: [], objects: [], loading: false, error: null, refresh: async () => {} }), + useMetadata: () => ({ apps: SHELL.apps, objects: [], loading: false, error: null, refresh: async () => {} }), resolveSetupAppPath: () => '/apps/setup', })); +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => SHELL.adapter, +})); + import { FirstRunChecklist } from '../FirstRunChecklist'; import { __resetBootPainted } from '../../../loadLocales'; import type { Specifier } from '../types'; @@ -221,6 +229,8 @@ beforeEach(() => { mailValues = { provider: resolved('smtp') }; putRefusal = null; AUTH.activeOrganization = { id: 'org_1', name: 'Default Organization' }; + SHELL.apps = []; + SHELL.adapter = null; AUTH.getMembers.mockReset().mockResolvedValue([{ id: 'm_1' }]); AUTH.listInvitations.mockReset().mockResolvedValue([]); browserZone = 'Asia/Shanghai'; @@ -411,3 +421,85 @@ describe('the reads wait for the first paint (objectui#12980)', () => { expect(calls('GET', '/api/settings')).toHaveLength(1); }); }); + +describe('Connect an AI assistant: done from a real record, never from a click', () => { + const ACCOUNT_APP = { + name: 'account', + navigation: [{ type: 'group', id: 'grp', children: [{ type: 'page', id: 'nav_connect_agent', pageName: 'connect_agent' }] }], + }; + let granted: unknown[]; + let keys: Record[]; + let list: ReturnType; + let find: ReturnType; + + beforeEach(() => { + granted = []; + keys = []; + list = vi.fn(async () => ({ clients: granted, truncated: false })); + find = vi.fn(async () => ({ data: keys })); + SHELL.apps = [ACCOUNT_APP]; + SHELL.adapter = { getClient: () => ({ oauth: { authorizedClients: { list } } }), find }; + }); + + it('nothing connected: the row is not done and links to the page', async () => { + keys = [{ id: 'k_old', name: 'old', revoked: true, expires_at: null }]; + renderChecklist(ADMIN); + const r = await screen.findByTestId('first-run-checklist-row-connect_assistant'); + expect(r.getAttribute('data-done')).toBe('false'); + expect(within(r).getByText('Work in this system from Claude, Doubao and similar assistants, as yourself.')).toBeTruthy(); + expect(screen.getByTestId('first-run-checklist-link-connect_assistant').getAttribute('href')).toBe( + '/apps/account/page/connect_agent', + ); + expect(screen.getByTestId('first-run-checklist-progress').textContent).toBe('0 of 7 done'); + expect(find).toHaveBeenCalledWith('sys_api_key', expect.objectContaining({ $filter: { user_id: 'u_admin' } })); + }); + + it('an authorized assistant makes it done', async () => { + granted = [{ id: 'c1', clientId: 'cl', name: 'Claude Desktop', scopes: [], organizationId: null, authorizedAt: null, lastUsedAt: null }]; + renderChecklist(ADMIN); + const r = await screen.findByTestId('first-run-checklist-row-connect_assistant'); + expect(r.getAttribute('data-done')).toBe('true'); + expect(within(r).getByText('An AI assistant or API key of yours is connected.')).toBeTruthy(); + }); + + it('an API key that still works makes it done', async () => { + keys = [{ id: 'k_live', name: 'doubao key', revoked: false, expires_at: null }]; + renderChecklist(ADMIN); + const r = await screen.findByTestId('first-run-checklist-row-connect_assistant'); + expect(r.getAttribute('data-done')).toBe('true'); + }); + + it('opening the page through the row writes nothing and leaves it not done', async () => { + renderChecklist(ADMIN); + const link = await screen.findByTestId('first-run-checklist-link-connect_assistant'); + fireEvent.click(link); + await settle(); + expect(row('connect_assistant').getAttribute('data-done')).toBe('false'); + expect(fetchMock.mock.calls.filter(([, init]) => ((init as RequestInit | undefined)?.method ?? 'GET') !== 'GET')).toHaveLength(0); + }); + + it('a read that fails leaves the row out rather than not done', async () => { + list.mockRejectedValue(new Error('down')); + renderChecklist(ADMIN); + await screen.findByTestId('first-run-checklist-row-invite'); + await settle(); + expect(screen.queryByTestId('first-run-checklist-row-connect_assistant')).toBeNull(); + }); + + it('MCP turned off (no page in the Account app): no row and no read', async () => { + SHELL.apps = [{ name: 'account', navigation: [] }]; + renderChecklist(ADMIN); + await screen.findByTestId('first-run-checklist-row-invite'); + await settle(); + expect(screen.queryByTestId('first-run-checklist-row-connect_assistant')).toBeNull(); + expect(list).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + }); + + it('a member reads nothing of it', async () => { + renderChecklist(MEMBER); + await settle(); + expect(list).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/console/connect/connectedAccess.ts b/ui/packages/app-shell/src/console/connect/connectedAccess.ts index 9d5dca3dd0b..62fa2247afe 100644 --- a/ui/packages/app-shell/src/console/connect/connectedAccess.ts +++ b/ui/packages/app-shell/src/console/connect/connectedAccess.ts @@ -134,9 +134,10 @@ export function useConnectedAccess({ enabled = true }: { enabled?: boolean } = { useEffect(() => { if (!adapter || !userId) return; let live = true; - adapter - .getClient() - .oauth.authorizedClients.list() + // Through a promise, so an adapter without the auth client is a failed + // read rather than a throw out of the effect. + Promise.resolve() + .then(() => adapter.getClient().oauth.authorizedClients.list()) .then( (value) => live && setAssistants({ state: 'ready', value: value.clients.map(assistantEntry) }), () => live && setAssistants({ state: 'failed' }), diff --git a/ui/packages/app-shell/src/console/home/__tests__/ConnectAssistantCard-30895.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/ConnectAssistantCard-30895.test.tsx new file mode 100644 index 00000000000..de1b590169c --- /dev/null +++ b/ui/packages/app-shell/src/console/home/__tests__/ConnectAssistantCard-30895.test.tsx @@ -0,0 +1,209 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Home's "Connect an AI Assistant" card: shown to a signed-in person who has + * connected nothing, hidden once they have connected one or hidden it. + * + * - §1 nothing connected (no authorized assistant; only a revoked or expired + * key): the card is shown, and its button opens Connect an AI Assistant; + * - §2 an authorized assistant, or a key that still works: no card; + * - §3 while the read is out, or when it fails: no card; + * - §4 the close button hides it for this person on this browser, also in a + * later mount (which reads nothing), and not for another person; + * - §5 MCP turned off (the Account app carries no page): no card, no read; + * - §6 connecting while it is shown (a key minted on this page) takes it away. + * + * Rendered with the real router, the real data bus and the real hook; only + * the adapter, the person and the served apps are stubbed. `t` echoes the key. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, language: 'en' }), +})); + +const SHELL = vi.hoisted(() => ({ + adapter: null as unknown, + user: { id: 'user_me' } as { id: string } | null, + apps: [] as unknown[], +})); + +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => SHELL.adapter, +})); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: SHELL.user }), +})); +vi.mock('../../../providers/MetadataProvider.js', () => ({ + useMetadata: () => ({ apps: SHELL.apps }), +})); + +import { notifyDataChanged } from '@object-ui/react'; +import { ConnectAssistantCard } from '../ConnectAssistantCard'; +import { connectAssistantCardKey } from '../connectAssistantCardGate'; + +const ACCOUNT_APP = { + name: 'account', + navigation: [ + { type: 'group', id: 'grp_account_ai_assistant', children: [{ type: 'page', id: 'nav_connect_agent', pageName: 'connect_agent' }] }, + ], +}; +const ASSISTANT = { + id: 'consent_1', + clientId: 'client_desktop', + name: 'Claude Desktop', + scopes: [], + organizationId: null, + authorizedAt: '2026-11-07T10:00:00.000Z', + lastUsedAt: null, +}; +const LIVE_KEY = { id: 'k_live', name: 'doubao key', created_at: '2026-11-07T10:00:00.000Z', last_used_at: null, expires_at: null, revoked: false }; +const DEAD_KEYS = [ + { id: 'k_revoked', name: 'old', created_at: null, last_used_at: null, expires_at: null, revoked: true }, + { id: 'k_expired', name: 'stale', created_at: null, last_used_at: null, expires_at: '2026-01-01T00:00:00.000Z', revoked: false }, +]; + +let granted: unknown[]; +let keyRows: Record[]; +let list: ReturnType; +let find: ReturnType; + +beforeEach(() => { + localStorage.clear(); + granted = []; + keyRows = DEAD_KEYS.map((k) => ({ ...k })); + list = vi.fn(async () => ({ clients: [...granted], truncated: false })); + find = vi.fn(async () => ({ data: keyRows.map((k) => ({ ...k })) })); + SHELL.user = { id: 'user_me' }; + SHELL.apps = [ACCOUNT_APP]; + SHELL.adapter = { getClient: () => ({ oauth: { authorizedClients: { list } } }), find }; +}); + +afterEach(() => { + cleanup(); +}); + +function renderHome() { + return render( + + + } /> + } /> + + , + ); +} + +async function settled() { + await waitFor(() => { + expect(list).toHaveBeenCalled(); + expect(find).toHaveBeenCalled(); + }); + await act(async () => { + for (let i = 0; i < 4; i++) await new Promise((r) => setTimeout(r, 0)); + }); +} + +describe('§1 nothing connected', () => { + it('shows the card, and its button opens Connect an AI Assistant', async () => { + renderHome(); + const card = await screen.findByTestId('home-connect-assistant'); + expect(card).toHaveTextContent('«home.connectAssistant.title»'); + expect(card).toHaveTextContent('«home.connectAssistant.body»'); + fireEvent.click(screen.getByTestId('home-connect-assistant-open')); + expect(await screen.findByTestId('connect-page')).toBeInTheDocument(); + }); + + it('reads only the signed-in person\'s keys', async () => { + renderHome(); + await screen.findByTestId('home-connect-assistant'); + expect(find).toHaveBeenCalledWith('sys_api_key', expect.objectContaining({ $filter: { user_id: 'user_me' } })); + }); +}); + +describe('§2 connected', () => { + it('an authorized assistant: no card', async () => { + granted = [ASSISTANT]; + renderHome(); + await settled(); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + }); + + it('a key that still works: no card', async () => { + keyRows = [{ ...LIVE_KEY }]; + renderHome(); + await settled(); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + }); +}); + +describe('§3 not known', () => { + it('while the read is out: no card', async () => { + list.mockReturnValue(new Promise(() => {})); + renderHome(); + await waitFor(() => expect(find).toHaveBeenCalled()); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + }); + + it('a failed read: no card', async () => { + list.mockRejectedValue(new Error('down')); + renderHome(); + await settled(); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + }); +}); + +describe('§4 hidden by the person', () => { + it('stays hidden for them on this browser, reading nothing, but not for another person', async () => { + renderHome(); + fireEvent.click(await screen.findByTestId('home-connect-assistant-dismiss')); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + expect(localStorage.getItem(connectAssistantCardKey('user_me'))).not.toBeNull(); + cleanup(); + + list.mockClear(); + find.mockClear(); + renderHome(); + await act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + expect(list).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + cleanup(); + + SHELL.user = { id: 'user_other' }; + renderHome(); + expect(await screen.findByTestId('home-connect-assistant')).toBeInTheDocument(); + }); +}); + +describe('§5 MCP turned off', () => { + it('the Account app carries no page: no card and no read', async () => { + SHELL.apps = [{ name: 'account', navigation: [] }]; + renderHome(); + await act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + expect(screen.queryByTestId('home-connect-assistant')).toBeNull(); + expect(list).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe('§6 connecting while it is shown', () => { + it('a key minted elsewhere on the page takes the card away', async () => { + renderHome(); + await screen.findByTestId('home-connect-assistant'); + keyRows = [{ ...LIVE_KEY }]; + act(() => notifyDataChanged({ objectName: 'sys_api_key' })); + await waitFor(() => expect(screen.queryByTestId('home-connect-assistant')).toBeNull()); + }); +}); From 68ff0b24d8f7246075ba39a7b6b46023b68ff439 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 7 Nov 2026 18:14:19 +0000 Subject: [PATCH 3/3] refactor(console): type the Connect path helper's served apps instead of any Co-Authored-By: Claude --- .../src/console/connect/connectAssistantPath.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts b/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts index 3967205f095..a8d85252d52 100644 --- a/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts +++ b/ui/packages/app-shell/src/console/connect/connectAssistantPath.ts @@ -23,15 +23,18 @@ export const CONNECT_ASSISTANT_PAGE = 'connect_agent'; */ export function navCarriesPage(items: unknown, pageName: string): boolean { if (!Array.isArray(items)) return false; - return items.some((item: any) => + return items.some((item: { type?: unknown; pageName?: unknown; children?: unknown } | null | undefined) => (item?.type === 'page' && item?.pageName === pageName) || navCarriesPage(item?.children, pageName)); } +type ServedApp = { name?: unknown; navigation?: unknown } & Record; + /** The Console path of Connect an AI Assistant, or `undefined` while the served Account app does not carry it. */ -export function connectAssistantPath(apps: readonly any[] | null | undefined): string | undefined { - const accountApp = (apps || []).find((a: any) => a?.name === 'account'); - return accountApp && navCarriesPage((accountApp as any).navigation, CONNECT_ASSISTANT_PAGE) - ? `/apps/${appAddressSegment(apps, accountApp)}/page/${CONNECT_ASSISTANT_PAGE}` +export function connectAssistantPath(apps: readonly T[] | null | undefined): string | undefined { + const served = (apps ?? []) as unknown as readonly ServedApp[]; + const accountApp = served.find((a) => a?.name === 'account'); + return accountApp && navCarriesPage(accountApp.navigation, CONNECT_ASSISTANT_PAGE) + ? `/apps/${appAddressSegment(served, accountApp)}/page/${CONNECT_ASSISTANT_PAGE}` : undefined; }