diff --git a/.changeset/34730-slack-settings-ui.md b/.changeset/34730-slack-settings-ui.md new file mode 100644 index 00000000000..adeefee5d66 --- /dev/null +++ b/.changeset/34730-slack-settings-ui.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +Clause-②: no +Metadata-protocol: none + +feat(app-shell): connect your Slack account on the notification settings page, and an admin Slack page in Setup + +The console side of Slack direct-message delivery (step 3 of the Slack DM work; the server doors shipped with `@objectstack/service-messaging`'s Slack link routes). + +- **Notification Settings: your Slack link.** Where the preference door lists the `slack` channel (only on a deployment that composes connector-slack), the page shows a Slack section. Without an install, or with an install whose token Slack refused, it says so and offers nothing. Otherwise **Connect Slack** asks `POST /api/v1/messaging/me/slack-link/proposal`; the page shows what the door answers: that a Slack user with your verified email was found (never whom), with **Confirm** (`…/confirm`) and **Cancel** (`DELETE /api/v1/messaging/me/slack-link`); or, when nothing was proposed, a sentence naming every reason the door does not tell apart (no verified email, no Slack user with it, or that Slack user linked to someone else). A confirmed link shows the Slack user and **Disconnect**. A refusal is shown in the server's own words (its `userMessage` when it carries one), and the section then reads the door again. +- **Setup's Slack page** (component `messaging:slack`, `/apps/setup/component/messaging/slack`): for an organization administrator holding `setup.write`, the capability the doors ask; anyone else sees what is needed and no door is read. It installs or sets again the organization's bot token (`PUT /api/v1/messaging/slack/account`) through a password input that always starts empty, removes the install after a confirm that says every linked person is told, and lists every link as served (person, Slack user once confirmed, when) with a confirmed **Remove** per link. When the list reaches the 10,000 links the server answers, the page says it may be incomplete. +- Every new sentence is in all eleven built-in locales (`slackLink`, `slackSetup`). diff --git a/content/docs/permissions/administrator-guide.mdx b/content/docs/permissions/administrator-guide.mdx index 1771532a502..4e1c0cf94f0 100644 --- a/content/docs/permissions/administrator-guide.mdx +++ b/content/docs/permissions/administrator-guide.mdx @@ -250,6 +250,32 @@ rules. A flow that should message the whole organization uses the `notify` step's `org:members` recipient instead ([Flows](/docs/automation/flows)). +## Deliver notifications by Slack direct message + +On a deployment that composes the Slack connector (`ConnectorSlackPlugin`), +notifications can also reach people as Slack direct messages, from your +organization's own Slack app. Without the connector none of this appears: +the notification settings page lists no Slack channel. + +1. **Install Slack (an administrator).** Open Setup's Slack page, + `/apps/setup/component/messaging/slack`; it needs `setup.write` in your + current organization, as the server does. Paste your Slack app's bot + token (it starts with `xoxb-`) and choose **Install**. Slack checks the + token before anything is saved; it is stored encrypted and never shown + again, so the field is always empty. **Save token** sets it again, for + instance after Slack refused it (the page then says **Token refused**). +2. **Connect (each person).** On **Notification Settings**, the Slack + section's **Connect Slack** asks for a proposal: a Slack user of your + workspace with the person's verified email, not linked to anyone else. + The proposal names no one until the person chooses **Confirm**; **Cancel** + drops it. Nothing reaches them on Slack before they confirm. + **Disconnect** removes the link. +3. **Manage links (an administrator).** The same Slack page lists every + link (the person, the Slack user once confirmed, and when) and removes + one; the person is told by in-app message and email and can connect again. + **Remove Slack** removes the install and every link, and tells each linked + person the same way. + ## Quick paths | I need to… | Do this | diff --git a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx index 488a5841fe4..e051a9fdd19 100644 --- a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.test.tsx @@ -30,6 +30,7 @@ import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from ' import { builtInLocales } from '@object-ui/i18n/locales'; import { NotificationSettingsPage } from './NotificationSettingsPage'; import { MY_PREFERENCES_URL } from './myPreferences'; +import { SLACK_LINK_URL } from './slackDoors'; import { getAppComponent } from '../../services/componentRegistry'; // The registry check below loads every built-in page, which reaches the // metadata admin's dynamic `@objectstack/lint` import: pay that load at @@ -66,10 +67,22 @@ function answer(taskEnabled: boolean, taskRow?: string, general: General = BUILT }; } -function host(apiFetch: ReturnType, adapter: { create: ReturnType; update: ReturnType }) { +const NO_SLACK_INSTALL = { data: { account: null, link: null } }; + +/** + * The Slack link door (`/me/slack-link`) answers through `slackFetch`, so + * `apiFetch` counts only the preference reads these tests are about. + */ +function host( + apiFetch: ReturnType, + adapter: { create: ReturnType; update: ReturnType }, + slackFetch: (url: string, init?: RequestInit) => Promise = async () => json(NO_SLACK_INSTALL), +) { + const prefsFetch = apiFetch as unknown as (url: string, init?: RequestInit) => Promise; + const routed = (url: string, init?: RequestInit) => (url.startsWith(SLACK_LINK_URL) ? slackFetch(url, init) : prefsFetch(url, init)); return ({ children }: { children: ReactNode }) => ( - + {children} @@ -366,3 +379,29 @@ describe('the caller\'s grant on sys_notification_preference decides whether the ); }); }); + +describe('the Slack section is drawn only where the preference door lists slack', () => { + const withoutSlack = () => { + const body = answer(false); + body.data.channels = body.data.channels.filter((c) => c.channel !== 'slack'); + body.data.topics = body.data.topics.map((t) => ({ ...t, channels: t.channels.filter((c) => c.channel !== 'slack') })); + return body; + }; + + it('with slack listed, the section reads the person’s link', async () => { + const slackFetch = vi.fn(async () => json(NO_SLACK_INSTALL)); + render(, { wrapper: host(vi.fn(async () => json(answer(false))), { create: vi.fn(), update: vi.fn() }, slackFetch) }); + + expect(await screen.findByTestId('slack-link-section')).toBeInTheDocument(); + await waitFor(() => expect(slackFetch).toHaveBeenCalledWith(SLACK_LINK_URL, expect.objectContaining({ method: 'GET' }))); + }); + + it('without slack listed, no section and no Slack door is called', async () => { + const slackFetch = vi.fn(async () => json(NO_SLACK_INSTALL)); + render(, { wrapper: host(vi.fn(async () => json(withoutSlack())), { create: vi.fn(), update: vi.fn() }, slackFetch) }); + + await screen.findByTestId('notification-settings-matrix'); + expect(screen.queryByTestId('slack-link-section')).toBeNull(); + expect(slackFetch).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx index e7f9c1e8b05..3cd1154f056 100644 --- a/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx +++ b/ui/packages/app-shell/src/console/notification-settings/NotificationSettingsPage.tsx @@ -21,7 +21,9 @@ * * Channels are columns as the door lists them, so a channel the deployment * adds later (Slack, …) appears without a change here; a channel the - * deployment cannot send on yet says so in its header. + * deployment cannot send on yet says so in its header. Where the door lists + * `slack` (connector-slack is composed), the page also draws the person's own + * Slack link (`SlackLinkSection`): Slack delivers only to a confirmed link. * * A caller who holds neither a create nor an edit grant on * `sys_notification_preference` (an external member: `external_default` @@ -75,6 +77,7 @@ import { type PreferenceWrite, type QuietHoursWindow, } from './myPreferences.js'; +import { SlackLinkSection } from './SlackLinkSection.js'; type Load = { readonly state: 'loading' } | { readonly state: 'failed' } | { readonly state: 'read'; readonly prefs: MyPreferences }; @@ -94,6 +97,9 @@ const SOURCE_KEY: Record = { mandatory: 'notificationSettings.sourceMandatory', }; +/** The channel the Slack section belongs to, as the preference door lists it. */ +const SLACK_CHANNEL = 'slack'; + function errorText(err: unknown): string { return err instanceof Error && err.message ? err.message : String(err); } @@ -336,6 +342,8 @@ export function NotificationSettingsPage() { + + {apiFetch && prefs.channels.some((c) => c.channel === SLACK_CHANNEL) && } ); diff --git a/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.test.tsx b/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.test.tsx new file mode 100644 index 00000000000..e46877274e4 --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.test.tsx @@ -0,0 +1,191 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The person's Slack section (#34730 step 3): connect → proposal → confirm → + * linked, cancel, disconnect, and each answer of the Slack link doors drawn as + * the door gave it. The doors are faked by URL and method with the envelopes + * `slack-link-routes.ts` writes; `t` echoes the KEY. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, language: 'en' }), +})); + +import { SlackLinkSection } from './SlackLinkSection'; +import { SLACK_LINK_URL } from './slackDoors'; + +const ACME = { id: 'acc1', workspace: 'Acme', workspaceId: 'T1', status: 'active' }; +const LINKED = { id: 'l1', userId: 'alice', slackUserId: 'UADA', slackUserName: 'Ada', state: 'confirmed', confirmedAt: '2026-11-20T10:00:00.000Z' }; +const ok = (data: unknown) => new Response(JSON.stringify({ success: true, data }), { status: 200 }); +const refused = (status: number, code: string, message: string, userMessage?: string) => + new Response(JSON.stringify({ success: false, error: { code, message, ...(userMessage ? { userMessage } : {}) } }), { status }); + +type Route = (state: { account: unknown; link: unknown }) => Response; + +/** A fake of the four person doors over one stored state; `routes` overrides a door by `METHOD path`. */ +function doors(initial: { account: unknown; link: unknown }, routes: Record = {}) { + const state = { ...initial }; + const fetch = vi.fn(async (url: string, init?: RequestInit) => { + const key = `${init?.method ?? 'GET'} ${url}`; + if (routes[key]) return routes[key](state); + switch (key) { + case `GET ${SLACK_LINK_URL}`: + return ok(state); + case `POST ${SLACK_LINK_URL}/proposal`: + state.link = { state: 'proposed' }; + return ok({ link: state.link }); + case `POST ${SLACK_LINK_URL}/confirm`: + state.link = LINKED; + return ok({ link: LINKED }); + case `DELETE ${SLACK_LINK_URL}`: { + const removed = state.link !== null; + state.link = null; + return ok({ removed }); + } + } + return refused(404, 'NOT_FOUND', key); + }); + return { fetch, state }; +} + +const calls = (f: ReturnType) => f.mock.calls.map(([url, init]) => `${(init as RequestInit | undefined)?.method ?? 'GET'} ${url}`); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('SlackLinkSection', () => { + it('connect → the proposal names no one → confirm → linked', async () => { + const { fetch } = doors({ account: ACME, link: null }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-connect')); + const proposal = await screen.findByTestId('slack-link-proposal'); + expect(proposal).toHaveTextContent('«slackLink.proposed»'); + expect(proposal).not.toHaveTextContent('Ada'); + + fireEvent.click(screen.getByTestId('slack-link-confirm')); + expect(await screen.findByTestId('slack-link-linked')).toHaveTextContent('«slackLink.linked»'); + expect(calls(fetch)).toEqual([ + `GET ${SLACK_LINK_URL}`, + `POST ${SLACK_LINK_URL}/proposal`, + `GET ${SLACK_LINK_URL}`, + `POST ${SLACK_LINK_URL}/confirm`, + `GET ${SLACK_LINK_URL}`, + ]); + }); + + it('cancel removes the proposal', async () => { + const { fetch, state } = doors({ account: ACME, link: { state: 'proposed' } }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-cancel')); + expect(await screen.findByTestId('slack-link-connect')).toBeInTheDocument(); + expect(state.link).toBeNull(); + expect(calls(fetch)).toContain(`DELETE ${SLACK_LINK_URL}`); + }); + + it('disconnect removes the link', async () => { + const { fetch, state } = doors({ account: ACME, link: LINKED }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-disconnect')); + expect(await screen.findByTestId('slack-link-connect')).toBeInTheDocument(); + expect(state.link).toBeNull(); + }); + + it('no install: says so and offers nothing', async () => { + const { fetch } = doors({ account: null, link: null }); + render(); + + expect(await screen.findByTestId('slack-link-not-installed')).toHaveTextContent('«slackLink.notInstalled»'); + expect(screen.queryByTestId('slack-link-connect')).toBeNull(); + }); + + it('a revoked token: says so and offers no connect', async () => { + const { fetch } = doors({ account: { ...ACME, status: 'revoked' }, link: null }); + render(); + + expect(await screen.findByTestId('slack-link-revoked')).toHaveTextContent('«slackLink.revoked»'); + expect(screen.queryByTestId('slack-link-connect')).toBeNull(); + }); + + it('a proposal answering link: null (no verified email, or no Slack user for it) names every cause, never one', async () => { + const { fetch } = doors({ account: ACME, link: null }, { [`POST ${SLACK_LINK_URL}/proposal`]: () => ok({ link: null }) }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-connect')); + expect(await screen.findByTestId('slack-link-no-match')).toHaveTextContent('«slackLink.noMatch»'); + expect(screen.getByTestId('slack-link-connect')).toBeInTheDocument(); + }); + + it('a stale proposal: the server’s own sentence (its userMessage), and a new proposal can be asked for', async () => { + const stale = 'Your email is no longer verified, or is not the email this Slack link was proposed for: ask for a new proposal. Nothing was changed.'; + const { fetch } = doors({ account: ACME, link: { state: 'proposed' } }, { + [`POST ${SLACK_LINK_URL}/confirm`]: () => refused(409, 'RESOURCE_CONFLICT', 'english', stale), + }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-confirm')); + expect(await screen.findByTestId('slack-link-refused')).toHaveTextContent(stale); + fireEvent.click(await screen.findByTestId('slack-link-propose-again')); + await waitFor(() => expect(calls(fetch)).toContain(`POST ${SLACK_LINK_URL}/proposal`)); + }); + + it('a replaced or removed proposal: the server’s 404 sentence, and the section reads the door again', async () => { + const gone = 'You have no proposed Slack link in this organization to confirm: ask for a proposal first. Nothing was changed.'; + const { fetch } = doors({ account: ACME, link: { state: 'proposed' } }, { + [`POST ${SLACK_LINK_URL}/confirm`]: (s) => { + s.link = null; + return refused(404, 'RESOURCE_NOT_FOUND', gone); + }, + }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-confirm')); + expect(await screen.findByTestId('slack-link-refused')).toHaveTextContent(gone); + expect(await screen.findByTestId('slack-link-connect')).toBeInTheDocument(); + }); + + it('Slack refusing the token mid-proposal: the server’s 502 sentence, then the revoked install as re-read', async () => { + const { fetch } = doors({ account: ACME, link: null }, { + [`POST ${SLACK_LINK_URL}/proposal`]: (s) => { + s.account = { ...ACME, status: 'revoked' }; + return refused(502, 'EXTERNAL_SERVICE_ERROR', 'Slack answered token_revoked. Nothing was changed.'); + }, + }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-connect')); + expect(await screen.findByTestId('slack-link-refused')).toHaveTextContent('Slack answered token_revoked. Nothing was changed.'); + expect(await screen.findByTestId('slack-link-revoked')).toBeInTheDocument(); + }); + + it('no install when the person clicks: the server’s 409 sentence', async () => { + const message = 'Slack is not installed for this organization: an administrator installs it first. Nothing was changed.'; + const { fetch } = doors({ account: ACME, link: null }, { + [`POST ${SLACK_LINK_URL}/proposal`]: (s) => { + s.account = null; + return refused(409, 'RESOURCE_CONFLICT', message); + }, + }); + render(); + + fireEvent.click(await screen.findByTestId('slack-link-connect')); + expect(await screen.findByTestId('slack-link-refused')).toHaveTextContent(message); + expect(await screen.findByTestId('slack-link-not-installed')).toBeInTheDocument(); + }); + + it('a failed read says so', async () => { + const { fetch } = doors({ account: null, link: null }, { [`GET ${SLACK_LINK_URL}`]: () => refused(503, 'SERVICE_UNAVAILABLE', 'no data engine') }); + render(); + + expect(await screen.findByTestId('slack-link-load-failed')).toHaveTextContent('«slackLink.loadFailed»'); + }); +}); diff --git a/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.tsx b/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.tsx new file mode 100644 index 00000000000..694ac57e9bf --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/SlackLinkSection.tsx @@ -0,0 +1,163 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Notification Settings page's Slack section: the signed-in person + * connects or disconnects their own Slack user, in their current organization, + * through the Slack link doors (`slackDoors.ts`). + * + * The page draws it only while the preference door lists `slack` as a + * channel, which it does only where connector-slack is composed. It shows the + * state the door answers and nothing else: + * + * - no install, or an install whose token Slack refused: says so, offers nothing; + * - no link: "Connect Slack", which asks for a proposal; + * - a proposal: what the door answers of it (that a match was found, never + * whom), with Confirm and Cancel; + * - a confirmed link: the Slack user it names, with Disconnect. + * + * After every action, refused or not, it reads the door again, so what it + * draws is what is stored. A refusal is shown in the server's own words. + */ + +import { useCallback, useEffect, useState } from 'react'; +import { Alert, AlertDescription, Button, Card, CardContent } from '@object-ui/components'; +import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; +import { + confirmSlackLink, + proposeSlackLink, + readOwnSlackLink, + removeOwnSlackLink, + type OwnSlackLink, + type SlackAccount, + type SlackAnswer, +} from './slackDoors.js'; + +type Fetch = (input: string, init?: RequestInit) => Promise; + +type Read = + | { readonly state: 'loading' } + | { readonly state: 'failed'; readonly message: string } + | { readonly state: 'read'; readonly account: SlackAccount | null; readonly link: OwnSlackLink | null }; + +const toRead = (out: Awaited>): Read => + out.ok ? { state: 'read', ...out.data } : { state: 'failed', message: out.refusal.message }; + +export function SlackLinkSection({ apiFetch }: { apiFetch: Fetch }) { + const { t } = useObjectTranslation(); + const displayLocale = useDisplayLocale(); + const [read, setRead] = useState({ state: 'loading' }); + const [busy, setBusy] = useState(false); + const [refusal, setRefusal] = useState(null); + const [noMatch, setNoMatch] = useState(false); + + const reread = useCallback(async () => setRead(toRead(await readOwnSlackLink(apiFetch))), [apiFetch]); + + useEffect(() => { + let cancelled = false; + void readOwnSlackLink(apiFetch).then((out) => { + if (!cancelled) setRead(toRead(out)); + }); + return () => { + cancelled = true; + }; + }, [apiFetch]); + + /** Run one door call, show its refusal if any, then read the door again. */ + const act = async (call: () => Promise>, after?: (data: T) => void) => { + setBusy(true); + setRefusal(null); + setNoMatch(false); + const out = await call(); + if (out.ok) after?.(out.data); + else setRefusal(out.refusal.message); + await reread(); + setBusy(false); + }; + + const formatAt = (at: string | null) => { + if (!at) return null; + const d = new Date(at); + return Number.isNaN(d.getTime()) ? at : d.toLocaleString(displayLocale); + }; + + let body; + if (read.state === 'loading') { + body =

{t('slackLink.loading')}

; + } else if (read.state === 'failed') { + body = ( + + {t('slackLink.loadFailed', { reason: read.message })} + + ); + } else if (!read.account) { + body =

{t('slackLink.notInstalled')}

; + } else { + const { account, link } = read; + const workspace = account.workspace; + body = ( +
+ {account.status === 'revoked' && ( + + {t('slackLink.revoked', { workspace })} + + )} + {link?.state === 'confirmed' ? ( +
+
+

{t('slackLink.linked', { workspace, slackUser: link.slackUserName ?? link.slackUserId ?? '' })}

+ {link.confirmedAt && ( +

{t('slackLink.linkedAt', { at: formatAt(link.confirmedAt) })}

+ )} +
+ +
+ ) : link?.state === 'proposed' ? ( +
+

{t('slackLink.proposed', { workspace })}

+
+ + + {refusal !== null && ( + + )} +
+
+ ) : account.status === 'active' ? ( +
+

{t('slackLink.notLinked', { workspace })}

+ +
+ ) : null} + {noMatch &&

{t('slackLink.noMatch', { workspace })}

} +
+ ); + } + + return ( + + +

{t('slackLink.title')}

+ {refusal !== null && ( + + {refusal} + + )} + {body} +
+
+ ); +} diff --git a/ui/packages/app-shell/src/console/notification-settings/slackDoors.ts b/ui/packages/app-shell/src/console/notification-settings/slackDoors.ts new file mode 100644 index 00000000000..e74ec455c6f --- /dev/null +++ b/ui/packages/app-shell/src/console/notification-settings/slackDoors.ts @@ -0,0 +1,188 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Slack link doors of the messaging service (`slack-link-routes.ts` in + * `@objectstack/service-messaging`, ADR-0013 addendum of 2026-11-19), as the + * console calls them: the person's own link on the Notification Settings page + * (`SlackLinkSection`), and an organization administrator's install and links + * on Setup's Slack page (`SlackSetupPage`). Every call goes through the host's + * authenticated fetch, as the page's own preference read does. + * + * What the doors answer is read as served and nothing is added to it: + * + * - ⛔ no answer carries the token, so none is ever shown; + * - a proposal names no Slack user before it is confirmed: the person's own + * view of it is `{ state: 'proposed' }`, and an administrator's list shows + * it with `slackUserId` and `slackUserName` null; + * - a proposal answers `link: null` when the person has no verified email, + * when no Slack user of the workspace holds it, and when that Slack user is + * linked to someone else in the install. The door does not say which, so + * the page names all three and never picks one. + * + * A refusal is the server's own sentence: its `userMessage` (already in the + * caller's language) when it carries one, else its `message`. + */ + +/** The person's own link, in their current organization. */ +export const SLACK_LINK_URL = '/api/v1/messaging/me/slack-link'; +/** The organization's install: read, set the token, remove. */ +export const SLACK_ACCOUNT_URL = '/api/v1/messaging/slack/account'; +/** Every link to the organization's install. */ +export const SLACK_LINKS_URL = '/api/v1/messaging/slack/links'; +/** The capability every administrator door asks in the caller's current organization (`SLACK_ADMIN_CAPABILITY`). */ +export const SLACK_ADMIN_CAPABILITY = 'setup.write'; +/** + * The most links `GET /slack/links` answers: the store reads them unpaged + * with `limit: 10000`. A list this long may be incomplete; the page says so + * and never pages on its own. + */ +export const SLACK_LINKS_SERVED_CAP = 10000; + +export interface SlackAccount { + id: string; + workspace: string; + workspaceId: string; + status: 'active' | 'revoked'; +} + +export interface SlackLink { + id: string; + userId: string; + slackUserId: string | null; + slackUserName: string | null; + state: 'proposed' | 'confirmed'; + confirmedAt: string | null; +} + +/** The person's own link: a proposal names no one; a confirmed link is the full view. */ +export type OwnSlackLink = { state: 'proposed' } | (SlackLink & { state: 'confirmed' }); + +export interface SlackRefusal { + status: number; + code: string; + message: string; +} + +export type SlackAnswer = { ok: true; data: T } | { ok: false; refusal: SlackRefusal }; + +type Fetch = (input: string, init?: RequestInit) => Promise; + +const isObject = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const text = (v: unknown): string | undefined => (typeof v === 'string' && v !== '' ? v : undefined); +const textOrNull = (v: unknown): string | null | undefined => (v === null ? null : typeof v === 'string' ? v : undefined); + +function readAccount(raw: unknown): SlackAccount | null | undefined { + if (raw === null) return null; + if (!isObject(raw) || !text(raw.id) || typeof raw.workspace !== 'string' || typeof raw.workspaceId !== 'string') return undefined; + if (raw.status !== 'active' && raw.status !== 'revoked') return undefined; + return { id: raw.id as string, workspace: raw.workspace, workspaceId: raw.workspaceId, status: raw.status }; +} + +function readLink(raw: unknown): SlackLink | undefined { + if (!isObject(raw) || !text(raw.id) || !text(raw.userId)) return undefined; + if (raw.state !== 'proposed' && raw.state !== 'confirmed') return undefined; + const slackUserId = textOrNull(raw.slackUserId); + const slackUserName = textOrNull(raw.slackUserName); + const confirmedAt = textOrNull(raw.confirmedAt); + if (slackUserId === undefined || slackUserName === undefined || confirmedAt === undefined) return undefined; + return { id: raw.id as string, userId: raw.userId as string, slackUserId, slackUserName, state: raw.state, confirmedAt }; +} + +function readOwnLink(raw: unknown): OwnSlackLink | null | undefined { + if (raw === null) return null; + if (isObject(raw) && raw.state === 'proposed') return { state: 'proposed' }; + const link = readLink(raw); + return link?.state === 'confirmed' ? { ...link, state: 'confirmed' } : undefined; +} + +const readRemoved = (data: Record) => (typeof data.removed === 'boolean' ? data.removed : undefined); + +/** One door call: the success envelope's `data` read by `read`, or the refusal in the server's own words. */ +async function door( + doFetch: Fetch, + method: string, + url: string, + read: (data: Record) => T | undefined, + body?: Record, +): Promise> { + let res: Response; + try { + res = await doFetch(url, { + method, + credentials: 'include', + headers: body ? { accept: 'application/json', 'content-type': 'application/json' } : { accept: 'application/json' }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + } catch (err) { + return { ok: false, refusal: { status: 0, code: '', message: err instanceof Error && err.message ? err.message : String(err) } }; + } + const payload: unknown = await res.json().catch(() => null); + const envelope = isObject(payload) ? payload : {}; + if (res.ok && envelope.success !== false && isObject(envelope.data)) { + const data = read(envelope.data); + if (data !== undefined) return { ok: true, data }; + return { ok: false, refusal: { status: res.status, code: '', message: `${method} ${url} answered no readable answer.` } }; + } + const error = isObject(envelope.error) ? envelope.error : {}; + return { + ok: false, + refusal: { + status: res.status, + code: text(error.code) ?? '', + message: text(error.userMessage) ?? text(error.message) ?? `${method} ${url} answered ${res.status}.`, + }, + }; +} + +/** `GET /me/slack-link`: the install (its workspace) and the person's link, each `null` when there is none. */ +export function readOwnSlackLink(f: Fetch): Promise> { + return door(f, 'GET', SLACK_LINK_URL, (d) => { + const account = readAccount(d.account); + const link = readOwnLink(d.link); + return account === undefined || link === undefined ? undefined : { account, link }; + }); +} + +/** `POST /me/slack-link/proposal`: `null` when nothing was proposed. */ +export function proposeSlackLink(f: Fetch): Promise> { + return door(f, 'POST', `${SLACK_LINK_URL}/proposal`, (d) => readOwnLink(d.link)); +} + +/** `POST /me/slack-link/confirm`: the confirmed link. */ +export function confirmSlackLink(f: Fetch): Promise> { + return door(f, 'POST', `${SLACK_LINK_URL}/confirm`, (d) => readOwnLink(d.link) ?? undefined); +} + +/** `DELETE /me/slack-link`: the person's link or proposal goes. */ +export function removeOwnSlackLink(f: Fetch): Promise> { + return door(f, 'DELETE', SLACK_LINK_URL, readRemoved); +} + +/** `GET /slack/account`: the install without its token, `null` when there is none. */ +export function readSlackAccount(f: Fetch): Promise> { + return door(f, 'GET', SLACK_ACCOUNT_URL, (d) => readAccount(d.account)); +} + +/** `PUT /slack/account` `{ token }`: install, or set the token again. */ +export function installSlack(f: Fetch, token: string): Promise> { + return door(f, 'PUT', SLACK_ACCOUNT_URL, (d) => readAccount(d.account) ?? undefined, { token }); +} + +/** `DELETE /slack/account`: the install and every link to it go; each linked person is told. */ +export function uninstallSlack(f: Fetch): Promise> { + return door(f, 'DELETE', SLACK_ACCOUNT_URL, readRemoved); +} + +/** `GET /slack/links`: every link to the install, as served. */ +export function listSlackLinks(f: Fetch): Promise> { + return door(f, 'GET', SLACK_LINKS_URL, (d) => { + if (!Array.isArray(d.links)) return undefined; + const links = d.links.map(readLink); + return links.every((l): l is SlackLink => l !== undefined) ? links : undefined; + }); +} + +/** `DELETE /slack/links/:id`: one link goes; the person is told. */ +export function removeSlackLink(f: Fetch, id: string): Promise> { + return door(f, 'DELETE', `${SLACK_LINKS_URL}/${encodeURIComponent(id)}`, readRemoved); +} diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index 4f6ab0b43a7..898e84ebe15 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -136,6 +136,9 @@ const PermissionSetAssignmentPage = lazyPage('permission set assignments', () => const RecycleBinPage = lazyPage('recycle bin', () => import('../views/setup/RecycleBinPage.js').then((m) => m.RecycleBinPage), ); +const SlackSetupPage = lazyPage('slack', () => + import('../views/setup/SlackSetupPage.js').then((m) => m.SlackSetupPage), +); /** * The position list's two served cells (objectstack#33582): by value they held * `metadata-admin/i18n.ts`, and with it the Studio `en` string namespace, in the @@ -275,6 +278,18 @@ registerAppComponent({ component: RecycleBinPage, }); +/** + * Setup's Slack page (ADR-0013 addendum, step 3 of objectstack#34730): an + * organization administrator installs the organization's Slack app and manages + * people's Slack links. Its doors ask `setup.write`, and so does the page. + */ +registerAppComponent({ + ref: 'messaging:slack', + label: 'Slack', + source: '@object-ui/app-shell', + component: SlackSetupPage, +}); + /* -------------------------------------------------------------------------- */ /* 2) Generic resources — list + JSONSchema-driven form for every type. */ /* -------------------------------------------------------------------------- */ diff --git a/ui/packages/app-shell/src/views/setup/SlackSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/SlackSetupPage.test.tsx new file mode 100644 index 00000000000..bc6294c489c --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/SlackSetupPage.test.tsx @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup's Slack page (#34730 step 3): gated by `setup.write` as its doors + * are; install, set the token again and remove the install, with a confirm + * that says linked people are told; list links as served and remove one with + * a confirm; the token input never pre-fills; at the served cap the list says + * it may be incomplete. The doors are faked with the envelopes + * `slack-link-routes.ts` writes; `t` echoes the KEY. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, language: 'en' }), +})); + +// The served cap is the store's unpaged read (10,000); two keeps the cap test small. +vi.mock('../../console/notification-settings/slackDoors', async (importOriginal) => ({ + ...(await importOriginal>()), + SLACK_LINKS_SERVED_CAP: 2, +})); + +import { SchemaRendererProvider } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { builtInLocales } from '@object-ui/i18n/locales'; +import { SlackSetupPage } from './SlackSetupPage'; +import { SLACK_ACCOUNT_URL, SLACK_LINKS_URL } from '../../console/notification-settings/slackDoors'; +import { getAppComponent } from '../../services/componentRegistry'; +// The registry check loads every built-in page; pay the metadata admin's lint load at collection. +import '@objectstack/lint'; +import '../../services/builtinComponents'; + +const ACME = { id: 'acc1', workspace: 'Acme', workspaceId: 'T1', status: 'active' }; +const ADA = { id: 'l1', userId: 'u_ada', slackUserId: 'UADA', slackUserName: 'Ada', state: 'confirmed', confirmedAt: '2026-11-20T10:00:00.000Z' }; +const BOB = { id: 'l2', userId: 'u_bob', slackUserId: null, slackUserName: null, state: 'proposed', confirmedAt: null }; +const ok = (data: unknown) => new Response(JSON.stringify({ success: true, data }), { status: 200 }); +const refused = (status: number, code: string, message: string) => + new Response(JSON.stringify({ success: false, error: { code, message } }), { status }); + +/** A fake of the five administrator doors over one stored state. */ +function doors(initial: { account: unknown; links: unknown[] }, put?: (body: { token: string }) => Response) { + const state = { ...initial }; + const fetch = vi.fn(async (url: string, init?: RequestInit) => { + const method = init?.method ?? 'GET'; + if (url === SLACK_ACCOUNT_URL && method === 'GET') return ok({ account: state.account }); + if (url === SLACK_ACCOUNT_URL && method === 'PUT') { + const body = JSON.parse(String(init?.body)) as { token: string }; + if (put) return put(body); + state.account = ACME; + return ok({ account: ACME }); + } + if (url === SLACK_ACCOUNT_URL && method === 'DELETE') { + state.account = null; + state.links = []; + return ok({ removed: true }); + } + if (url === SLACK_LINKS_URL && method === 'GET') return ok({ links: state.links }); + if (url.startsWith(`${SLACK_LINKS_URL}/`) && method === 'DELETE') { + const id = decodeURIComponent(url.slice(SLACK_LINKS_URL.length + 1)); + state.links = state.links.filter((l) => (l as { id: string }).id !== id); + return ok({ removed: true }); + } + return refused(404, 'NOT_FOUND', `${method} ${url}`); + }); + return { fetch, state }; +} + +function served(systemPermissions: string[]): MePermissionsAuthenticatedResponse { + return { + authenticated: true, + userId: 'admin', + tenantId: 'org1', + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: [], + objects: {}, + fields: {}, + systemPermissions, + } as MePermissionsAuthenticatedResponse; +} + +function host(fetch: ReturnType, systemPermissions: string[] = ['setup.access', 'setup.write']) { + return ({ children }: { children: ReactNode }) => ( + + + {children} + + + ); +} + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('SlackSetupPage', () => { + it('without setup.write: says what is needed and reads no door', async () => { + const { fetch } = doors({ account: ACME, links: [ADA] }); + render(, { wrapper: host(fetch, ['setup.access']) }); + + expect(await screen.findByTestId('slack-setup-not-allowed')).toHaveTextContent('«slackSetup.notAllowed»'); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('install: the token goes to PUT { token }, the input is emptied, and the install is drawn', async () => { + const { fetch } = doors({ account: null, links: [] }); + render(, { wrapper: host(fetch) }); + + expect(await screen.findByTestId('slack-setup-not-installed')).toBeInTheDocument(); + const input = screen.getByTestId('slack-setup-token') as HTMLInputElement; + expect(input).toHaveValue(''); + expect(input).toHaveAttribute('type', 'password'); + fireEvent.change(input, { target: { value: 'xoxb-1' } }); + fireEvent.click(screen.getByTestId('slack-setup-save')); + + expect(await screen.findByTestId('slack-setup-account')).toHaveTextContent('«slackSetup.workspace»'); + expect(fetch).toHaveBeenCalledWith(SLACK_ACCOUNT_URL, expect.objectContaining({ method: 'PUT', body: JSON.stringify({ token: 'xoxb-1' }) })); + expect(screen.getByTestId('slack-setup-token')).toHaveValue(''); + expect(screen.getByTestId('slack-setup-notice')).toHaveTextContent('«slackSetup.installed»'); + }); + + it('update: an installed token is never pre-filled; a refused token shows the server’s sentence', async () => { + const message = 'This token belongs to another Slack workspace than the one installed (Acme). Remove the install first, which removes every link to it. Nothing was saved.'; + const { fetch } = doors({ account: ACME, links: [] }, () => refused(409, 'RESOURCE_CONFLICT', message)); + render(, { wrapper: host(fetch) }); + + await screen.findByTestId('slack-setup-account'); + expect(screen.getByTestId('slack-setup-token')).toHaveValue(''); + fireEvent.change(screen.getByTestId('slack-setup-token'), { target: { value: 'xoxb-other' } }); + fireEvent.click(screen.getByTestId('slack-setup-save')); + + expect(await screen.findByTestId('slack-setup-refused')).toHaveTextContent(message); + expect(screen.getByTestId('slack-setup-token')).toHaveValue(''); + }); + + it('remove the install: a confirm that says linked people are told, then DELETE', async () => { + const { fetch, state } = doors({ account: ACME, links: [ADA] }); + render(, { wrapper: host(fetch) }); + + fireEvent.click(await screen.findByTestId('slack-setup-uninstall')); + expect(await screen.findByTestId('slack-setup-confirm')).toHaveTextContent('«slackSetup.uninstallBody»'); + expect(fetch).not.toHaveBeenCalledWith(SLACK_ACCOUNT_URL, expect.objectContaining({ method: 'DELETE' })); + fireEvent.click(screen.getByTestId('slack-setup-confirm-remove')); + + expect(await screen.findByTestId('slack-setup-not-installed')).toBeInTheDocument(); + expect(state.account).toBeNull(); + }); + + it('lists links as served — a proposal names no Slack user — and removes one after a confirm', async () => { + const { fetch, state } = doors({ account: ACME, links: [ADA, BOB] }); + render(, { wrapper: host(fetch) }); + + const ada = await screen.findByTestId('slack-setup-link-l1'); + expect(ada).toHaveTextContent('u_ada'); + expect(ada).toHaveTextContent('Ada · UADA'); + expect(screen.getByTestId('slack-setup-link-l2')).toHaveTextContent('«slackSetup.proposedLink»'); + + fireEvent.click(screen.getByTestId('slack-setup-remove-l2')); + expect(await screen.findByTestId('slack-setup-confirm')).toHaveTextContent('«slackSetup.removeBody»'); + fireEvent.click(screen.getByTestId('slack-setup-confirm-remove')); + + await waitFor(() => expect(screen.queryByTestId('slack-setup-link-l2')).toBeNull()); + expect(fetch).toHaveBeenCalledWith(`${SLACK_LINKS_URL}/l2`, expect.objectContaining({ method: 'DELETE' })); + expect(state.links).toEqual([ADA]); + }); + + it('at the served cap the list says it may be incomplete, and never pages', async () => { + const { fetch } = doors({ account: ACME, links: [ADA, BOB] }); + render(, { wrapper: host(fetch) }); + + expect(await screen.findByTestId('slack-setup-links-capped')).toHaveTextContent('«slackSetup.linksCapped»'); + expect(fetch.mock.calls.filter(([url]) => String(url).startsWith(SLACK_LINKS_URL))).toHaveLength(1); + }); + + it('the served cap is the store’s unpaged read', async () => { + const actual = await vi.importActual<{ SLACK_LINKS_SERVED_CAP: number }>('../../console/notification-settings/slackDoors'); + expect(actual.SLACK_LINKS_SERVED_CAP).toBe(10000); + }); + + it('below the cap no such text', async () => { + const { fetch } = doors({ account: ACME, links: [ADA] }); + render(, { wrapper: host(fetch) }); + + await screen.findByTestId('slack-setup-link-l1'); + expect(screen.queryByTestId('slack-setup-links-capped')).toBeNull(); + }); +}); + +describe('Setup names the page', () => { + it('messaging:slack resolves to this page', () => { + expect(getAppComponent('messaging:slack')).toBeTruthy(); + }); + + it('every built-in locale carries the same Slack keys and placeholders', () => { + type Pack = Record | undefined>; + const packs = builtInLocales as unknown as Record; + const placeholders = (s: string) => (s.match(/\{\{\w+\}\}/g) ?? []).sort(); + for (const section of ['slackLink', 'slackSetup']) { + const en = packs.en[section]!; + for (const [locale, pack] of Object.entries(packs)) { + expect(Object.keys(pack[section] ?? {}).sort(), `${locale}.${section}`).toEqual(Object.keys(en).sort()); + for (const key of Object.keys(en)) { + expect(placeholders(pack[section]![key]), `${locale}.${section}.${key}`).toEqual(placeholders(en[key])); + } + } + } + }); +}); diff --git a/ui/packages/app-shell/src/views/setup/SlackSetupPage.tsx b/ui/packages/app-shell/src/views/setup/SlackSetupPage.tsx new file mode 100644 index 00000000000..a34a5a8194c --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/SlackSetupPage.tsx @@ -0,0 +1,297 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup's Slack page: an organization administrator installs the + * organization's own Slack app (its bot token), sets the token again, or + * removes the install, and lists and removes people's Slack links — through + * the administrator doors of the Slack link routes (`slackDoors.ts`). + * + * Gated by the capability those doors ask, `setup.write` in the caller's + * current organization (`hasCapabilities`, which fails open on an unreported + * answer: the doors still refuse). Without it the page reads nothing. + * + * ⛔ It never shows a token: no door answers one, and the token input starts + * empty whatever is installed. A link is listed as served: its person's id, + * the Slack user only once confirmed, and when it was confirmed. The list is + * read unpaged; at the door's cap the page says it may be incomplete. + */ + +import { useCallback, useContext, useEffect, useState, type FormEvent } from 'react'; +import { MessageSquare } from 'lucide-react'; +import { + Alert, + AlertDescription, + Badge, + Button, + Card, + CardContent, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + Input, + Label, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@object-ui/components'; +import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; +import { usePermissions } from '@object-ui/permissions'; +import { SchemaRendererContext } from '@object-ui/react'; +import { PageHeader } from '../../layout/PageHeader.js'; +import { + installSlack, + listSlackLinks, + readSlackAccount, + removeSlackLink, + SLACK_ADMIN_CAPABILITY, + SLACK_LINKS_SERVED_CAP, + uninstallSlack, + type SlackAccount, + type SlackAnswer, + type SlackLink, +} from '../../console/notification-settings/slackDoors.js'; + +type Fetch = (input: string, init?: RequestInit) => Promise; +type Loaded = { state: 'loading' } | { state: 'failed'; message: string } | { state: 'read'; value: T }; +/** What the confirm dialog removes: the whole install, or one link. */ +type Removal = { kind: 'install' } | { kind: 'link'; link: SlackLink }; + +const loaded = (out: SlackAnswer): Loaded => + out.ok ? { state: 'read', value: out.data } : { state: 'failed', message: out.refusal.message }; + +export function SlackSetupPage() { + const { t } = useObjectTranslation(); + const { hasCapabilities } = usePermissions(); + const apiFetch = useContext(SchemaRendererContext)?.apiFetch as Fetch | undefined; + const allowed = hasCapabilities([SLACK_ADMIN_CAPABILITY]); + + const header = ( +