From 4d66a6dca606313e1b9cbcb51bdfcce30a4f9b70 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:26:57 +0000 Subject: [PATCH 1/9] fix(ui): return focus to the menu button after a menu item's dialog A dialog opened from a row's actions menu dropped keyboard focus to when it closed (#3715): on Settings > Connectors and AI providers (Edit credential, Replace, Delete), Members (Edit, Transfer ownership, Remove), Teams, API keys and Projects, and on the rows whose menus were only half wired, such as the Documents row's Delete, Move and Team tags. The menu item that opened the dialog is gone by then, and useRestoreFocus only knew a return point the caller passed as restoreFocusRef, which ten row menus never did. The menu names its own button. Radix's DropdownMenu, like any WAI-ARIA menu button, labels its menu by the button (aria-labelledby) and the button declares the popup (aria-haspopup). useRestoreFocus now reads that button when the dialog opens, while the menu still stands, and returns focus there on close when the opener was a menu item. A caller's restoreFocusRef still wins. A label that opens nothing (a listbox's heading) is never taken, a submenu climbs to the outermost button, and a button that is gone too leaves Radix its default. The dialog, data table and accessibility guides say a menu-opened dialog needs no ref; restoreFocusRef stays for an opener that unmounts or moves. --- .../components/dialog/dialog.browser.test.tsx | 97 ++++++++++++ .../components/entity/entity-row-actions.tsx | 6 +- .../ui/src/hooks/use-restore-focus.test.ts | 142 ++++++++++++++++++ packages/ui/src/hooks/use-restore-focus.ts | 67 ++++++++- .../components/connectors-settings.test.tsx | 44 +++++- .../ui-docs/content/components/data-table.md | 2 +- services/ui-docs/content/components/dialog.md | 2 +- .../content/foundations/accessibility.md | 2 +- 8 files changed, 354 insertions(+), 8 deletions(-) diff --git a/packages/ui/src/components/dialog/dialog.browser.test.tsx b/packages/ui/src/components/dialog/dialog.browser.test.tsx index df8fa03e8d..d8154be809 100644 --- a/packages/ui/src/components/dialog/dialog.browser.test.tsx +++ b/packages/ui/src/components/dialog/dialog.browser.test.tsx @@ -1,5 +1,6 @@ import '@testing-library/jest-dom/vitest'; import { cleanup, waitFor } from '@testing-library/react'; +import { Pencil, Trash2 } from 'lucide-react'; import { useRef, useState } from 'react'; import { afterEach, describe, expect, it } from 'vitest'; import { page, userEvent } from 'vitest/browser'; @@ -7,6 +8,8 @@ import { page, userEvent } from 'vitest/browser'; import { render, screen } from '@/tests/utils/render'; import { DataTableActionMenu } from '../data-table/data-table-action-menu'; +import { EntityRowActions } from '../entity/entity-row-actions'; +import { DeleteDialog } from './delete-dialog'; import { Dialog } from './dialog'; import '../../globals.css'; @@ -57,6 +60,100 @@ function MenuDialogHarness() { ); } +/** A table row's actions menu whose items open dialogs, with no restore + * ref anywhere: the menu's own button is where focus has to come back. */ +function RowMenuHarness() { + const [dialog, setDialog] = useState<'edit' | 'delete' | null>(null); + return ( + <> + + setDialog('edit'), + }, + { + key: 'delete', + label: 'Delete', + icon: Trash2, + destructive: true, + onClick: () => setDialog('delete'), + }, + ]} + /> + { + if (!open) setDialog(null); + }} + > + + + { + if (!open) setDialog(null); + }} + onDelete={() => setDialog(null)} + /> + + ); +} + +describe('row menu to dialog, without a restore ref', () => { + it.each([ + ['Edit credential', 'Escape'], + ['Delete', 'Escape'], + ['Delete', 'Cancel'], + ])( + 'returns focus to the row menu button after %s closes by %s', + async (item, close) => { + const { user } = render(); + const trigger = screen.getByRole('button', { + name: 'Actions for GitHub', + }); + await user.tab(); + await user.tab(); + expect(trigger).toHaveFocus(); + await user.keyboard('{Enter}'); + await waitFor(() => + expect( + screen.getByRole('menuitem', { name: 'Edit credential' }), + ).toHaveFocus(), + ); + if (item === 'Delete') await user.keyboard('{ArrowDown}'); + await waitFor(() => + expect(screen.getByRole('menuitem', { name: item })).toHaveFocus(), + ); + await user.keyboard('{Enter}'); + const dialog = await screen.findByRole('dialog'); + await waitFor(() => + expect(dialog.contains(document.activeElement)).toBe(true), + ); + if (close === 'Escape') { + await user.keyboard('{Escape}'); + } else { + screen.getByRole('button', { name: 'Cancel' }).focus(); + await user.keyboard('{Enter}'); + } + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect( + screen.queryByRole('menu', { hidden: true }), + ).not.toBeInTheDocument(); + expect(trigger).toHaveFocus(); + }); + }, + ); +}); + describe('menu-to-dialog lifecycle', () => { it('keeps keyboard activation, modal focus trapping and trigger restoration', async () => { const { user } = render(); diff --git a/packages/ui/src/components/entity/entity-row-actions.tsx b/packages/ui/src/components/entity/entity-row-actions.tsx index 9960a7ce9a..a69f71d159 100644 --- a/packages/ui/src/components/entity/entity-row-actions.tsx +++ b/packages/ui/src/components/entity/entity-row-actions.tsx @@ -44,7 +44,11 @@ interface EntityRowActionsProps { align?: 'start' | 'center' | 'end'; /** Whether the entire menu trigger is disabled */ disabled?: boolean; - /** Stable focus target for dialogs opened from an unmounting menu item. */ + /** + * The menu button, for a caller that names it as a dialog's + * `restoreFocusRef`. A dialog opened from one of the items returns focus + * here without it: the menu names its button (`useRestoreFocus`). + */ triggerRef?: React.RefObject; } diff --git a/packages/ui/src/hooks/use-restore-focus.test.ts b/packages/ui/src/hooks/use-restore-focus.test.ts index 5e1c5859d6..03f27ebfbf 100644 --- a/packages/ui/src/hooks/use-restore-focus.test.ts +++ b/packages/ui/src/hooks/use-restore-focus.test.ts @@ -194,6 +194,148 @@ describe('useRestoreFocus', () => { expect(event.defaultPrevented).toBe(false); }); + /** A menu button and its open menu holding one item, as Radix renders + * them: the menu labelled by its button, the button declaring the popup. */ + function openMenu(itemLabel = 'Edit') { + const trigger = document.createElement('button'); + trigger.id = 'row-menu-trigger'; + trigger.setAttribute('aria-haspopup', 'menu'); + const menu = document.createElement('div'); + menu.setAttribute('role', 'menu'); + menu.setAttribute('aria-labelledby', trigger.id); + const item = document.createElement('div'); + item.setAttribute('role', 'menuitem'); + item.tabIndex = 0; + item.textContent = itemLabel; + menu.appendChild(item); + document.body.append(trigger, menu); + item.focus(); + return { trigger, menu, item }; + } + + it("returns focus to the menu's button when a menu item opened it", () => { + // A row's actions menu → Edit: no restore ref at the call site. The menu + // names its button, and the button is still there once the menu is gone. + const { trigger, menu } = openMenu(); + + const { result } = renderHook(({ open }) => useRestoreFocus(open), { + initialProps: { open: true }, + }); + menu.remove(); + + const event = new Event('close', { cancelable: true }); + result.current(event); + + expect(event.defaultPrevented).toBe(true); + expect(document.activeElement).toBe(trigger); + }); + + it('climbs a submenu to the outermost menu button', () => { + const { trigger, menu } = openMenu('More'); + const subTrigger = menu.querySelector('[role="menuitem"]'); + if (subTrigger === null) throw new Error('no item'); + subTrigger.id = 'row-menu-more'; + subTrigger.setAttribute('aria-haspopup', 'menu'); + const submenu = document.createElement('div'); + submenu.setAttribute('role', 'menu'); + submenu.setAttribute('aria-labelledby', subTrigger.id); + const item = document.createElement('div'); + item.setAttribute('role', 'menuitem'); + item.tabIndex = 0; + submenu.appendChild(item); + document.body.appendChild(submenu); + item.focus(); + + const { result } = renderHook(({ open }) => useRestoreFocus(open), { + initialProps: { open: true }, + }); + menu.remove(); + submenu.remove(); + result.current(new Event('close', { cancelable: true })); + + expect(document.activeElement).toBe(trigger); + }); + + it('finds the button that controls a menu naming no label', () => { + const trigger = document.createElement('button'); + trigger.setAttribute('aria-haspopup', 'true'); + trigger.setAttribute('aria-controls', 'actions-menu'); + const menu = document.createElement('div'); + menu.id = 'actions-menu'; + menu.setAttribute('role', 'menu'); + const item = document.createElement('div'); + item.setAttribute('role', 'menuitem'); + item.tabIndex = 0; + menu.appendChild(item); + document.body.append(trigger, menu); + item.focus(); + + const { result } = renderHook(({ open }) => useRestoreFocus(open), { + initialProps: { open: true }, + }); + menu.remove(); + result.current(new Event('close', { cancelable: true })); + + expect(document.activeElement).toBe(trigger); + }); + + it("prefers the caller's fallback over the menu's button", () => { + openMenu(); + const toolbar = document.createElement('button'); + document.body.appendChild(toolbar); + const fallbackRef = createRef(); + fallbackRef.current = toolbar; + + const { result } = renderHook( + ({ open }) => useRestoreFocus(open, fallbackRef), + { initialProps: { open: true } }, + ); + result.current(new Event('close', { cancelable: true })); + + expect(document.activeElement).toBe(toolbar); + }); + + it('never takes a label that opens nothing for the menu button', () => { + // A listbox labelled by its heading: the heading is no return point. + const heading = document.createElement('h2'); + heading.id = 'picker-heading'; + heading.tabIndex = -1; + const listbox = document.createElement('div'); + listbox.setAttribute('role', 'listbox'); + listbox.setAttribute('aria-labelledby', heading.id); + const option = document.createElement('div'); + option.setAttribute('role', 'option'); + option.tabIndex = 0; + listbox.appendChild(option); + document.body.append(heading, listbox); + option.focus(); + + const { result } = renderHook(({ open }) => useRestoreFocus(open), { + initialProps: { open: true }, + }); + listbox.remove(); + const event = new Event('close', { cancelable: true }); + result.current(event); + + expect(event.defaultPrevented).toBe(false); + expect(document.activeElement).not.toBe(heading); + }); + + it('leaves Radix its default when the menu button is gone too', () => { + // The whole row went (another session deleted it): nothing to return to. + const { trigger, menu } = openMenu(); + + const { result } = renderHook(({ open }) => useRestoreFocus(open), { + initialProps: { open: true }, + }); + menu.remove(); + trigger.remove(); + const event = new Event('close', { cancelable: true }); + result.current(event); + + expect(event.defaultPrevented).toBe(false); + }); + it('leaves an ordinary control that merely sits in a menu alone', () => { // The rule is the element's own role, not its ancestry: a button inside a // menu-labelled container is still a real control. diff --git a/packages/ui/src/hooks/use-restore-focus.ts b/packages/ui/src/hooks/use-restore-focus.ts index 65159b3810..ec15a31f11 100644 --- a/packages/ui/src/hooks/use-restore-focus.ts +++ b/packages/ui/src/hooks/use-restore-focus.ts @@ -24,6 +24,53 @@ function isTransientOpener(element: HTMLElement): boolean { return role !== null && TRANSIENT_OPENER_ROLES.has(role); } +/** The overlays a transient opener sits in. */ +const TRANSIENT_POPUP = '[role="menu"], [role="listbox"]'; +/** How far a submenu chain is followed before giving up. */ +const MAX_POPUP_DEPTH = 8; + +/** + * The button whose popup holds `element` — where a keyboard user expects to + * land once a dialog opened from one of that popup's items closes. The + * WAI-ARIA menu button pattern names the relation from both ends: the popup + * is labelled by its button (`aria-labelledby`) or the button controls it + * (`aria-controls`), and the button declares the popup (`aria-haspopup`). + * Standard ARIA, like the transient roles themselves, so any menu that + * follows the pattern answers here (Radix's `DropdownMenu` does). A submenu + * is labelled by the item that opened it, itself transient, so the walk + * climbs to the outermost button. + * + * Read when the overlay OPENS: by the time it closes, the popup is gone. + */ +function popupButtonOf(element: HTMLElement): HTMLElement | null { + const doc = element.ownerDocument; + const idsIn = (value: string | null) => (value ?? '').split(/\s+/); + const opensAPopup = (candidate: Element | null): candidate is HTMLElement => + candidate instanceof HTMLElement && + (candidate.getAttribute('aria-haspopup') ?? 'false') !== 'false'; + let current = element; + for (let depth = 0; depth < MAX_POPUP_DEPTH; depth++) { + if (!isTransientOpener(current)) return current; + const popup = current.closest(TRANSIENT_POPUP); + if (popup === null) return null; + const button = + idsIn(popup.getAttribute('aria-labelledby')) + .map((id) => (id === '' ? null : doc.getElementById(id))) + .find(opensAPopup) ?? + (popup.id === '' + ? undefined + : [...doc.querySelectorAll('[aria-controls]')].find( + (candidate) => + idsIn(candidate.getAttribute('aria-controls')).includes( + popup.id, + ) && opensAPopup(candidate), + )); + if (button === undefined || button === current) return null; + current = button; + } + return null; +} + /** * Restores DOM focus to the control that was focused before an overlay opened. * @@ -42,7 +89,12 @@ function isTransientOpener(element: HTMLElement): boolean { * does not also run. * * What it captured is not always a control that can hold focus past the close - * — see `TRANSIENT_OPENER_ROLES` — which is what `fallbackRef` is for. + * — see `TRANSIENT_OPENER_ROLES`. A menu item's own menu names its button, + * so the hook finds that button itself (`popupButtonOf`): a dialog opened + * from a row's actions menu returns focus to that row's menu button with no + * wiring at the call site. `fallbackRef` is for everything else — an opener + * that unmounts or moves (a toolbar button the first row replaces), or a + * return point the caller chooses — and, when set, wins over the menu button. * * @param open Whether the overlay is currently open. * @param fallbackRef Optional stable element to focus when the captured opener @@ -55,11 +107,18 @@ export function useRestoreFocus( fallbackRef?: RefObject, ) { const previouslyFocused = useRef(null); + /** The menu button behind a transient opener, read while its menu stands. */ + const popupButton = useRef(null); useLayoutEffect(() => { if (open) { const active = document.activeElement; previouslyFocused.current = active instanceof HTMLElement ? active : null; + popupButton.current = + previouslyFocused.current !== null && + isTransientOpener(previouslyFocused.current) + ? popupButtonOf(previouslyFocused.current) + : null; } }, [open]); @@ -67,7 +126,8 @@ export function useRestoreFocus( (event: Event) => { let target = previouslyFocused.current; // Menu items and other transient openers go away with the overlay they - // belong to; fall back to a stable trigger (e.g. the menu button). + // belong to; fall back to a stable trigger — the caller's, else the + // menu button the item's menu named when the overlay opened. // `` is no opener either: focus rests there when the focused // control was removed in the same update that opened this overlay — an // edit dialog's Cancel bringing a details dialog back. @@ -77,7 +137,7 @@ export function useRestoreFocus( target === target.ownerDocument.body || isTransientOpener(target) ) { - target = fallbackRef?.current ?? null; + target = fallbackRef?.current ?? popupButton.current; } // Only take over from Radix when a restore target still exists in the // document; otherwise let Radix's default close behaviour run. @@ -86,6 +146,7 @@ export function useRestoreFocus( target.focus(); } previouslyFocused.current = null; + popupButton.current = null; }, [fallbackRef], ); diff --git a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx index 1ca6722fc1..bee1b6aa59 100644 --- a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx +++ b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx @@ -2,7 +2,7 @@ import { pickFilterOption } from '@tale/ui/testing/filters'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { checkAccessibility } from '@/tests/utils/a11y'; -import { render, screen, within } from '@/tests/utils/render'; +import { render, screen, waitFor, within } from '@/tests/utils/render'; import type { ConnectorSummary, @@ -710,6 +710,48 @@ describe('ConnectorsSettings', () => { }); }); + // #3715: the menu item that opened the dialog is gone once it closes, so + // a keyboard user lands back on the row's menu button — never . + it.each(['Edit credential', 'Replace token', 'Delete'])( + 'returns keyboard focus to the row menu once %s closes', + async (item) => { + const { user } = render(); + const trigger = screen.getByRole('button', { + name: 'Actions for Platform bot', + }); + trigger.focus(); + await user.keyboard('{Enter}'); + const menu = within(await screen.findByRole('menu')); + const target = menu.getByRole('menuitem', { name: item }); + for ( + let step = 0; + step < 8 && document.activeElement !== target; + step++ + ) { + await user.keyboard('{ArrowDown}'); + } + expect(target).toHaveFocus(); + await user.keyboard('{Enter}'); + const dialog = await screen.findByRole('dialog'); + await waitFor(() => { + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + expect(dialog).toContainElement( + document.activeElement as HTMLElement, + ); + }); + + // Cancel from the keyboard; Escape is the real-browser suite's + // (`@tale/ui` dialog.browser.test.tsx), jsdom's layer stack needs two. + within(dialog).getByRole('button', { name: 'Cancel' }).focus(); + await user.keyboard('{Enter}'); + + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(trigger).toHaveFocus(); + }); + }, + ); + it('keeps make-default visible but inert on a disabled credential', async () => { const { user } = render(); await user.click( diff --git a/services/ui-docs/content/components/data-table.md b/services/ui-docs/content/components/data-table.md index 48bb26b3c8..84d249ec1e 100644 --- a/services/ui-docs/content/components/data-table.md +++ b/services/ui-docs/content/components/data-table.md @@ -65,7 +65,7 @@ The toolbar wraps rather than overflows. When its column cannot hold the control When an `addAction` opens a dialog, pass a button ref as `addAction.triggerRef` and the same ref as the dialog's `restoreFocusRef`. The ref follows the button when creating the first row moves it from the empty state into the toolbar, so closing the dialog returns focus to the new button. -When a `DataTableActionMenu` item opens a dialog, pass a stable button ref as `triggerRef` and pass the same ref to the dialog's `restoreFocusRef`. The menu item disappears when the dialog opens; the toolbar button remains the keyboard user's return point after closing it. +When a `DataTableActionMenu` or `EntityRowActions` item opens a dialog, closing the dialog returns focus to the menu's button. The menu item disappears when the dialog opens, so the dialog returns to the button the menu names as its label. Pass a button ref as `triggerRef` and the same ref as the dialog's `restoreFocusRef` only when that button can itself unmount or move while the dialog is open. ## Decide what scrolls diff --git a/services/ui-docs/content/components/dialog.md b/services/ui-docs/content/components/dialog.md index c59baa0cf2..c488566cdc 100644 --- a/services/ui-docs/content/components/dialog.md +++ b/services/ui-docs/content/components/dialog.md @@ -72,7 +72,7 @@ Keep descriptions in one place rather than repeating them in the summary and bod | `customHeader` | Replaces the visible header; the required title remains available to assistive technology. | | `hideClose` | Hides the close control; provide an accessible dismiss path unless the current operation deliberately blocks it. | | `className`, `headerClassName`, `bodyClassName`, `footerClassName` | Targeted layout adjustments. | -| `restoreFocusRef` | Stable fallback when the captured opener unmounts, for example after a menu closes. | +| `restoreFocusRef` | Stable fallback when the captured opener unmounts or moves, for example a toolbar button the first row replaces. A dialog opened from a menu item needs none: it returns to that menu's button. | | `preventCloseAutoFocus` | Opt out of automatic restoration only when the caller explicitly manages the next focus target. | ## Handle lifecycle and focus deliberately diff --git a/services/ui-docs/content/foundations/accessibility.md b/services/ui-docs/content/foundations/accessibility.md index 6b95df6c8d..3d5fb1911e 100644 --- a/services/ui-docs/content/foundations/accessibility.md +++ b/services/ui-docs/content/foundations/accessibility.md @@ -47,7 +47,7 @@ The target must accept programmatic focus. `tabIndex={-1}` makes the main region ## Check overlays and disabled controls -A modal dialog traps focus while open and should return it to a useful opener on close. `Dialog`, `Sheet` and `ResponsiveDialog` all capture the opener themselves; if that opener unmounts, supply a stable `restoreFocusRef`. Test Escape, explicit cancellation, completion, and a failed request. Nonmodal tooltips and popovers do not all share modal focus behavior; do not assume every overlay traps focus. A popover that renders as `role="dialog"` still needs a name: point `aria-labelledby` at its visible heading, as `FilterPanel` does. +A modal dialog traps focus while open and should return it to a useful opener on close. `Dialog`, `Sheet` and `ResponsiveDialog` all capture the opener themselves. When the opener is a menu item, which is gone once the dialog closes, they return focus to the button that opened the menu. If any other opener unmounts or moves, supply a stable `restoreFocusRef`. Test Escape, explicit cancellation, completion, and a failed request. Nonmodal tooltips and popovers do not all share modal focus behavior; do not assume every overlay traps focus. A popover that renders as `role="dialog"` still needs a name: point `aria-labelledby` at its visible heading, as `FilterPanel` does. `disabledReason` keeps supported disabled controls reachable so people can discover why an action is unavailable. Check both the tooltip and the blocked action. Keep essential instructions visible outside the tooltip as well. From 66642591b63f3e498dc8bac6030c38374b4c4c8c Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:30:05 +0000 Subject: [PATCH 2/9] test(platform): keep connector dialogs whole across live refetches Once another session's credential write refreshes an open connectors page (#3712, next commit), the list refetches under whatever the admin holds open. #3778 made the shared credential table's columns stable and seeds the edit form when it opens, and tested both on the AI providers page. These tests hold both on the connectors page: - an Edit dialog the admin typed into stays open, with what they typed, through a refetch that changed the list; - an Edit opened after a colleague's rename shows the new name, and its untouched form cannot save the old name back. Each fails with its #3778 change reverted: the first without the stable columns, the second with stable columns but no seed-on-open. --- .../components/connectors-settings.test.tsx | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx index bee1b6aa59..a006626455 100644 --- a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx +++ b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx @@ -752,6 +752,72 @@ describe('ConnectorsSettings', () => { }, ); + // #3712: another session's write reaches the open page, so the list + // refetches under whatever the admin has open. + it('keeps an open, typed-into dialog across a refetch that changed the list', async () => { + const page = () => ; + const { user, rerender } = render(page()); + await user.click( + screen.getByRole('button', { name: 'Actions for Platform bot' }), + ); + await user.click( + within(await screen.findByRole('menu')).getByRole('menuitem', { + name: 'Edit credential', + }), + ); + const form = within( + await screen.findByRole('dialog', { name: 'Edit credential' }), + ); + await rename(user, form, 'Platform bot (typed)'); + + // A colleague added a credential: new rows, new objects, new counts. + fixtures.credentials = [ + ...defaultCredentials.map((row) => ({ ...row })), + credential({ id: 'cred-9', name: 'Ops bot' }), + ]; + rerender(page()); + + expect(screen.getByText('Ops bot')).toBeInTheDocument(); + expect( + screen.getByRole('dialog', { name: 'Edit credential' }), + ).toBeInTheDocument(); + expect(form.getByRole('textbox', { name: /^Name/ })).toHaveValue( + 'Platform bot (typed)', + ); + }); + + it('opens Edit on what the listing holds now, not what it held at mount', async () => { + const page = () => ; + const { user, rerender } = render(page()); + // A colleague renamed the credential while this page stayed open. + fixtures.credentials = [ + credential({ + id: 'cred-1', + name: 'Platform bot (ops)', + isDefault: true, + }), + defaultCredentials[1], + ]; + rerender(page()); + + await user.click( + screen.getByRole('button', { name: 'Actions for Platform bot (ops)' }), + ); + await user.click( + within(await screen.findByRole('menu')).getByRole('menuitem', { + name: 'Edit credential', + }), + ); + const form = within( + await screen.findByRole('dialog', { name: 'Edit credential' }), + ); + expect(form.getByRole('textbox', { name: /^Name/ })).toHaveValue( + 'Platform bot (ops)', + ); + // Saving an untouched form must not write the old name back. + expect(form.getByRole('button', { name: 'Save' })).toBeDisabled(); + }); + it('keeps make-default visible but inert on a disabled credential', async () => { const { user } = render(); await user.click( From 1ceeda751fb3a4955d7a6d6fddac07af522ba27f Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:44:08 +0000 Subject: [PATCH 3/9] fix(platform): hint connector credential writes to every open tab An open Settings > Connectors page never learned about another session's credential changes (#3712). A credential another admin deleted stayed listed and actionable, and one they added stayed hidden, until a reload or a remount after the five-minute freshness window. The same listing feeds the compose Inbox field and a thread's mailbox. Connector credential writes emitted no realtime hint, although the app already keyed every read of the listing under `connector_credential`. - Every write the listing shows now inserts one organization-wide `connector_credential` hint in its own transaction: a create (the settings door and the consent callback's in-transaction seams), an update (rename, rotation, enable or disable, endpoint, config), a delete and the default it hands on, a new default, a grant the refresh found dead, and the mailbox config heal. A silent token renewal and the mail-sync cursor change nothing a listing shows and stay quiet. Both ends name the entity through `CONNECTOR_CREDENTIAL_HINT_ENTITY`. - A refusal that proves the cache stale now refreshes it like a success. An adapter row can declare `refusalInvalidates`, and the shared write hooks then fire its invalidation on such a refusal. The connector and AI provider credential update, delete and set-default rows declare `CREDENTIAL_NOT_FOUND`. A tab that missed a hint (its stream was down) drops the ghost row, and the delete confirm with it, instead of failing the same way on every click. - The hooks' comments no longer describe a Convex reactive query. Tests: the service hint test and the refresh test drive every write against a statement-answering double, including a lost compare-and-swap that announces nothing. The reads test runs the real hooks and adapter rows over a stubbed fetch and hint stream: a hint refetches the shared listing, a NOT_FOUND refusal refetches the connectors or providers listing, and another refusal does not. It also locks #3714's fix (#3806): a refused create or edit on either surface raises no generic toast. Each fails with its change reverted. The manual suite gains CONN-F21 (two sessions) and CONN-B11 (a missed hint). The admin guide (EN/DE/FR) says the table updates while open. --- docs/de/platform/admin/connectors.md | 2 +- docs/en/platform/admin/connectors.md | 2 +- docs/fr/platform/admin/connectors.md | 2 +- .../connectors/hooks/connector-reads.test.tsx | 324 ++++++++++++++++++ .../settings/connectors/hooks/mutations.ts | 9 +- .../settings/connectors/hooks/queries.ts | 8 +- .../platform/app/hooks/use-backend-action.ts | 7 + .../app/hooks/use-backend-mutation.ts | 7 + services/platform/app/lib/backend/adapters.ts | 7 + services/platform/app/lib/backend/settings.ts | 23 +- .../service.hints.test.ts | 261 ++++++++++++++ .../service.oauth2-refresh.test.ts | 36 +- .../domains/connector_credentials/service.ts | 71 +++- services/platform/lib/shared/hint-entities.ts | 12 + .../tests/manual/reference/automation.md | 1 + .../tests/manual/suites/connectors.md | 19 +- 16 files changed, 761 insertions(+), 30 deletions(-) create mode 100644 services/platform/app/features/settings/connectors/hooks/connector-reads.test.tsx create mode 100644 services/platform/backend/domains/connector_credentials/service.hints.test.ts diff --git a/docs/de/platform/admin/connectors.md b/docs/de/platform/admin/connectors.md index 5eb598c9e6..1779e4b5dd 100644 --- a/docs/de/platform/admin/connectors.md +++ b/docs/de/platform/admin/connectors.md @@ -27,7 +27,7 @@ Manche Connectors benötigen zusätzlich die Adresse der Instanz. Für Confluenc ## Einen Standard wählen -Die Tabelle zeigt eine Zeile je Zugangsdaten-Eintrag. **Standard** kennzeichnet den Eintrag für Aktionen ohne ausdrückliche Auswahl. Mit **Zum Standard machen** im Zeilenmenü änderst du ihn. Pro Connector ist ein Standard möglich. +Die Tabelle zeigt eine Zeile je Zugangsdaten-Eintrag und aktualisiert sich ohne Neuladen, solange sie geöffnet ist: Was andere Admins hinzufügen, ändern oder löschen, siehst du sofort. **Standard** kennzeichnet den Eintrag für Aktionen ohne ausdrückliche Auswahl. Mit **Zum Standard machen** im Zeilenmenü änderst du ihn. Pro Connector ist ein Standard möglich. Ein Connector mit mehreren Einträgen, aber ohne Standard funktioniert weiterhin für Aufrufer, die Zugangsdaten benennen. Ohne einen solchen Namen braucht der Aufruf einen Standard. Benenne Konten eindeutig, bevor du sie in Automatisierungen verwendest, damit später erkennbar bleibt, welches Konto gemeint ist. diff --git a/docs/en/platform/admin/connectors.md b/docs/en/platform/admin/connectors.md index 5624a1c729..662184b423 100644 --- a/docs/en/platform/admin/connectors.md +++ b/docs/en/platform/admin/connectors.md @@ -27,7 +27,7 @@ Some connectors also require an instance address. For Confluence, use the Atlass ## Choose the default -The table contains one row per credential. The **Default** badge marks the credential used when an action does not explicitly name one. Select **Make default** in a row's menu to change it; one default is allowed per connector. +The table contains one row per credential and updates while it is open: a credential another admin adds, changes or deletes appears there without a reload. The **Default** badge marks the credential used when an action does not explicitly name one. Select **Make default** in a row's menu to change it; one default is allowed per connector. A connector with several credentials and no default can still serve callers that name a credential. Callers that omit the name need a default. Name accounts clearly before wiring automations so a future administrator can identify the intended account. diff --git a/docs/fr/platform/admin/connectors.md b/docs/fr/platform/admin/connectors.md index 965517b9c4..b5541feecb 100644 --- a/docs/fr/platform/admin/connectors.md +++ b/docs/fr/platform/admin/connectors.md @@ -27,7 +27,7 @@ Certains connecteurs demandent aussi l’adresse de l’instance. Pour Confluenc ## Choisir les identifiants par défaut -Le tableau contient une ligne par jeu d’identifiants. Le badge **Par défaut** indique ceux utilisés lorsqu’une action n’en nomme pas. **Définir par défaut**, dans le menu d’une ligne, change ce choix. Chaque connecteur a un seul choix par défaut. +Le tableau contient une ligne par jeu d’identifiants et se met à jour sans rechargement tant qu’il est ouvert : ce qu’un autre admin ajoute, modifie ou supprime y apparaît aussitôt. Le badge **Par défaut** indique ceux utilisés lorsqu’une action n’en nomme pas. **Définir par défaut**, dans le menu d’une ligne, change ce choix. Chaque connecteur a un seul choix par défaut. Sans choix par défaut, un connecteur qui possède plusieurs identifiants peut toujours servir les appels qui les nomment explicitement. Les autres appels ont besoin d’un choix par défaut. Nomme les comptes clairement avant de les utiliser dans des automatisations, pour que leur destination reste compréhensible. diff --git a/services/platform/app/features/settings/connectors/hooks/connector-reads.test.tsx b/services/platform/app/features/settings/connectors/hooks/connector-reads.test.tsx new file mode 100644 index 0000000000..6a2a51137f --- /dev/null +++ b/services/platform/app/features/settings/connectors/hooks/connector-reads.test.tsx @@ -0,0 +1,324 @@ +import { AppShell } from '@tale/ui/app-shell'; +import { toast } from '@tale/ui/use-toast'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + useCreateCredential as useCreateProviderCredential, + useDeleteCredential as useDeleteProviderCredential, + useUpdateCredential as useUpdateProviderCredential, +} from '@/app/features/settings/providers/hooks/mutations'; +import { useProviderCredentials } from '@/app/features/settings/providers/hooks/queries'; +import { useBackendQuery } from '@/app/hooks/use-backend-query'; +import { useBackendHints } from '@/app/lib/backend/use-backend-hints'; +import { i18n } from '@/lib/i18n/i18n'; +import { CONNECTOR_CREDENTIAL_HINT_ENTITY } from '@/lib/shared/hint-entities'; + +import { + useCreateCredential, + useDeleteCredential, + useSetDefaultCredential, + useUpdateCredential, +} from './mutations'; +import { useConnectorCredentials } from './queries'; + +/** + * #3712 and #3714 at the seam the pages use: real hooks, real adapter rows + * and a real query client; only `fetch` is stubbed, answering like the + * backend, and the hint stream is a controllable stand-in. + * + * - Another session's credential write reaches the open connectors page, + * and the mailbox reads that share its listing, as a hint. + * - A write refused because its credential is gone — a hint this tab + * missed — refetches the listing, so the ghost row drops instead of + * failing the same way on every click. Other refusals leave it alone. + * - A refused create or edit raises no generic "Try again" toast: the + * dialog shows the server's sentence inline, once. + */ + +vi.mock('@tale/ui/use-toast', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, toast: vi.fn() }; +}); + +const ORG = 'org-connectors'; +const CONNECTOR_LIST = '/api/app/connector-credentials'; +const PROVIDER_LIST = '/api/app/provider-credentials'; + +/** The GET paths the stubbed backend answered, in order. */ +let gets: string[] = []; +/** What a write to a credential id answers: a refusal, or success. */ +let writeAnswer: { status: number; body: unknown } = { + status: 200, + body: { ok: true }, +}; + +function json(body: unknown, status = 200): Response { + return new Response(status === 204 ? null : JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +function backend(input: RequestInfo | URL, init?: RequestInit): Response { + const url = new URL( + input instanceof Request ? input.url : String(input), + 'http://localhost', + ); + const path = url.pathname; + if ((init?.method ?? 'GET') !== 'GET') { + return json(writeAnswer.body, writeAnswer.status); + } + gets.push(path); + if (path === CONNECTOR_LIST) return json({ credentials: [] }); + if (path === PROVIDER_LIST) return json({ credentials: [] }); + // The session probe and anything else this file does not exercise. + return json({ error: 'UNAUTHORIZED' }, 401); +} + +const fetchesOf = (path: string) => + gets.filter((entry) => entry === path).length; + +const refusal = (code: string, message: string, status: number) => ({ + status, + body: { error: code, message }, +}); + +/** A controllable hint stream: the test dispatches the backend's events. */ +class FakeEventSource { + static last: FakeEventSource | undefined; + readyState = 1; + private readonly listeners = new Map< + string, + Set<(event: MessageEvent) => void> + >(); + + constructor() { + FakeEventSource.last = this; + } + + addEventListener( + type: string, + listener: (event: MessageEvent) => void, + ): void { + const set = this.listeners.get(type) ?? new Set(); + set.add(listener); + this.listeners.set(type, set); + } + + removeEventListener( + type: string, + listener: (event: MessageEvent) => void, + ): void { + this.listeners.get(type)?.delete(listener); + } + + close(): void { + this.readyState = 2; + } + + emit(type: string, data: string): void { + for (const listener of this.listeners.get(type) ?? []) { + listener(new MessageEvent(type, { data })); + } + } +} + +let queryClient: QueryClient; + +function wrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +/** Every destructive toast raised so far. */ +const failureToasts = () => + vi + .mocked(toast) + .mock.calls.map(([shown]) => shown) + .filter((shown) => shown.variant === 'destructive'); + +beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + gets = []; + writeAnswer = { status: 200, body: { ok: true } }; + window.__ENV__ = { BASE_PATH: '' }; + vi.spyOn(window, 'fetch').mockImplementation((input, init) => + Promise.resolve(backend(input, init)), + ); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + queryClient.clear(); + vi.mocked(toast).mockClear(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + delete window.__ENV__; + FakeEventSource.last = undefined; +}); + +describe('connector credential reads', () => { + it("refreshes the open list — and the mailbox reads on it — when another session's write is hinted", async () => { + vi.stubGlobal('EventSource', FakeEventSource); + renderHook( + () => { + useBackendHints(ORG); + useConnectorCredentials(ORG); + // The compose Inbox field and a thread's mailbox read the same + // listing (`useEmailConnectors`, `useMailboxes`). + useBackendQuery('connector_credentials/queries:listCredentials', { + organizationId: ORG, + }); + }, + { wrapper }, + ); + await waitFor(() => expect(fetchesOf(CONNECTOR_LIST)).toBe(1)); + + act(() => { + FakeEventSource.last?.emit( + 'hint', + JSON.stringify({ + entity: CONNECTOR_CREDENTIAL_HINT_ENTITY, + entityId: 'cred-1', + }), + ); + }); + + // One listing, shared: one refetch serves every reader. + await waitFor(() => expect(fetchesOf(CONNECTOR_LIST)).toBe(2)); + }); + + it.each([ + ['Disable', () => useUpdateCredential(), { status: 'disabled' }], + ['Make default', () => useSetDefaultCredential(), {}], + ['Delete', () => useDeleteCredential(), {}], + ] as const)( + 'refetches the list when %s names a credential another session deleted', + async (_verb, useWrite, extra) => { + const { result } = renderHook( + () => { + useConnectorCredentials(ORG); + return useWrite(); + }, + { wrapper }, + ); + await waitFor(() => expect(fetchesOf(CONNECTOR_LIST)).toBe(1)); + writeAnswer = refusal( + 'CREDENTIAL_NOT_FOUND', + 'Credential not found.', + 404, + ); + + await act(async () => { + await expect( + result.current.mutateAsync({ + organizationId: ORG, + credentialId: 'cred-gone', + ...extra, + }), + ).rejects.toMatchObject({ data: { code: 'CREDENTIAL_NOT_FOUND' } }); + }); + + await waitFor(() => expect(fetchesOf(CONNECTOR_LIST)).toBe(2)); + }, + ); + + it('leaves the list alone for a refusal that says nothing about it', async () => { + const { result } = renderHook( + () => { + useConnectorCredentials(ORG); + return useSetDefaultCredential(); + }, + { wrapper }, + ); + await waitFor(() => expect(fetchesOf(CONNECTOR_LIST)).toBe(1)); + writeAnswer = refusal('RATE_LIMITED', 'Slow down.', 429); + + await act(async () => { + await expect( + result.current.mutateAsync({ + organizationId: ORG, + credentialId: 'cred-1', + }), + ).rejects.toBeDefined(); + }); + + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(fetchesOf(CONNECTOR_LIST)).toBe(1); + }); + + it('refetches the AI providers list the same way', async () => { + const { result } = renderHook( + () => { + useProviderCredentials(ORG); + return useDeleteProviderCredential(); + }, + { wrapper }, + ); + await waitFor(() => expect(fetchesOf(PROVIDER_LIST)).toBe(1)); + writeAnswer = refusal('CREDENTIAL_NOT_FOUND', 'Credential not found.', 404); + + await act(async () => { + await expect( + result.current.mutateAsync({ + organizationId: ORG, + credentialId: 'cred-gone', + }), + ).rejects.toBeDefined(); + }); + + await waitFor(() => expect(fetchesOf(PROVIDER_LIST)).toBe(2)); + }); +}); + +describe('refused credential saves (#3714)', () => { + it.each([ + [ + 'connectors create', + () => useCreateCredential(), + { + connectorSlug: 'github', + authMethod: 'bearer', + name: 'GitHub', + secret: { token: 'synthetic' }, + }, + ], + ['connectors edit', () => useUpdateCredential(), { name: 'GitHub' }], + [ + 'AI providers create', + () => useCreateProviderCredential(), + { providerSlug: 'openrouter', authMethod: 'env', name: 'OpenRouter' }, + ], + ['AI providers edit', () => useUpdateProviderCredential(), { name: 'x' }], + ] as const)( + 'reports a refused %s once, in its dialog: no generic toast', + async (_surface, useWrite, args) => { + const { result } = renderHook(() => useWrite(), { wrapper }); + writeAnswer = refusal( + 'CREDENTIAL_NAME_TAKEN', + 'A credential named "GitHub" already exists for this connector — pick a different name.', + 409, + ); + + await act(async () => { + await expect( + result.current.mutateAsync({ + organizationId: ORG, + credentialId: 'cred-1', + ...args, + } as never), + ).rejects.toMatchObject({ data: { code: 'CREDENTIAL_NAME_TAKEN' } }); + }); + + expect(failureToasts()).toEqual([]); + }, + ); +}); diff --git a/services/platform/app/features/settings/connectors/hooks/mutations.ts b/services/platform/app/features/settings/connectors/hooks/mutations.ts index 42a07365b7..89ba6a7fd9 100644 --- a/services/platform/app/features/settings/connectors/hooks/mutations.ts +++ b/services/platform/app/features/settings/connectors/hooks/mutations.ts @@ -3,11 +3,12 @@ import { useBackendMutation } from '@/app/hooks/use-backend-mutation'; /** * Write hooks for the connectors settings page. The secret-carrying writes - * (create, update) are Convex ACTIONS — plaintext must reach the node-side - * encryption layer — while delete and default-swap are plain mutations. The - * credential list is a reactive query, so none of these invalidate anything. + * (create, update) ride the action lane — plaintext must reach the node-side + * encryption layer — while delete and default-swap are plain mutations. Each + * one's adapter row refreshes the credential listing when it lands, and when + * it is refused because the credential is gone (another session deleted it). * Error feedback belongs to the call sites (dialog-inline or toast, via - * `mapConnectorError`), so the mutation hooks opt out of the generic toast. + * `mapCredentialError`), so the mutation hooks opt out of the generic toast. * * OAuth credentials have no write hook here: they are created and refreshed by * the consent flow's callback, which the browser reaches through diff --git a/services/platform/app/features/settings/connectors/hooks/queries.ts b/services/platform/app/features/settings/connectors/hooks/queries.ts index 99b53701af..ad6ee08b33 100644 --- a/services/platform/app/features/settings/connectors/hooks/queries.ts +++ b/services/platform/app/features/settings/connectors/hooks/queries.ts @@ -2,9 +2,11 @@ import { useActionQuery } from '@/app/hooks/use-action-query'; import { useBackendQuery } from '@/app/hooks/use-backend-query'; /** - * Read hooks for the connectors settings page. Credentials come from a - * reactive Convex query (masked by construction — the server never selects - * ciphertext), so the writes next door propagate without manual invalidation. + * Read hooks for the connectors settings page. Credentials come from the + * backend listing (masked by construction — the server never selects + * ciphertext), keyed under the connector-credential entity: this tab's own + * writes refresh it when they land, another session's reach it as a realtime + * hint, and a write refused because its credential is gone refetches it. * The connector catalog comes from an ACTION (it reads the shipped connector * files from disk), so it goes through `useActionQuery`. */ diff --git a/services/platform/app/hooks/use-backend-action.ts b/services/platform/app/hooks/use-backend-action.ts index 7a62754fbf..8855a7a17b 100644 --- a/services/platform/app/hooks/use-backend-action.ts +++ b/services/platform/app/hooks/use-backend-action.ts @@ -72,6 +72,13 @@ export function useBackendAction( }, onError: (error, ...rest) => { console.error(`Action failed: ${name}`, error); + // A refusal that proves the cache stale refreshes it like a success. + if ( + adapter?.invalidate !== undefined && + adapter.refusalInvalidates?.(error) === true + ) { + adapter.invalidate(queryClient, rest[0], adapterCtx); + } if (errorToast !== false) { toast({ title: errorToast?.title ?? t('error.generic.title'), diff --git a/services/platform/app/hooks/use-backend-mutation.ts b/services/platform/app/hooks/use-backend-mutation.ts index 61580b84e7..9df6690e6b 100644 --- a/services/platform/app/hooks/use-backend-mutation.ts +++ b/services/platform/app/hooks/use-backend-mutation.ts @@ -75,6 +75,13 @@ export function useBackendMutation( onError: (error, ...rest) => { // Never swallow a mutation failure, even when the visible toast is opted out. console.error(`Mutation failed: ${name}`, error); + // A refusal that proves the cache stale refreshes it like a success. + if ( + adapter?.invalidate !== undefined && + adapter.refusalInvalidates?.(error) === true + ) { + adapter.invalidate(queryClient, rest[0], adapterCtx); + } if (errorToast !== false) { toast({ title: errorToast?.title ?? t('error.generic.title'), diff --git a/services/platform/app/lib/backend/adapters.ts b/services/platform/app/lib/backend/adapters.ts index c85e9edd37..5db0d141b5 100644 --- a/services/platform/app/lib/backend/adapters.ts +++ b/services/platform/app/lib/backend/adapters.ts @@ -154,6 +154,13 @@ export interface WriteAdapter { args: Record, ctx: AdapterContext, ) => void; + /** + * Whether this refusal proves the reads the caller acted on stale — the + * write named a row another session already removed — so `invalidate` + * fires for it as well. A write whose failure says nothing about the cache + * leaves it out. + */ + refusalInvalidates?: (error: unknown) => boolean; } /** One fetched page on the adapted paginated lane (the 0.4 page envelope). */ diff --git a/services/platform/app/lib/backend/settings.ts b/services/platform/app/lib/backend/settings.ts index b3847d438c..10d7ddb001 100644 --- a/services/platform/app/lib/backend/settings.ts +++ b/services/platform/app/lib/backend/settings.ts @@ -9,10 +9,12 @@ import type { ItemOf, ReturnsOf } from '@/app/lib/backend/contract'; import { API_KEY_HINT_ENTITY, + CONNECTOR_CREDENTIAL_HINT_ENTITY, MEMBER_HINT_ENTITY, PROVIDER_CREDENTIAL_HINT_ENTITY, TEAM_HINT_ENTITY, } from '@/lib/shared/hint-entities'; +import { backendErrorCode } from '@/lib/utils/backend-error'; import { invalidateMyPasswordPolicy } from './account'; import type { @@ -497,7 +499,7 @@ export const settingsReadAdapters: Record = { return { queryKey: backendKey( orgId, - 'connector_credential', + CONNECTOR_CREDENTIAL_HINT_ENTITY, 'list', connectorSlug ?? null, ), @@ -1042,10 +1044,21 @@ function invalidateConnectorCredentials( const orgId = orgOf(args, ctx); if (orgId === undefined) return; void client.invalidateQueries({ - queryKey: backendEntityPrefix(orgId, 'connector_credential'), + queryKey: backendEntityPrefix(orgId, CONNECTOR_CREDENTIAL_HINT_ENTITY), }); } +/** + * A credential write refused because its credential is gone — another + * session deleted it, and this tab missed the hint (its stream was down). + * The listing the reader acted on is stale, so the same reads refetch: the + * row drops, and its menu or confirm with it, instead of failing the same + * way on every click. + */ +function credentialGone(error: unknown): boolean { + return backendErrorCode(error) === 'CREDENTIAL_NOT_FOUND'; +} + function invalidateSandboxSessions( client: Parameters>[0], args: Record, @@ -1348,6 +1361,7 @@ export const settingsWriteAdapters: Record = { }, ).then(() => null), invalidate: invalidateProviderReads, + refusalInvalidates: credentialGone, }, 'provider_credentials/actions:updateCredentialWithDefinition': { run: (args, ctx) => @@ -1385,6 +1399,7 @@ export const settingsWriteAdapters: Record = { { orgId: requireOrg(args, ctx), method: 'DELETE' }, ).then(() => null), invalidate: invalidateProviderReads, + refusalInvalidates: credentialGone, }, 'provider_credentials/mutations:setDefaultCredential': { run: (args, ctx) => @@ -1393,6 +1408,7 @@ export const settingsWriteAdapters: Record = { { orgId: requireOrg(args, ctx), body: { isDefault: true } }, ).then(() => null), invalidate: invalidateProviderReads, + refusalInvalidates: credentialGone, }, 'connector_credentials/actions:createCredential': { run: (args, ctx) => @@ -1433,6 +1449,7 @@ export const settingsWriteAdapters: Record = { ).then(() => null); }, invalidate: invalidateConnectorCredentials, + refusalInvalidates: credentialGone, }, 'connector_credentials/mutations:deleteCredential': { run: (args, ctx) => @@ -1441,6 +1458,7 @@ export const settingsWriteAdapters: Record = { { orgId: requireOrg(args, ctx), method: 'DELETE' }, ).then(() => null), invalidate: invalidateConnectorCredentials, + refusalInvalidates: credentialGone, }, 'connector_credentials/mutations:setDefaultCredential': { run: (args, ctx) => @@ -1449,6 +1467,7 @@ export const settingsWriteAdapters: Record = { { orgId: requireOrg(args, ctx), body: {} }, ).then(() => null), invalidate: invalidateConnectorCredentials, + refusalInvalidates: credentialGone, }, 'connector_oauth_apps/actions:upsert': { run: (args, ctx) => diff --git a/services/platform/backend/domains/connector_credentials/service.hints.test.ts b/services/platform/backend/domains/connector_credentials/service.hints.test.ts new file mode 100644 index 0000000000..328ce0c037 --- /dev/null +++ b/services/platform/backend/domains/connector_credentials/service.hints.test.ts @@ -0,0 +1,261 @@ +// @vitest-environment node + +/** + * #3712: an open Settings > Connectors page learns about another session's + * credential writes only through the realtime hint stream. Every write the + * listing shows — create (the settings door and the consent callback's + * in-transaction seam alike), update, delete with its default hand-over, + * set default and the mailbox config heal — inserts one + * `connector_credential` hint for the organization, in the write's own + * transaction. A write that changes nothing emits none. + * + * Driven against a statement-answering `sql` stand-in; the audit writer is + * a spy. `github` + `bearer` is a shipped connector with no required config. + */ + +import type { Sql, TransactionSql } from 'postgres'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { CONNECTOR_CREDENTIAL_HINT_ENTITY } from '../../../lib/shared/hint-entities.ts'; + +const { createAuditLog } = vi.hoisted(() => ({ createAuditLog: vi.fn() })); +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog })); + +import { + createCredential, + createCredentialInTransaction, + deleteCredential, + patchCredentialConfigInternal, + patchMailSyncWatermarks, + setDefaultCredential, + updateCredential, +} from './service.ts'; + +interface Statement { + text: string; + values: unknown[]; + /** Whether it ran inside `sql.begin`. */ + inTransaction: boolean; +} + +function fakeSql(answer: (statement: Statement) => unknown[] | undefined): { + sql: Sql; + statements: Statement[]; +} { + const statements: Statement[] = []; + let depth = 0; + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const statement = { + text: strings.join('?').replace(/\s+/g, ' ').trim(), + values, + inTransaction: depth > 0, + }; + statements.push(statement); + return Promise.resolve(answer(statement) ?? []); + }; + tag.begin = async (fn: (tx: unknown) => Promise) => { + depth += 1; + try { + return await fn(tag); + } finally { + depth -= 1; + } + }; + tag.unsafe = (text: string) => text; + tag.json = (value: unknown) => value; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a template-tag stand-in for postgres.js + return { sql: tag as unknown as Sql, statements }; +} + +const ROW = { + id: 'cred-1', + organizationId: 'org-1', + connectorSlug: 'github', + authMethod: 'bearer', + name: 'CI bot', + encryptedData: { keyFingerprint: 'fp', iv: 'iv', ciphertext: 'ct', tag: 't' }, + endpointUrl: null, + config: null, + maskedPreview: 'ghp_***', + isDefault: true, + mailSyncInboundSince: null, + mailSyncOutboundSince: null, + status: 'active', + statusDetail: null, + createdBy: 'user-1', + createdAt: 1, + updatedAt: 1, +}; + +const ACTOR = { userId: 'user-1', email: 'ada@example.test' }; + +/** The outbox rows a run inserted, as the hint each one carries. */ +function hints(statements: readonly Statement[]) { + return statements + .filter((s) => s.text.startsWith('INSERT INTO app_realtime.outbox')) + .map((s) => ({ + orgId: s.values[0], + userId: s.values[1], + entity: s.values[2], + entityId: s.values[3], + inTransaction: s.inTransaction, + })); +} + +const hintFor = (entityId: string) => ({ + orgId: 'org-1', + // Org-wide: every admin's open tab, not only the writer's. + userId: null, + entity: CONNECTOR_CREDENTIAL_HINT_ENTITY, + entityId, + inTransaction: true, +}); + +const ownRow = + (row: typeof ROW, extra?: (s: Statement) => unknown[] | undefined) => + (statement: Statement) => + statement.text.includes('WHERE id = ? AND org_id = ? LIMIT 1') + ? [row] + : extra?.(statement); + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('ENCRYPTION_SECRET_HEX', 'test-key-material'); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe('connector credential writes — realtime hints', () => { + it('hints a creation to the whole organization, inside its transaction', async () => { + const { sql, statements } = fakeSql((s) => + s.text.startsWith('INSERT INTO app.connector_credentials') + ? [{ id: 'cred-new' }] + : undefined, + ); + + await createCredential(sql, { + organizationId: 'org-1', + connectorSlug: 'github', + authMethod: 'bearer', + name: 'CI bot', + secret: { token: 'ghp_super_secret' }, + createdBy: 'user-1', + actor: ACTOR, + }); + + expect(hints(statements)).toEqual([hintFor('cred-new')]); + // The hint names the row, never its secret. + expect(JSON.stringify(hints(statements))).not.toContain('ghp_'); + }); + + it('hints a consent-callback creation in the transaction the callback owns', async () => { + // The OAuth callback adds (and Reconnect renews) through the + // in-transaction seams: the hint rides the caller's transaction. + const { sql, statements } = fakeSql((s) => + s.text.startsWith('INSERT INTO app.connector_credentials') + ? [{ id: 'cred-oauth' }] + : undefined, + ); + + await sql.begin((tx) => + createCredentialInTransaction(tx as unknown as TransactionSql, { + organizationId: 'org-1', + connectorSlug: 'github', + authMethod: 'bearer', + name: 'CI bot', + secret: { token: 'ghp_from_consent' }, + createdBy: 'user-1', + }), + ); + + expect(hints(statements)).toEqual([hintFor('cred-oauth')]); + }); + + it('hints an update: a rename, a rotation, a disable', async () => { + for (const patch of [ + { name: 'Release bot' }, + { secret: { token: 'ghp_rotated' } }, + { status: 'disabled' as const }, + ]) { + const { sql, statements } = fakeSql(ownRow(ROW)); + await updateCredential(sql, { + organizationId: 'org-1', + credentialId: 'cred-1', + ...patch, + actor: ACTOR, + }); + expect(hints(statements)).toEqual([hintFor('cred-1')]); + } + }); + + it('hints a delete — and with it the default it handed on', async () => { + const { sql, statements } = fakeSql( + ownRow(ROW, (s) => + s.text.includes("status = 'active' ORDER BY created_at_ms ASC") + ? [{ id: 'cred-2' }] + : undefined, + ), + ); + + await deleteCredential(sql, 'org-1', 'cred-1', ACTOR); + + // One hint covers both rows: the listing refetches whole. + expect(hints(statements)).toEqual([hintFor('cred-1')]); + }); + + it('hints a new default, and stays quiet when it already was', async () => { + const other = { ...ROW, id: 'cred-2', isDefault: false }; + let run = fakeSql(ownRow(other)); + await setDefaultCredential(run.sql, 'org-1', 'cred-2', ACTOR); + expect(hints(run.statements)).toEqual([hintFor('cred-2')]); + + run = fakeSql(ownRow(ROW)); + await setDefaultCredential(run.sql, 'org-1', 'cred-1', ACTOR); + expect(hints(run.statements)).toEqual([]); + }); + + it('hints the mailbox config heal, which changes the sender the Inbox names', async () => { + const { sql, statements } = fakeSql((s) => + s.text.startsWith('UPDATE app.connector_credentials') + ? [{ id: 'cred-1' }] + : undefined, + ); + + await patchCredentialConfigInternal(sql, 'org-1', 'cred-1', { + imapHost: 'imap.example.test', + fromAddress: 'inbox@example.test', + }); + + expect(hints(statements)).toEqual([hintFor('cred-1')]); + }); + + it('stays quiet for a heal of a row that is gone, and for the sync cursor', async () => { + const heal = fakeSql(() => undefined); + await patchCredentialConfigInternal(heal.sql, 'org-1', 'cred-gone', { + imapHost: 'imap.example.test', + }); + expect(hints(heal.statements)).toEqual([]); + + // The mail sync advances its cursor on every pass; nothing a listing + // shows moved, so no tab refetches for it. + const cursor = fakeSql(() => undefined); + await patchMailSyncWatermarks(cursor.sql, 'org-1', 'cred-1', { + inboundSince: 5, + }); + expect(hints(cursor.statements)).toEqual([]); + }); + + it('emits nothing for a write the service refused', async () => { + const { sql, statements } = fakeSql(() => undefined); + await expect( + updateCredential(sql, { + organizationId: 'org-1', + credentialId: 'cred-gone', + name: 'x', + }), + ).rejects.toMatchObject({ code: 'CREDENTIAL_NOT_FOUND' }); + expect(hints(statements)).toEqual([]); + }); +}); diff --git a/services/platform/backend/domains/connector_credentials/service.oauth2-refresh.test.ts b/services/platform/backend/domains/connector_credentials/service.oauth2-refresh.test.ts index 088874932d..4f933a5df8 100644 --- a/services/platform/backend/domains/connector_credentials/service.oauth2-refresh.test.ts +++ b/services/platform/backend/domains/connector_credentials/service.oauth2-refresh.test.ts @@ -82,17 +82,32 @@ interface Store { casLostTo?: Row; } +/** A realtime hint the seam emitted, as the outbox row it inserted. */ +interface EmittedHint { + orgId: unknown; + entity: unknown; + entityId: unknown; +} + /** * A `sql` double over one credential row that behaves like the table: the * listing and the by-id re-read answer the stored row, and both CAS UPDATEs * (the needs-reauth flip and the re-sealed envelope) either write the row * or — when a concurrent write got there first — change nothing and return - * no row. Every UPDATE is also captured for inspection. + * no row. Every UPDATE and every realtime hint is also captured for + * inspection; a transaction runs its statements on the same double. */ -function fakeSql(store: Store): Sql & { updates: Update[] } { +function fakeSql( + store: Store, +): Sql & { updates: Update[]; hints: EmittedHint[] } { const updates: Update[] = []; + const hints: EmittedHint[] = []; const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { const text = strings.join('?'); + if (text.includes('INSERT INTO app_realtime.outbox')) { + hints.push({ orgId: values[0], entity: values[2], entityId: values[3] }); + return Promise.resolve([]); + } if (text.includes('UPDATE app.connector_credentials')) { updates.push({ text, values }); if (text.includes("status = 'needs-reauth'")) { @@ -135,10 +150,19 @@ function fakeSql(store: Store): Sql & { updates: Update[] } { return Object.assign(tag, { unsafe: (text: string) => text, json: (value: unknown) => value, + begin: (fn: (tx: unknown) => Promise) => fn(tag), updates, - }) as unknown as Sql & { updates: Update[] }; + hints, + }) as unknown as Sql & { updates: Update[]; hints: EmittedHint[] }; } +/** The one hint a flip of `cred_1` owes every open settings page. */ +const FLIP_HINT = { + orgId: 'org_1', + entity: 'connector_credential', + entityId: 'cred_1', +}; + function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, @@ -231,6 +255,8 @@ describe('resolveConnectorCredential — oauth2 refresh', () => { expect(update.text).toContain('AND updated_at_ms = ?'); expect(update.values).toContain(1000); expect(update.text).not.toContain('status'); + // A silent renewal changes nothing a listing shows: no hint. + expect(sql.hints).toEqual([]); const next = envelopeOf(store); expect(next.accessToken).toBe('fresh-token'); // The vendor omitted the refresh token and the scopes: the grant's stay. @@ -279,6 +305,8 @@ describe('resolveConnectorCredential — oauth2 refresh', () => { status: 'needs-reauth', statusDetail: expect.stringContaining('no refresh token'), }); + // Every open Settings > Connectors page learns the row needs Reconnect. + expect(sql.hints).toEqual([FLIP_HINT]); }); it('marks a vendor-rejected refresh needs-reauth with the vendor code and refuses', async () => { @@ -333,6 +361,8 @@ describe('resolveConnectorCredential — oauth2 refresh', () => { expect(update.text).toContain("status = 'needs-reauth'"); expect(update.text).toContain('AND updated_at_ms = ?'); expect(update.values).toContain(1000); + // A lost compare-and-swap changed nothing, so it announces nothing. + expect(sql.hints).toEqual([]); }); it("refuses with the winner's verdict when a concurrent refresh already marked the row", async () => { diff --git a/services/platform/backend/domains/connector_credentials/service.ts b/services/platform/backend/domains/connector_credentials/service.ts index af4b1bcbdd..b12e6ce49a 100644 --- a/services/platform/backend/domains/connector_credentials/service.ts +++ b/services/platform/backend/domains/connector_credentials/service.ts @@ -1,6 +1,7 @@ import type { Sql, TransactionSql } from 'postgres'; import { AppError } from '../../../lib/shared/errors/app-error'; +import { CONNECTOR_CREDENTIAL_HINT_ENTITY } from '../../../lib/shared/hint-entities.ts'; import { buildAuthHeader, buildSecretBindings, @@ -27,6 +28,7 @@ import { type EncryptedSecret, } from '../../core/lib/secret_box.ts'; import { toJson } from '../../db/sql.ts'; +import { emitHintInTx } from '../../realtime/outbox.ts'; import { createAuditLog } from '../audit_logs/service.ts'; import { applyMicrosoftTenant, @@ -48,6 +50,11 @@ import { * credential, its connector and auth method — never the secret and never * the config. The actor is the signed-in person a door hands in; a write * without one (a token renewal the callback runs) is the system's. + * + * Every write the listing shows also hints the organization's open tabs in + * the same transaction ({@link hintCredential}), so another admin's add, + * delete or disable reaches an open Settings > Connectors page — and the + * mailbox pickers built on the same listing — within a hint round trip. */ type Db = Sql | TransactionSql; @@ -478,6 +485,25 @@ async function clearOtherDefaults( `; } +/** + * A credential the listing shows changed: tell every open tab of the + * organization. Org-wide on purpose — the listing is the organization's, + * not the writer's — and inside the write's own transaction, so a hint + * never announces a change that rolled back. The mail-sync cursor and a + * silent token renewal change nothing a listing shows, so they emit none. + */ +async function hintCredential( + tx: TransactionSql, + organizationId: string, + credentialId: string, +): Promise { + await emitHintInTx(tx, { + orgId: organizationId, + entity: CONNECTOR_CREDENTIAL_HINT_ENTITY, + entityId: credentialId, + }); +} + export interface MaskedCredential { id: string; connectorSlug: string; @@ -690,6 +716,7 @@ async function insertPreparedCredential( }, status: 'success', }); + await hintCredential(tx, args.organizationId, credentialId); return { credentialId }; } @@ -818,6 +845,7 @@ export async function updateCredentialInTransaction( }, status: 'success', }); + await hintCredential(tx, args.organizationId, row.id); } /** Delete a credential; deleting the DEFAULT promotes the oldest remaining @@ -866,6 +894,7 @@ export async function deleteCredential( }, status: 'success', }); + await hintCredential(tx, organizationId, row.id); }); } @@ -915,6 +944,7 @@ export async function setDefaultCredential( }, status: 'success', }); + await hintCredential(tx, organizationId, row.id); }); } @@ -1120,14 +1150,20 @@ async function markNeedsReauth( row: CredentialRow, statusDetail: string, ): Promise { - const flipped = await sql<{ id: string }[]>` - UPDATE app.connector_credentials - SET status = 'needs-reauth', status_detail = ${statusDetail}, - updated_at_ms = ${Date.now()} - WHERE id = ${row.id} AND org_id = ${row.organizationId} - AND updated_at_ms = ${row.updatedAt} - RETURNING id - `; + // The row turns orange on every open settings page: flip and hint commit + // together, and a lost compare-and-swap announces nothing. + const flipped = await sql.begin(async (tx) => { + const rows = await tx<{ id: string }[]>` + UPDATE app.connector_credentials + SET status = 'needs-reauth', status_detail = ${statusDetail}, + updated_at_ms = ${Date.now()} + WHERE id = ${row.id} AND org_id = ${row.organizationId} + AND updated_at_ms = ${row.updatedAt} + RETURNING id + `; + if (rows.length > 0) await hintCredential(tx, row.organizationId, row.id); + return rows; + }); if (flipped.length === 0) { console.warn( `[connector-credentials] "${row.connectorSlug}" credential "${row.name}" changed under the refresh for organization ${row.organizationId}; not marking needs-reauth (${statusDetail})`, @@ -1432,10 +1468,17 @@ export async function patchCredentialConfigInternal( credentialId: string, config: Record, ): Promise { - await sql` - UPDATE app.connector_credentials SET - config = ${sql.json(toJson(config))}, - updated_at_ms = ${Date.now()} - WHERE id = ${credentialId} AND org_id = ${organizationId} - `; + // The healed sender address is what the compose Inbox field names. + await sql.begin(async (tx) => { + const patched = await tx<{ id: string }[]>` + UPDATE app.connector_credentials SET + config = ${tx.json(toJson(config))}, + updated_at_ms = ${Date.now()} + WHERE id = ${credentialId} AND org_id = ${organizationId} + RETURNING id + `; + if (patched.length > 0) { + await hintCredential(tx, organizationId, credentialId); + } + }); } diff --git a/services/platform/lib/shared/hint-entities.ts b/services/platform/lib/shared/hint-entities.ts index 05f3b8e2bc..0b3695021a 100644 --- a/services/platform/lib/shared/hint-entities.ts +++ b/services/platform/lib/shared/hint-entities.ts @@ -54,6 +54,18 @@ export const DEFERRED_SEND_HINT_ENTITY = 'chat_deferred'; */ export const PROVIDER_CREDENTIAL_HINT_ENTITY = 'provider_credential'; +/** + * An organization's connector credentials — the Settings > Connectors table + * and the mailbox reads built on the same listing (the compose Inbox field, + * the mailbox a thread names). Every write the listing shows hints under + * this entity: an add or a Reconnect through the consent callback, a rename, + * a secret rotation, an enable or disable, a default moved or handed on by a + * delete, and a grant the refresh found dead. Before it existed another + * admin's changes never reached an open page: a deleted credential stayed + * listed and actionable, and a new one stayed hidden, until a reload. + */ +export const CONNECTOR_CREDENTIAL_HINT_ENTITY = 'connector_credential'; + /** * An organization's membership — the Members settings table, the member * pickers a document review or a team dialog reads, and the shell's own diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 2e3d47a188..ec49a96a00 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -259,6 +259,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F19`, `CONN-F20`, `CONN-B7`–`CONN-B10` (the backend half, #3711): a consent lands where its intent says — an Add stores a NEW credential under a name no sibling holds and never renews the default; a Reconnect renews exactly the credential its row named (id, name, default flag, mail-sync cursor and audit actor kept; `needs-reauth` cleared, `disabled` kept) or saves nothing when that credential is gone, even when the delete races the store; the start door keeps a target only when it is this organization's OAuth grant of that connector and the callback never reads one from its request; the initiator's membership and developer role are re-checked at the callback before the code is redeemed; two Adds completing at once number past each other with one default; a pending row minted before migration `0130` completes as an Add; Slack keeps one credential per workspace and refuses a Reconnect into another; membership revocation during the token exchange or already holding the member row refuses the final grant transaction | ✅ automated | `backend/domains/connectors/oauth-grant-plan.test.ts` (the decision table), `backend/domains/connectors/oauth.test.ts`, `backend/domains/connectors/oauth-routes.test.ts`, `backend/integration-check.ts` (`checkConnectorOauthIntent` in `backend/domains/connectors/oauth-intent.integration.ts`, run by `backend:integration`) | | [connectors](../suites/connectors.md) | The new `credential_missing`, `account_mismatch` and `forbidden` server pages and their back link render in EN/DE/FR from the request's language preferences; `de-CH` uses DE, quality weights and unsupported-language fallback are honored, and headers and links cannot inject HTML | ✅ automated | `backend/domains/connectors/oauth-routes.test.ts` (localized renderer and start/callback header propagation) | | [connectors](../suites/connectors.md) | `CONN-F15`, `CONN-F16`, `CONN-F20` (the hand-off): **Connect** starts an Add naming no credential, a row's **Reconnect** names that row — the default's sibling included | 🔶 component | `app/features/settings/connectors/connector-oauth.test.ts`, `app/features/settings/connectors/components/connectors-settings.test.tsx` | +| [connectors](../suites/connectors.md) | `CONN-F21`, `CONN-B11` (the seams, #3712): every credential write the listing shows — the settings door, the consent callback's in-transaction seams, a delete that hands the default on, a needs-reauth flip, the mailbox config heal — inserts one organization-wide `connector_credential` hint in its own transaction, and a silent token renewal or the mail-sync cursor none; the hint refetches the settings listing and the mailbox reads that share it; a credential write refused `CREDENTIAL_NOT_FOUND` refetches the connectors or AI providers listing, and other refusals leave it; an open dialog survives a refetch that changed the list, and **Edit credential** seeds from the row as it is when opened | 🔶 unit + component | `backend/domains/connector_credentials/service.hints.test.ts`, `backend/domains/connector_credentials/service.oauth2-refresh.test.ts`, `app/features/settings/connectors/hooks/connector-reads.test.tsx`, `app/features/settings/connectors/components/connectors-settings.test.tsx` — the two-session round over a real stack stays manual | | [conversations](../suites/conversations.md) | `CONV-G1`–`CONV-G3`, `CONV-F1`–`CONV-F9`, `CONV-B1`–`CONV-B4`, `CONV-F27`, `CONV-F30` | ⛔ manual-only | — (the `email-automation` spec, which automated the gate, redirect, channel filter, and reading pane, was retired in #2857 and has no successor; `home-panel.test.tsx` only proves the Inbox view is absent without an inbox) | | [conversations](../suites/conversations.md) / [responsive](../suites/responsive.md) | `CONV-F29`, `RESP-F11` (the conversation's half): the header's identity mark is the contact's initials, the subject with a title fallback, the contact's name, the relative time, the email and the source (mailbox · address or the API source) in that order, each separator grouped with its item, the actions menu; the phone's back control shows only over an open conversation or compose and leads to the Home list | 🔶 component | `app/features/conversations/components/conversation-header.test.tsx`, `app/features/conversations/components/inbox-mobile-back-button.test.tsx`; the composer frame stays manual, the header at real widths is `RESP-F16`'s row | | [conversations](../suites/conversations.md) | `CONV-F11` | 🔶 partial | `backend/domains/conversations/api-sync.integration.ts` owns HTTP/Postgres source imports, attachments, replies, undo, replay, isolation and deletion; `use-inbox-availability.test.ts` owns the API-only gate. Visual two-app flow and keyboard behavior remain manual. | diff --git a/services/platform/tests/manual/suites/connectors.md b/services/platform/tests/manual/suites/connectors.md index 15c7ac0339..189f1682c6 100644 --- a/services/platform/tests/manual/suites/connectors.md +++ b/services/platform/tests/manual/suites/connectors.md @@ -1,6 +1,6 @@ # Connectors -> **Prefix** `CONN-` · **Reset** none · **Cost** 36 boxes +> **Prefix** `CONN-` · **Reset** none · **Cost** 38 boxes Exercise the **connector credentials** page under Settings — one flat table of every credential the organization holds for a shipped connector (#2889 @@ -232,6 +232,15 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability kept); the default row is byte-for-byte unchanged. A Reconnect on a **Disabled** row renews its grant but leaves it **Disabled** — **Enable** is what returns it. +- [ ] `CONN-F21` · **Another session's writes reach an open page** — Two + signed-in admins, **A** with `/dashboard/{org}/settings/connectors` open. + **B**, in their own browser, adds a credential, renames one, disables one + and deletes one → A's table follows each within a few seconds, with no + reload, focus change or navigation: the new row appears, the renamed and + disabled rows show B's name and **Disabled** badge, the deleted row is + gone. An **Edit credential** dialog A holds open on another row stays open + through B's writes with what A typed; opening **Edit credential** after + B's rename shows B's name. ## Boundary & error tests @@ -285,6 +294,14 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability → **Reconnect** → consent in a different workspace than the row's → The fixed page "That is a different workspace"; nothing was saved. Reconnect in the row's own workspace renews it. +- [ ] `CONN-B11` · **Acting on a row another session deleted** — As in + CONN-F21, but block A's `…/events` request first (DevTools → Network → + block request URL), so A misses the hint; B deletes a credential A still + sees → On A, that row's menu → **Disable** answers one toast + `settings.credentials.updateFailed` naming "Credential not found." and the + row leaves A's table; on another such row, **Delete** → **Delete** answers + `settings.credentials.deleteFailed` once and the confirm closes with the + row. No second click can fail the same way. ## Accessibility (WCAG 2.1 AA) From aa6b5c396a716b2606a1cfb57a6eb968f9f8242c Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:54:51 +0000 Subject: [PATCH 4/9] fix(platform): name the credential a deleted default hands over to Deleting a connector's default credential showed "Deleting it leaves no default until you pick another one." In the same transaction the server made the oldest remaining active credential the default, and nothing said which account took over (#3713). The promotion has been deliberate since the 0.4 mutation: an invocation that names no credential resolves through the default, so it keeps working. The integration lane pins it. The sentence is the AI providers' rule, where nothing promotes, and connectors inherited it through the shared row menu's fallback. The rule is now one function, `defaultSuccessor`: the oldest active credential of the connector, never a disabled or needs-reauth one, with ties broken by id. The delete applies it under the pair lock (as a new credential's default flag is decided), on siblings read after the lock. The listing names its answer on the default's row, and the connectors delete confirm reads it: - "Deleting it makes "Release bot" the default for calls that name no credential", naming the account that takes over; - or no active credential can take over, so unnamed calls fail until an admin picks one; - or, from a listing that names nothing, the rule itself. AI providers keep their sentence. The admin guide and connector overview (EN/DE/FR) state the hand-over. The manual suite gains CONN-F22; CONN-F13 and CONN-F14 no longer expect no default after deleting the default, and pins.md records why. --- docs/de/platform/admin/connectors.md | 2 +- docs/de/platform/connectors/overview.md | 2 +- docs/en/platform/admin/connectors.md | 2 +- docs/en/platform/connectors/overview.md | 2 +- docs/fr/platform/admin/connectors.md | 2 +- docs/fr/platform/connectors/overview.md | 2 +- .../components/connectors-settings.test.tsx | 61 +++++ .../connectors/credential-adapter.tsx | 17 ++ .../credentials/credential-row-actions.tsx | 3 + .../backend/contract/connector-credentials.ts | 2 + .../service.audit.test.ts | 13 +- .../service.default-successor.test.ts | 245 ++++++++++++++++++ .../service.hints.test.ts | 4 +- .../domains/connector_credentials/service.ts | 99 +++++-- services/platform/messages/de.yml | 10 + services/platform/messages/en.yml | 10 + services/platform/messages/fr.yml | 11 + .../tests/manual/reference/automation.md | 3 +- .../platform/tests/manual/reference/pins.md | 1 + .../tests/manual/suites/connectors.md | 19 +- 20 files changed, 473 insertions(+), 37 deletions(-) create mode 100644 services/platform/backend/domains/connector_credentials/service.default-successor.test.ts diff --git a/docs/de/platform/admin/connectors.md b/docs/de/platform/admin/connectors.md index 1779e4b5dd..3cbfce00c0 100644 --- a/docs/de/platform/admin/connectors.md +++ b/docs/de/platform/admin/connectors.md @@ -41,7 +41,7 @@ Nutze die Ersetzen-Aktion der jeweiligen Methode, etwa **API-Schlüssel ersetzen -Das Löschen von Zugangsdaten entzieht abhängigen Automatisierungen und Agenten den Zugriff. Stelle die Aufrufer vorher um und wähle bei Bedarf einen neuen Standard. Ein gelöschter Eintrag lässt sich nicht durch erneutes Öffnen wiederherstellen. +Das Löschen von Zugangsdaten entzieht abhängigen Automatisierungen und Agenten den Zugriff. Stelle die Aufrufer vorher um. Löschst du den Standard eines Connectors, wird sein ältester verbleibender aktiver Eintrag zum Standard; die Bestätigung nennt diesen Eintrag, bevor du löschst. Ein deaktivierter Eintrag oder einer, der neu verbunden werden muss, übernimmt nie. Bleibt kein aktiver Eintrag übrig, hat der Connector keinen Standard, bis du einen wählst. Ein gelöschter Eintrag lässt sich nicht durch erneutes Öffnen wiederherstellen. diff --git a/docs/de/platform/connectors/overview.md b/docs/de/platform/connectors/overview.md index 4c38cac39c..6d0c642f52 100644 --- a/docs/de/platform/connectors/overview.md +++ b/docs/de/platform/connectors/overview.md @@ -47,7 +47,7 @@ Confluence und Shopify brauchen pro Eintrag eine **Instanz-URL**. Verwende den U ## Das Konto für eine Aktion bestimmen -Eine Aktion verwendet den ausdrücklich genannten Eintrag oder, ohne Angabe, den Standard des Connectors. Nur ein Eintrag pro Connector kann Standard sein. Ohne Standard schlägt ein Aufruf ohne Namen fehl, selbst wenn andere Zugangsdaten vorhanden sind. +Eine Aktion verwendet den ausdrücklich genannten Eintrag oder, ohne Angabe, den Standard des Connectors. Nur ein Eintrag pro Connector kann Standard sein. Ohne Standard schlägt ein Aufruf ohne Namen fehl, selbst wenn andere Zugangsdaten vorhanden sind. Löschst du den Standard, wird der älteste verbleibende aktive Eintrag dieses Connectors zum Standard; die Löschbestätigung nennt ihn vorher. Zwei Support-Postfächer sind beispielsweise zwei Einträge. Vergib unterscheidbare Namen und prüfe die aufgelöste Eingabe eines Workflows vor dem Live-Lauf. Der Standard wird verwendet, wenn die Aktion keinen bestimmten Eintrag nennt. Postfachoperationen, die alle aktiven Konten auslesen, sind ein eigener Fall. diff --git a/docs/en/platform/admin/connectors.md b/docs/en/platform/admin/connectors.md index 662184b423..8f10fa6d04 100644 --- a/docs/en/platform/admin/connectors.md +++ b/docs/en/platform/admin/connectors.md @@ -41,7 +41,7 @@ Use the row's replacement action for its method, such as **Replace API key** or -Deleting credentials removes access for automations and agents that depend on them. Move callers first and select a new default when needed. Deletion cannot be undone by reopening the same row. +Deleting credentials removes access for automations and agents that depend on them. Move callers first. Deleting a connector's default makes its oldest remaining active credential the default, and the confirmation names that credential before you delete. A disabled credential or one that needs Reconnect never takes over, so with no active credential left the connector has no default until you choose one. Deletion cannot be undone by reopening the same row. diff --git a/docs/en/platform/connectors/overview.md b/docs/en/platform/connectors/overview.md index 18ece05f68..346f6a7380 100644 --- a/docs/en/platform/connectors/overview.md +++ b/docs/en/platform/connectors/overview.md @@ -47,7 +47,7 @@ Confluence and Shopify require an **Instance URL** per credential. Use the Atlas ## Choose which account an action uses -An action uses the credential it explicitly names, or the connector’s default when no name is supplied. Only one credential per connector is the default. With no default, an unnamed call fails even if other credentials exist. +An action uses the credential it explicitly names, or the connector’s default when no name is supplied. Only one credential per connector is the default. With no default, an unnamed call fails even if other credentials exist. Deleting the default makes the oldest remaining active credential of that connector the default; the delete confirmation names it first. For example, two support mailboxes are two credential rows. Choose names that distinguish them and inspect a workflow’s resolved input before running it live. A default is a fallback for selection, not proof that every job should use that account. Mailbox operations designed to inspect all active accounts are a separate case. diff --git a/docs/fr/platform/admin/connectors.md b/docs/fr/platform/admin/connectors.md index b5541feecb..0ca7ad37fa 100644 --- a/docs/fr/platform/admin/connectors.md +++ b/docs/fr/platform/admin/connectors.md @@ -41,7 +41,7 @@ Utilise l’action de remplacement adaptée à la méthode, par exemple **Rempla -Supprimer des identifiants retire l’accès aux automatisations et agents qui en dépendent. Migre les appelants et choisis un nouveau défaut si nécessaire. Rouvrir la même ligne ne permet pas d’annuler la suppression. +Supprimer des identifiants retire l’accès aux automatisations et agents qui en dépendent. Migre d’abord les appelants. Si tu supprimes les identifiants par défaut d’un connecteur, ses plus anciens identifiants actifs restants deviennent le choix par défaut, et la confirmation les nomme avant la suppression. Des identifiants désactivés ou à reconnecter ne prennent jamais le relais : s’il ne reste aucun identifiant actif, le connecteur n’a pas de choix par défaut tant que tu n’en choisis pas. Rouvrir la même ligne ne permet pas d’annuler la suppression. diff --git a/docs/fr/platform/connectors/overview.md b/docs/fr/platform/connectors/overview.md index bf8a73441a..e744184499 100644 --- a/docs/fr/platform/connectors/overview.md +++ b/docs/fr/platform/connectors/overview.md @@ -47,7 +47,7 @@ Confluence et Shopify demandent une **URL de l'instance** pour chaque compte. Ut ## Déterminer le compte utilisé -Une action utilise les identifiants explicitement nommés, ou ceux par défaut du connector en l’absence de nom. Un seul compte par connector peut être défini comme compte par défaut. Sans compte par défaut, un appel sans nom échoue même si d’autres identifiants existent. +Une action utilise les identifiants explicitement nommés, ou ceux par défaut du connector en l’absence de nom. Un seul compte par connector peut être défini comme compte par défaut. Sans compte par défaut, un appel sans nom échoue même si d’autres identifiants existent. Si tu supprimes le compte par défaut, les plus anciens identifiants actifs restants de ce connector deviennent le compte par défaut ; la confirmation de suppression les nomme d’abord. Deux boîtes support correspondent par exemple à deux lignes. Donne-leur des noms distincts et examine les données résolues du workflow avant une exécution réelle. Le compte par défaut est utilisé lorsque l’action ne nomme pas un autre compte. Les opérations de courrier conçues pour parcourir tous les comptes actifs constituent un cas séparé. diff --git a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx index a006626455..4df954b8fb 100644 --- a/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx +++ b/services/platform/app/features/settings/connectors/components/connectors-settings.test.tsx @@ -818,6 +818,67 @@ describe('ConnectorsSettings', () => { expect(form.getByRole('button', { name: 'Save' })).toBeDisabled(); }); + // #3713: the server hands a deleted default to the oldest active + // credential left, and the listing names it on the default's row. + it.each([ + [ + 'names the credential that takes the default over', + { id: 'cred-3', name: 'Ops bot' }, + 'This is the default credential. Deleting it makes "Ops bot" the default for calls that name no credential.', + ], + [ + 'says no default remains when no active credential can take over', + null, + 'This is the default credential, and no other active credential can take over: calls that name no credential fail until you make one the default.', + ], + ] as const)( + 'the delete confirm of the default %s', + async (_case, successor, sentence) => { + fixtures.credentials = [ + credential({ + id: 'cred-1', + name: 'Platform bot', + isDefault: true, + defaultSuccessor: successor, + }), + ...defaultCredentials.slice(1), + ]; + const { user } = render(); + await user.click( + screen.getByRole('button', { name: 'Actions for Platform bot' }), + ); + await user.click( + within(await screen.findByRole('menu')).getByRole('menuitem', { + name: 'Delete', + }), + ); + const confirm = within( + await screen.findByRole('dialog', { name: 'Delete credential' }), + ); + expect(confirm.getByText(sentence)).toBeInTheDocument(); + // Never the AI providers' rule, which promotes nobody. + expect( + confirm.queryByText(/leaves no default until you pick another one/), + ).not.toBeInTheDocument(); + }, + ); + + it('says nothing about the default when deleting another credential', async () => { + const { user } = render(); + await user.click( + screen.getByRole('button', { name: 'Actions for Release bot' }), + ); + await user.click( + within(await screen.findByRole('menu')).getByRole('menuitem', { + name: 'Delete', + }), + ); + const confirm = within( + await screen.findByRole('dialog', { name: 'Delete credential' }), + ); + expect(confirm.queryByText(/default credential/)).not.toBeInTheDocument(); + }); + it('keeps make-default visible but inert on a disabled credential', async () => { const { user } = render(); await user.click( diff --git a/services/platform/app/features/settings/connectors/credential-adapter.tsx b/services/platform/app/features/settings/connectors/credential-adapter.tsx index c25770e31b..32e6fa3de6 100644 --- a/services/platform/app/features/settings/connectors/credential-adapter.tsx +++ b/services/platform/app/features/settings/connectors/credential-adapter.tsx @@ -320,6 +320,23 @@ export const connectorCredentialAdapter: CredentialAdapter< : t('connectors.credential.needsReauthHint') : undefined, + // Deleting a connector's default hands it to the oldest active credential + // left (the server's `defaultSuccessor`), which the listing names on the + // default's row — so the confirm says who takes over, not the AI + // providers' "no default remains". + deleteWarning: (t, credential) => { + if (!credential.isDefault) return undefined; + const successor = credential.defaultSuccessor; + if (successor === undefined) { + return t('connectors.credential.deleteDefaultHandsOnOldest'); + } + return successor === null + ? t('connectors.credential.deleteDefaultLeavesNone') + : t('connectors.credential.deleteDefaultHandsOn', { + name: successor.name, + }); + }, + // Nothing resolves its key through a connector credential by reference. useDeleteWarning: () => undefined, diff --git a/services/platform/app/features/settings/credentials/credential-row-actions.tsx b/services/platform/app/features/settings/credentials/credential-row-actions.tsx index 7814ebc76f..80c434d95d 100644 --- a/services/platform/app/features/settings/credentials/credential-row-actions.tsx +++ b/services/platform/app/features/settings/credentials/credential-row-actions.tsx @@ -229,6 +229,9 @@ export function CredentialRowActions< // delete will be refused. [ dependencyWarning, + // A surface whose server hands the default on (connectors) says + // so through its own warning; the shared sentence is the + // no-promotion rule. adapter.deleteWarning?.(t, credential, vendor, siblingCount) ?? (credential.isDefault ? t('credentials.deleteDefaultWarning') diff --git a/services/platform/app/lib/backend/contract/connector-credentials.ts b/services/platform/app/lib/backend/contract/connector-credentials.ts index 53f5191e3f..fe25e98d0f 100644 --- a/services/platform/app/lib/backend/contract/connector-credentials.ts +++ b/services/platform/app/lib/backend/contract/connector-credentials.ts @@ -171,6 +171,8 @@ export interface ConnectorCredentialsContract { connectorSlug: string; authMethod: 'oauth2' | 'api-key' | 'bearer' | 'basic'; name: string; + /** On the default only: who deleting it makes the default, or null. */ + defaultSuccessor?: { id: string; name: string } | null; }>; }; } diff --git a/services/platform/backend/domains/connector_credentials/service.audit.test.ts b/services/platform/backend/domains/connector_credentials/service.audit.test.ts index d50eeee432..e0c2c14db2 100644 --- a/services/platform/backend/domains/connector_credentials/service.audit.test.ts +++ b/services/platform/backend/domains/connector_credentials/service.audit.test.ts @@ -205,11 +205,20 @@ describe('connector credential writes — audit rows', () => { }); it('records a deletion with the state it removed and the default it promoted', async () => { + // The pair's siblings, read under its lock: the oldest active one takes + // the default over. + const sibling = { + ...ROW, + id: 'cred-2', + name: 'Backup', + isDefault: false, + createdAt: 2, + }; const { sql } = fakeSql( (s) => ownRow(ROW)(s) ?? - (s.text.startsWith('SELECT id FROM app.connector_credentials') - ? [{ id: 'cred-2' }] + (s.text.includes('WHERE org_id = ? AND connector_slug = ?') + ? [ROW, sibling] : undefined), ); diff --git a/services/platform/backend/domains/connector_credentials/service.default-successor.test.ts b/services/platform/backend/domains/connector_credentials/service.default-successor.test.ts new file mode 100644 index 0000000000..bab9d043d1 --- /dev/null +++ b/services/platform/backend/domains/connector_credentials/service.default-successor.test.ts @@ -0,0 +1,245 @@ +// @vitest-environment node + +/** + * #3713: deleting a connector's DEFAULT credential hands the default to the + * oldest remaining active credential of that connector — a continuity rule + * since 0.4, so calls that name no credential keep working — but the delete + * confirm said no default would remain. The rule now lives in one function: + * the delete applies it, and the listing names its answer on the default + * row, so the confirm can say which account takes over before the admin + * deletes. + * + * Driven against a statement-answering `sql` stand-in; the audit writer is + * a spy. + */ + +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../audit_logs/service.ts', () => ({ createAuditLog: vi.fn() })); + +import { + defaultSuccessor, + deleteCredential, + listCredentials, +} from './service.ts'; + +interface Statement { + text: string; + values: unknown[]; +} + +function fakeSql(answer: (statement: Statement) => unknown[] | undefined): { + sql: Sql; + statements: Statement[]; +} { + const statements: Statement[] = []; + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const statement = { + text: strings.join('?').replace(/\s+/g, ' ').trim(), + values, + }; + statements.push(statement); + return Promise.resolve(answer(statement) ?? []); + }; + tag.begin = (fn: (tx: unknown) => Promise) => fn(tag); + tag.unsafe = (text: string) => text; + tag.json = (value: unknown) => value; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a template-tag stand-in for postgres.js + return { sql: tag as unknown as Sql, statements }; +} + +type Status = 'active' | 'disabled' | 'needs-reauth'; + +function row( + id: string, + name: string, + createdAt: number, + patch: { isDefault?: boolean; status?: Status; connectorSlug?: string } = {}, +) { + return { + id, + organizationId: 'org-1', + connectorSlug: patch.connectorSlug ?? 'github', + authMethod: 'bearer' as const, + name, + encryptedData: { + keyFingerprint: 'fp', + iv: 'iv', + ciphertext: 'ct', + tag: 't', + }, + endpointUrl: null, + config: null, + maskedPreview: 'ghp_***', + isDefault: patch.isDefault ?? false, + mailSyncInboundSince: null, + mailSyncOutboundSince: null, + status: patch.status ?? ('active' as Status), + statusDetail: null, + createdBy: 'user-1', + createdAt, + updatedAt: createdAt, + }; +} + +const SUPPORT = row('cred-support', 'Support bot', 1, { isDefault: true }); +const RELEASE = row('cred-release', 'Release bot', 3); +const OPS = row('cred-ops', 'Ops bot', 5); +const PAUSED = row('cred-paused', 'Paused bot', 2, { status: 'disabled' }); +const STALE = row('cred-stale', 'Stale grant', 2, { status: 'needs-reauth' }); + +/** The table as the delete sees it: the own-row read and the pair read. */ +function table(rows: ReturnType[]) { + return (statement: Statement) => { + if (statement.text.includes('WHERE id = ? AND org_id = ? LIMIT 1')) { + return rows.filter((r) => r.id === statement.values[1]); + } + if (statement.text.includes('WHERE org_id = ? AND connector_slug = ?')) { + return rows.filter((r) => r.connectorSlug === statement.values[2]); + } + if (statement.text.includes('FROM app.connector_credentials WHERE')) { + return rows; + } + return undefined; + }; +} + +/** Whom a run's UPDATE made the default, if anyone. */ +const promoted = (statements: readonly Statement[]) => + statements + .filter((s) => s.text.includes('SET is_default = true')) + .map((s) => s.values.at(-1)); + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('ENCRYPTION_SECRET_HEX', 'test-key-material'); +}); + +describe('defaultSuccessor', () => { + it('hands the default to the oldest active sibling', () => { + expect(defaultSuccessor([SUPPORT, OPS, RELEASE], SUPPORT.id)).toBe(RELEASE); + }); + + it('never to a disabled credential or a dead grant', () => { + expect(defaultSuccessor([SUPPORT, PAUSED, STALE, OPS], SUPPORT.id)).toBe( + OPS, + ); + expect(defaultSuccessor([SUPPORT, PAUSED, STALE], SUPPORT.id)).toBeNull(); + }); + + it('breaks a tie on the creation instant by id, like the listing reads it', () => { + const b = row('cred-b', 'B', 7); + const a = row('cred-a', 'A', 7); + expect(defaultSuccessor([SUPPORT, b, a], SUPPORT.id)).toBe(a); + }); + + it('answers null when the default is the only credential', () => { + expect(defaultSuccessor([SUPPORT], SUPPORT.id)).toBeNull(); + }); +}); + +describe('the listing names what a delete of the default would do', () => { + it('names the successor on the default row alone', async () => { + const other = row('cred-shop', 'Shop', 0, { + connectorSlug: 'shopify', + isDefault: true, + }); + const { sql } = fakeSql(table([SUPPORT, RELEASE, OPS, other])); + + const listed = await listCredentials(sql, 'org-1'); + + const byId = new Map(listed.map((c) => [c.id, c])); + expect(byId.get(SUPPORT.id)?.defaultSuccessor).toEqual({ + id: RELEASE.id, + name: 'Release bot', + }); + // Another connector's credentials never take over GitHub's default. + expect(byId.get('cred-shop')?.defaultSuccessor).toBeNull(); + expect(byId.get(RELEASE.id)).not.toHaveProperty('defaultSuccessor'); + }); + + it('says no default would remain when only disabled or dead siblings are left', async () => { + const { sql } = fakeSql(table([SUPPORT, PAUSED, STALE])); + + const support = (await listCredentials(sql, 'org-1')).find( + (c) => c.id === SUPPORT.id, + ); + + expect(support?.defaultSuccessor).toBeNull(); + }); +}); + +describe('deleteCredential', () => { + it('makes exactly the credential the listing named the default', async () => { + const rows = [SUPPORT, OPS, RELEASE, PAUSED]; + const named = ( + await listCredentials(fakeSql(table(rows)).sql, 'org-1') + ).find((c) => c.id === SUPPORT.id)?.defaultSuccessor?.id; + const { sql, statements } = fakeSql(table(rows)); + + await deleteCredential(sql, 'org-1', SUPPORT.id); + + expect(named).toBe(RELEASE.id); + expect(promoted(statements)).toEqual([RELEASE.id]); + }); + + it('decides under the pair lock, from siblings read after it', async () => { + const { sql, statements } = fakeSql(table([SUPPORT, RELEASE])); + + await deleteCredential(sql, 'org-1', SUPPORT.id); + + const lock = statements.findIndex((s) => + s.text.includes('pg_advisory_xact_lock'), + ); + const pairRead = statements.findIndex((s) => + s.text.includes('WHERE org_id = ? AND connector_slug = ?'), + ); + const removal = statements.findIndex((s) => + s.text.startsWith('DELETE FROM app.connector_credentials'), + ); + expect(lock).toBeGreaterThanOrEqual(0); + expect(lock).toBeLessThan(pairRead); + expect(pairRead).toBeLessThan(removal); + }); + + it('promotes nobody when no active sibling remains', async () => { + const { sql, statements } = fakeSql(table([SUPPORT, PAUSED])); + + await deleteCredential(sql, 'org-1', SUPPORT.id); + + expect(promoted(statements)).toEqual([]); + }); + + it('leaves the default alone when a non-default credential is deleted', async () => { + const { sql, statements } = fakeSql(table([SUPPORT, RELEASE, OPS])); + + await deleteCredential(sql, 'org-1', RELEASE.id); + + expect(promoted(statements)).toEqual([]); + }); + + it('refuses a credential another delete removed while it waited for the lock', async () => { + let reads = 0; + const { sql, statements } = fakeSql((statement) => { + if (statement.text.includes('WHERE id = ? AND org_id = ? LIMIT 1')) { + reads += 1; + // Found before the lock, gone after it. + return reads === 1 ? [SUPPORT] : []; + } + if (statement.text.includes('WHERE org_id = ? AND connector_slug = ?')) { + return [RELEASE]; + } + return undefined; + }); + + await expect( + deleteCredential(sql, 'org-1', SUPPORT.id), + ).rejects.toMatchObject({ code: 'CREDENTIAL_NOT_FOUND' }); + expect( + statements.some((s) => + s.text.startsWith('DELETE FROM app.connector_credentials'), + ), + ).toBe(false); + }); +}); diff --git a/services/platform/backend/domains/connector_credentials/service.hints.test.ts b/services/platform/backend/domains/connector_credentials/service.hints.test.ts index 328ce0c037..a045c072f1 100644 --- a/services/platform/backend/domains/connector_credentials/service.hints.test.ts +++ b/services/platform/backend/domains/connector_credentials/service.hints.test.ts @@ -193,8 +193,8 @@ describe('connector credential writes — realtime hints', () => { it('hints a delete — and with it the default it handed on', async () => { const { sql, statements } = fakeSql( ownRow(ROW, (s) => - s.text.includes("status = 'active' ORDER BY created_at_ms ASC") - ? [{ id: 'cred-2' }] + s.text.includes('WHERE org_id = ? AND connector_slug = ?') + ? [ROW, { ...ROW, id: 'cred-2', isDefault: false, createdAt: 2 }] : undefined, ), ); diff --git a/services/platform/backend/domains/connector_credentials/service.ts b/services/platform/backend/domains/connector_credentials/service.ts index b12e6ce49a..1990ee6df2 100644 --- a/services/platform/backend/domains/connector_credentials/service.ts +++ b/services/platform/backend/domains/connector_credentials/service.ts @@ -42,8 +42,8 @@ import { * (this module's decrypt seam). The validation, payload, masking, and * auth-injection pieces are the 0.4 PURE modules reused verbatim; the * transactional invariants (case-insensitive name uniqueness, at most one - * default per pair, delete-promotes-oldest-active) run here, backed by the - * table's own unique indexes. + * default per pair, delete-promotes-oldest-active through + * `defaultSuccessor`) run here, backed by the table's own unique indexes. * * Every write leaves a `connector` audit row in its own transaction * (`connector_credential.created` / `.updated` / `.deleted`) naming the @@ -517,6 +517,12 @@ export interface MaskedCredential { statusDetail?: string; createdAt: number; updatedAt: number; + /** + * On the pair's default, in the listing: the credential deleting this one + * makes the default ({@link defaultSuccessor}), or null when none would — + * so the delete confirm can name the account that takes over. + */ + defaultSuccessor?: { id: string; name: string } | null; } function toMasked(row: CredentialRow): MaskedCredential { @@ -549,7 +555,24 @@ export async function listCredentials( OR connector_slug = ${connectorSlug ?? null}) ORDER BY connector_slug ASC, name ASC `; - return rows.map(toMasked); + const byConnector = new Map(); + for (const row of rows) { + const pair = byConnector.get(row.connectorSlug); + if (pair === undefined) byConnector.set(row.connectorSlug, [row]); + else pair.push(row); + } + return rows.map((row) => { + const masked = toMasked(row); + if (row.isDefault) { + const successor = defaultSuccessor( + byConnector.get(row.connectorSlug) ?? [], + row.id, + ); + masked.defaultSuccessor = + successor === null ? null : { id: successor.id, name: successor.name }; + } + return masked; + }); } export async function getCredential( @@ -848,8 +871,37 @@ export async function updateCredentialInTransaction( await hintCredential(tx, args.organizationId, row.id); } -/** Delete a credential; deleting the DEFAULT promotes the oldest remaining - * ACTIVE row of the pair (never a disabled one). */ +/** + * Who becomes the pair's default when its default, `deletedId`, is deleted: + * the oldest remaining ACTIVE credential. An invocation that names no + * credential resolves through the default, so leaving the connector without + * one would break every automation step that relied on it, not just the + * deleted account. Never a disabled row or a dead grant (`needs-reauth`): + * handing the default to a credential that cannot serve would be worse. + * Null when no active sibling remains. + * + * The one copy of the rule: the delete applies it and the listing names its + * answer, so the delete confirm can say which account takes over. + */ +export function defaultSuccessor< + R extends { id: string; status: CredentialStatus; createdAt: number }, +>(siblings: readonly R[], deletedId: string): R | null { + let successor: R | null = null; + for (const row of siblings) { + if (row.id === deletedId || row.status !== 'active') continue; + if ( + successor === null || + row.createdAt < successor.createdAt || + (row.createdAt === successor.createdAt && row.id < successor.id) + ) { + successor = row; + } + } + return successor; +} + +/** Delete a credential; deleting the DEFAULT hands it to + * {@link defaultSuccessor}. */ export async function deleteCredential( sql: Sql, organizationId: string, @@ -857,26 +909,29 @@ export async function deleteCredential( actor?: CredentialActor, ): Promise { await sql.begin(async (tx) => { - const row = await requireOwnRow(tx, organizationId, credentialId); + const found = await requireOwnRow(tx, organizationId, credentialId); + // The successor is decided from the sibling list, like a new + // credential's default flag: under the same pair lock, so a concurrent + // add cannot read the pair while its default is leaving. + await lockCredentialPair(tx, organizationId, found.connectorSlug); + const siblings = await rowsForConnector( + tx, + organizationId, + found.connectorSlug, + ); + const row = + siblings.find((sibling) => sibling.id === found.id) ?? + (await requireOwnRow(tx, organizationId, credentialId)); await tx`DELETE FROM app.connector_credentials WHERE id = ${row.id}`; let promotedId: string | null = null; - if (row.isDefault) { - const successors = await tx<{ id: string }[]>` - SELECT id FROM app.connector_credentials - WHERE org_id = ${organizationId} - AND connector_slug = ${row.connectorSlug} AND status = 'active' - ORDER BY created_at_ms ASC, id ASC - LIMIT 1 + const successor = row.isDefault ? defaultSuccessor(siblings, row.id) : null; + if (successor !== null) { + await tx` + UPDATE app.connector_credentials + SET is_default = true, updated_at_ms = ${Date.now()} + WHERE id = ${successor.id} `; - const successor = successors[0]; - if (successor) { - await tx` - UPDATE app.connector_credentials - SET is_default = true, updated_at_ms = ${Date.now()} - WHERE id = ${successor.id} - `; - promotedId = successor.id; - } + promotedId = successor.id; } await createAuditLog(tx, { organizationId, diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index 68a6fb1442..83df774816 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -5726,6 +5726,16 @@ settings: Verbinde neu, um die Freigabe erneut zu erteilen. needsReauthDetail: '{detail} Verbinde neu, um die Freigabe erneut zu erteilen.' reconnect: Neu verbinden + deleteDefaultHandsOn: >- + Das sind die Standard-Zugangsdaten. Nach dem Löschen wird "{name}" zum + Standard für Aufrufe, die keine Zugangsdaten nennen. + deleteDefaultLeavesNone: >- + Das sind die Standard-Zugangsdaten, und keine anderen aktiven + Zugangsdaten können übernehmen: Aufrufe ohne eigene Angabe schlagen + fehl, bis du einen Eintrag zum Standard machst. + deleteDefaultHandsOnOldest: >- + Das sind die Standard-Zugangsdaten. Nach dem Löschen wird der älteste + aktive Eintrag dieses Connectors zum Standard, sofern es einen gibt. replace: apiKeyTitle: API-Schlüssel ersetzen tokenTitle: Token ersetzen diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index 38b81ce03b..3f452aeab9 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -5903,6 +5903,16 @@ settings: needsReauthHint: Authorization expired or revoked. Reconnect to restore access. needsReauthDetail: '{detail} Reconnect to grant consent again.' reconnect: Reconnect + deleteDefaultHandsOn: >- + This is the default credential. Deleting it makes "{name}" the default + for calls that name no credential. + deleteDefaultLeavesNone: >- + This is the default credential, and no other active credential can + take over: calls that name no credential fail until you make one the + default. + deleteDefaultHandsOnOldest: >- + This is the default credential. Deleting it makes the oldest active + credential of this connector the default, if there is one. replace: apiKeyTitle: Replace API key tokenTitle: Replace token diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index bf4d943dc2..ae86607a35 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -5812,6 +5812,17 @@ settings: accorder le consentement à nouveau. needsReauthDetail: '{detail} Reconnecte-toi pour accorder le consentement à nouveau.' reconnect: Reconnecter + deleteDefaultHandsOn: >- + Ce sont les identifiants par défaut. Si tu les supprimes, « {name} » + devient le choix par défaut des appels qui n'en nomment aucun. + deleteDefaultLeavesNone: >- + Ce sont les identifiants par défaut, et aucun autre identifiant actif + ne peut prendre le relais : les appels qui n'en nomment aucun échouent + jusqu'à ce que tu en définisses d'autres par défaut. + deleteDefaultHandsOnOldest: >- + Ce sont les identifiants par défaut. Si tu les supprimes, les plus + anciens identifiants actifs de ce connecteur deviennent le choix par + défaut, s'il y en a. replace: apiKeyTitle: Remplacer la clé API tokenTitle: Remplacer le jeton diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index ec49a96a00..d5e6dbbf93 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -250,7 +250,8 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [chat](../suites/chat.md) | `CHAT-F39`–`CHAT-F40` — a send snaps the new message to the top even inside the thread-open restore window, a downward wheel during the glide does not cancel it while an upward one does, **Scroll to bottom** pressed mid-stream keeps following growth until an upward wheel, and the previous turn's rows stay mounted at their rendered height when a send demotes them to history | 🔶 browser | `app/features/chat/components/message-thread.browser.test.tsx` (real Chromium geometry), `app/features/chat/hooks/use-chat-scroll.test.ts` (tick precedence, wheel/touch direction), `app/features/chat/hooks/use-response-slack.test.ts` (spacer formula), `app/features/chat/components/message-thread.test.tsx` (row identity); trackpad momentum and touch gestures stay manual | | [chat](../suites/chat.md) | `CHAT-F41` — a tool-using reply never jumps at settle: the thread view reads the settled rounds' text and reasoning from the stream channel's parts (an earlier round's text shows while the next tool runs, and the finalized text is byte-identical to what streamed), holds those parts the way it holds the text from the generation row's delete until the finalized row lands (also across a synthesized row's handover to its real row), and defers to the finalized row's own parts the moment they arrive | 🔶 component | `app/features/chat/lib/thread-view-core.test.ts` (earlier-round text from live parts, settle-gap parts hold, synthesized-row text + handover); the rendered outcome — no jump of the answer body at settle — stays manual | | [chat](../suites/chat.md) | `CHAT-F43` — an arena round shows in the column as its own optimistic send the moment it is sent, the send-snap glides it to the column's top with the reply's room beneath it, and the real rows take the bubble over in place (one copy, same node) | 🔶 browser | `app/features/chat/components/arena/arena-column.browser.test.tsx` (real Chromium geometry, the transcript read served as a subscription); the fan-out against two live models and the verdict gating stay manual | -| [connectors](../suites/connectors.md) | `CONN-F1`, `CONN-F3`–`CONN-F10`, `CONN-F5a`, `CONN-F13`, `CONN-F14`, `CONN-B1`, `CONN-B4`, `CONN-B5` | 🔶 component | `app/features/settings/connectors/components/connectors-settings.test.tsx` (rows, add flow and its suggested name, row actions, denial) | +| [connectors](../suites/connectors.md) | `CONN-F1`, `CONN-F3`–`CONN-F10`, `CONN-F5a`, `CONN-F13`, `CONN-F14`, `CONN-F22`, `CONN-B1`, `CONN-B4`, `CONN-B5` | 🔶 component | `app/features/settings/connectors/components/connectors-settings.test.tsx` (rows, add flow and its suggested name, row actions, what deleting the default says, denial) | +| [connectors](../suites/connectors.md) | `CONN-F22` (the backend half, #3713): one rule decides the default a delete hands on — the oldest active credential of the connector, never a disabled or needs-reauth one, ties by id; the listing names it on the default's row and the delete applies it under the pair lock | ✅ unit | `backend/domains/connector_credentials/service.default-successor.test.ts` | | [connectors](../suites/connectors.md) | `CONN-F1`–`CONN-F3` (empty state, picker, search) | ✅ automated | `settings.spec.ts` ("connectors: empty credentials surface and the add-catalog picker") | | [connectors](../suites/connectors.md) | `CONN-F7`, `CONN-B1` (required-config gating) | 🔶 component | `app/features/settings/connectors/config-fields.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F17` | 🔶 component | `app/features/settings/connectors/components/mcp-endpoint-section.test.tsx` | diff --git a/services/platform/tests/manual/reference/pins.md b/services/platform/tests/manual/reference/pins.md index 69d1511194..9cd5d261f2 100644 --- a/services/platform/tests/manual/reference/pins.md +++ b/services/platform/tests/manual/reference/pins.md @@ -36,6 +36,7 @@ time you are tempted to shorten one. | `NAV-F11` | The public docs moved to a separate origin. `app/components/user-button.test.tsx` pins the shared canonical constant and safe new-tab attributes; the box no longer expects the old marketing-site subpath. | | `KNOW-F16` | The hub folder listing decorated only `active` sync configs, so a config in `error` lost its "(synced)" label and read as a plain folder — a dead grant froze the mirror with nothing on screen and nobody told (2026-09-15). The listing now decorates errored configs too, the Source cell carries the health badge, and the owner gets one bell + email per failure episode; `sync-health.test.ts` and `service.failure-notify.test.ts` hold the episode rule, the itest lane `onedrive dead grant…` holds it end to end. The badge must also disappear WITHOUT a reload: the engine now emits `folder`/`document` hints, which it never did before. | | `KNOW-F19` | The Source cell spelled its source out, so "OneDrive (synchronisiert)" wrapped onto two lines at the column's minimum width and ran into RAG status; Google Drive alone showed a bare mark that never said whether it synced, and the preview sidebar kept its own three-provider map that printed `google_drive` for the rest (2026-09-15). The cell is now the vendor mark plus a synced / not-synced / failure glyph, from one map the preview reads too, with the words on hover, on focus and as the accessible name; `use-document-source.test.tsx` and `use-documents-table-config.test.tsx` hold the names and glyphs, while the fit, the preview sidebar and the dark theme stay manual. | +| `CONN-F14` / `CONN-F22` | Deleting a connector's default never left it without one while an active credential remained: the server hands the default to the oldest active credential (a 0.4 continuity rule — an unnamed call keeps working), and skips disabled and needs-reauth rows. The shared delete dialog said the opposite, "leaves no default", which is true only for AI providers, and CONN-F14 reached its no-default state by deleting the default (#3713). The rule is now one function (`defaultSuccessor` in `backend/domains/connector_credentials/service.ts`): the delete applies it and the listing names its answer on the default's row, which the confirm reads. `service.default-successor.test.ts` and `connectors-settings.test.tsx` hold both halves; CONN-F14 now reaches no default by disabling it. | | `RESP-F2` / `TASK-F25` | The mobile More sheet (retired with the four-tab bar) was a `Sheet` opened from state — no Radix trigger — and `Sheet` never ran `useRestoreFocus`, so Escape dropped the document on ``. The primitive now restores the opener (`sheet.test.tsx`). The task page's phone details sheet is opened from state the same way, so `TASK-F25` now judges the **Show details** button regaining focus. | | `CONV-F4` / `CONV-F12` / `CONV-F16` / `CONV-F20` / `CONV-F25` | Desktop and phone keep the facets in different places on purpose: the Home panel's Inbox view stands beside every Home route (a chat, a task, a project), so its facets cannot ride the inbox route's URL — it remembers them per device instead; the phone's list is the inbox page itself and keeps `?read=` / `?assignee=` / `?channel=` / `?mailbox=`. Both run on `useInboxList`, so the facet semantics must not differ. The team and channel chips are drawn by the phone list's rows only — the panel's rows share one anatomy with chats and tasks — which is why `CONV-F12` / `CONV-F19` / `CONV-F21` judge them at 390 px. | | `TASK-A2` / `PROJ-A2` | The task detail is a `ResponsiveDialog` with no trigger; neither its dialog nor its drawer branch passed `onCloseAutoFocus`, so Escape left focus on ``. The primitive now captures the opener (`responsive-dialog.test.tsx`); the boxes judge the card regaining focus. | diff --git a/services/platform/tests/manual/suites/connectors.md b/services/platform/tests/manual/suites/connectors.md index 189f1682c6..7f2be643c6 100644 --- a/services/platform/tests/manual/suites/connectors.md +++ b/services/platform/tests/manual/suites/connectors.md @@ -1,6 +1,6 @@ # Connectors -> **Prefix** `CONN-` · **Reset** none · **Cost** 38 boxes +> **Prefix** `CONN-` · **Reset** none · **Cost** 39 boxes Exercise the **connector credentials** page under Settings — one flat table of every credential the organization holds for a shipped connector (#2889 @@ -174,11 +174,11 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability action at all. - [ ] `CONN-F13` · **Delete with confirm** — Row menu → **Delete** → A confirm dialog (`settings.credentials.deleteTitle`, body naming the credential - `settings.credentials.deleteBody`); deleting the default additionally warns - (`settings.credentials.deleteDefaultWarning`). Confirm → toast + `settings.credentials.deleteBody`); deleting the default additionally says + what happens to the default (CONN-F22). Confirm → toast `settings.credentials.deletedToast`; the row is gone after reload. - [ ] `CONN-F14` · **No-default warning** — Leave a connector holding only - non-default active credentials (delete its default, or disable it) → A + non-default credentials that are not disabled (disable its default) → A warning alert above the table names the vendor(s): `settings.credentials.noDefault`. Surfaced, never auto-fixed; it clears once a default is picked. @@ -241,6 +241,17 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability gone. An **Edit credential** dialog A holds open on another row stays open through B's writes with what A typed; opening **Edit credential** after B's rename shows B's name. +- [ ] `CONN-F22` · **Deleting the default hands it on** — GitHub holding + **Support bot** (default), **Release bot** and a disabled **Paused bot**, all + created in that order → **Support bot**'s menu → **Delete** → the confirm + names **Release bot** as the new default + (`settings.connectors.credential.deleteDefaultHandsOn`); confirm → after a + reload **Release bot** carries **Default** and no no-default alert shows. + With only the disabled **Paused bot** left beside the default, the confirm + says no active credential can take over + (`settings.connectors.credential.deleteDefaultLeavesNone`), and after the + delete **Paused bot** stays **Disabled** and not the default. Deleting a + credential that is not the default says nothing about the default. ## Boundary & error tests From f6877a6106cfdab4587a407030eed55639c95d77 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:05:16 +0000 Subject: [PATCH 5/9] docs(platform): document every connector the picker ships The Add credential picker offers fifteen connectors. The connector guides (EN/DE/FR) and the manual suite described thirteen (#3716). GlitchTip (added 2026-09-27) and Jev decisions (#3425) appeared in no catalog page, and the Instance URL guidance named only Confluence and Shopify, although GlitchTip's form asks for one and the automation guide already sends admins to connect it. - The overviews table GlitchTip (token + Instance URL, read-only issue intake for the GlitchTip importer) and Jev decisions (an OpenRouter API key; typed questions answered with calibrated probabilities, read-only, billed to that OpenRouter account). They also say what both read and write. - The Instance URL guidance in the overviews, the admin guides and the connector authoring page names GlitchTip, its origin, and the deployment host policy a self-hosted instance needs. The admin guides' method table names the GlitchTip token scopes and the OpenRouter key. - The screenshot caption no longer counts the connectors, so it cannot drift again. - The GlitchTip form shows its own Instance URL help and placeholder (https://app.glitchtip.com) instead of the generic API example. - The manual suite counts 19 definitions and 15 vendors (CONN-F3), and CONN-F6 covers GlitchTip. A guard keeps them together: `catalog_docs.test.ts` reads the listing the picker serves and fails when a locale's table misses or adds a connector, when a per-credential connector goes unnamed where either guide explains the instance address, or when the manual suite's count or list drifts. It fails 7 of 8 on main's pages. `services/platform/turbo.json` hashes the two docs pages for it, and the turbo-inputs guard lists them. --- docs/de/develop/connectors.md | 2 +- docs/de/platform/admin/connectors.md | 6 +- docs/de/platform/connectors/overview.md | 8 +- docs/en/develop/connectors.md | 2 +- docs/en/platform/admin/connectors.md | 6 +- docs/en/platform/connectors/overview.md | 8 +- docs/fr/develop/connectors.md | 2 +- docs/fr/platform/admin/connectors.md | 6 +- docs/fr/platform/connectors/overview.md | 8 +- .../connectors/credential-adapter.tsx | 4 +- .../features/settings/connectors/labels.ts | 4 + .../catalog_docs.test.ts | 148 ++++++++++++++++++ services/platform/messages/de.yml | 4 + services/platform/messages/en.yml | 3 + services/platform/messages/fr.yml | 4 + .../tests/guards/turbo-inputs.guard.test.ts | 10 ++ .../tests/manual/reference/automation.md | 1 + .../tests/manual/suites/connectors.md | 14 +- services/platform/turbo.json | 2 + 19 files changed, 213 insertions(+), 29 deletions(-) create mode 100644 services/platform/backend/core/connector_credentials/catalog_docs.test.ts diff --git a/docs/de/develop/connectors.md b/docs/de/develop/connectors.md index f3aee098b4..f1db14567d 100644 --- a/docs/de/develop/connectors.md +++ b/docs/de/develop/connectors.md @@ -34,7 +34,7 @@ auth: | `allowedHosts` bei per-credential | Hostsuffixe: `atlassian.net` erlaubt seine Subdomains | | `configFields` | Nicht geheime Angaben je Zugang, etwa Serverhost, Port, Region oder API-Version | -Confluence und Shopify verwenden Ursprünge je Zugang. Geheimnisse gehören nicht in `configFields`, sondern in die verschlüsselten Zugangsdaten. Bei JavaScript-Aktionen setzt `ctx.http` die erlaubten HTTP-Ziele durch. Native Backends, etwa für Mailprotokolle, prüfen ihren Transport selbst; eine HTTP-Freigabeliste beschreibt nicht ihre gesamte Sicherheitsgrenze. +Confluence, GlitchTip und Shopify verwenden Ursprünge je Zugang. Geheimnisse gehören nicht in `configFields`, sondern in die verschlüsselten Zugangsdaten. Bei JavaScript-Aktionen setzt `ctx.http` die erlaubten HTTP-Ziele durch. Native Backends, etwa für Mailprotokolle, prüfen ihren Transport selbst; eine HTTP-Freigabeliste beschreibt nicht ihre gesamte Sicherheitsgrenze. diff --git a/docs/de/platform/admin/connectors.md b/docs/de/platform/admin/connectors.md index 3cbfce00c0..7821c1b838 100644 --- a/docs/de/platform/admin/connectors.md +++ b/docs/de/platform/admin/connectors.md @@ -18,12 +18,12 @@ Der Connector bestimmt die Felder. Verwende die tatsächlichen Zugangsdaten des | Methode | Benötigte Angaben | | --- | --- | -| API-Schlüssel | Der vom Dienst ausgegebene Schlüssel, etwa für Tavily oder Shopify. | -| Token | Ein Dienst-Token, etwa ein persönlicher GitHub-Zugangstoken oder ein Discord-Bot-Token. | +| API-Schlüssel | Der vom Dienst ausgegebene Schlüssel, etwa für Tavily oder Shopify. Jev decisions braucht einen OpenRouter-API-Schlüssel. | +| Token | Ein Dienst-Token, etwa ein persönlicher GitHub-Zugangstoken, ein Discord-Bot-Token oder ein GlitchTip-API-Token mit `project:read` und `event:read`. | | Benutzername und Passwort | Das vom Dienst erwartete Paar, etwa Anmeldung und App-Passwort oder eine anbieterspezifische ID mit Token. | | OAuth | Die Freigabe im Browser beim Anbieter. Tale speichert die zurückgegebene Berechtigung. | -Manche Connectors benötigen zusätzlich die Adresse der Instanz. Für Confluence ist das die Basisadresse der Atlassian-Site. Für Shopify verwendest du die `myshopify.com`-Adresse des Shops, nicht die öffentliche Shop-Domain. +Manche Connectors benötigen zusätzlich die Adresse der Instanz. Für Confluence ist das die Basisadresse der Atlassian-Site. Für GlitchTip ist das der Ursprung der Instanz, etwa `https://app.glitchtip.com`; eine selbst betriebene Instanz muss zusätzlich in der Host-Richtlinie der Bereitstellung für Connectors erlaubt sein. Für Shopify verwendest du die `myshopify.com`-Adresse des Shops, nicht die öffentliche Shop-Domain. ## Einen Standard wählen diff --git a/docs/de/platform/connectors/overview.md b/docs/de/platform/connectors/overview.md index 6d0c642f52..29ae0be23e 100644 --- a/docs/de/platform/connectors/overview.md +++ b/docs/de/platform/connectors/overview.md @@ -16,9 +16,11 @@ Nutze einen Connector, wenn Tale Daten in einem externen Dienst lesen oder ände | Confluence | Confluence-Cloud-Seiten ins Wissen importieren. | Benutzername mit Passwort oder Token. | | Discord | Mit Nachrichten und Kanälen arbeiten. | Token. | | GitHub | Repositorys, Issues und Pull Requests lesen oder verwalten. | Token. | +| GlitchTip | Issues eines Projekts lesen, damit der GlitchTip-Import daraus Aufgaben anlegt. | Token und eine Instanz-URL. | | Gmail | E-Mails lesen, senden und organisieren. | OAuth. | | Google Drive | Dateien ins Wissen importieren. | OAuth. | | IMAP / SMTP Mailbox | E-Mails über einen eigenen Maildienst lesen oder senden. | Benutzername und Passwort. | +| Jev decisions | Typisierte Fragen zu den Daten eines Workflows mit kalibrierten Wahrscheinlichkeiten beantworten, um zu entscheiden, ob gehandelt wird. | API-Schlüssel (ein OpenRouter-Schlüssel). | | Microsoft Outlook | Mit E-Mails, Kalendern und Kontakten arbeiten. | OAuth. | | Shopify | Mit Produkten, Kunden und Bestellungen arbeiten. | API-Schlüssel. | | Slack | Mit Nachrichten und Kanälen arbeiten. | OAuth. | @@ -35,7 +37,7 @@ Wissensimporte verwenden die [Dokumentenindexierung](/de/platform/knowledge/docu Wähle **Zugangsdaten hinzufügen**, suche den Dienst und öffne seine Karte. Bereits eingerichtete Connectors erscheinen zuerst. Trotzdem kannst du für denselben Dienst ein weiteres Konto hinzufügen. Das Formular fragt nach der vom Connector unterstützten Anmeldung. - + ![Der Dialog Zugangsdaten hinzufügen über der Tabelle unter Einstellungen > Connectors, mit den mitgelieferten Connectoren als Karten samt Kategorien und Aktionszahl, einem Suchfeld oben und dem bereits eingerichteten Connector Tavily am Anfang der Liste.](/images/platform/connectors-add-credential.webp) @@ -43,7 +45,7 @@ Wähle **Zugangsdaten hinzufügen**, suche den Dienst und öffne seine Karte. Be Das Feld **Name** enthält zunächst den Namen des Connectors. Fügst du für denselben Dienst mehrere Konten hinzu, ersetze ihn durch einen zweckbezogenen Namen, etwa `Support-Postfach` oder `Release-Bot`. Verwende Zugangsdaten des externen Diensts, keinen Tale-API-Schlüssel. Melde dich bei OAuth mit dem Konto beim Provider an, das du hinzufügen willst, und schließe die Zustimmung ab. Jede Verbindung legt neue Zugangsdaten an, benannt nach dem Connector und durchnummeriert (`Gmail`, dann `Gmail 2`); Slack führt pro Workspace genau einen Satz. Benenne neue Zugangsdaten um, damit die Konten unterscheidbar bleiben. Kann der Vorgang nicht starten, muss gegebenenfalls ein Administrator zuerst die OAuth-App einrichten. -Confluence und Shopify brauchen pro Eintrag eine **Instanz-URL**. Verwende den Ursprung der Atlassian-Site oder die `myshopify.com`-Adresse des Shops, keine beliebige Unterseite oder Kundendomain. [Connector-Zugangsdaten](/de/platform/admin/connectors) erklärt Felder, erneute Autorisierung und Schlüsselaustausch. +Confluence, GlitchTip und Shopify brauchen pro Eintrag eine **Instanz-URL**. Verwende den Ursprung der Atlassian-Site, den Ursprung der GlitchTip-Instanz wie `https://app.glitchtip.com` oder die `myshopify.com`-Adresse des Shops, keine beliebige Unterseite oder Kundendomain. Eine selbst betriebene GlitchTip-Instanz muss zusätzlich in der Host-Richtlinie der Bereitstellung für Connectors erlaubt sein. [Connector-Zugangsdaten](/de/platform/admin/connectors) erklärt Felder, erneute Autorisierung und Schlüsselaustausch. ## Das Konto für eine Aktion bestimmen @@ -55,7 +57,7 @@ Das Deaktivieren erhält die Konfiguration, verhindert aber ihre Nutzung. Der Au ## Lesen und Schreiben unterscheiden -Automatisierungen verwenden Connector-Aktionen als Workflow-Nodes. Jede Aktion definiert Eingabeschema, Ausgabe und Lese- oder Schreibwirkung. Testläufe simulieren die Antworten. Ein Live-Schreibvorgang kann Nachrichten senden oder externe Daten ändern und unterliegt der Freigaberichtlinie der Organisation. +Automatisierungen verwenden Connector-Aktionen als Workflow-Nodes. Jede Aktion definiert Eingabeschema, Ausgabe und Lese- oder Schreibwirkung. GlitchTip und Jev decisions lesen nur: Der GlitchTip-Import legt Tale-Aufgaben an und ändert nie das ursprüngliche Issue, und eine Jev-Entscheidung beantwortet jede Frage mit ihren Wahrscheinlichkeiten, ohne etwas zu schreiben. Jede Entscheidung wird dem OpenRouter-Konto berechnet, dessen Schlüssel die Zugangsdaten enthalten. Testläufe simulieren die Antworten. Ein Live-Schreibvorgang kann Nachrichten senden oder externe Daten ändern und unterliegt der Freigaberichtlinie der Organisation. Projektagenten mit konfigurierten Connectors erhalten deren unterstützte Leseaktionen über Tales Connector-Broker. Er hält diese Zugangsdaten außerhalb der Sandbox und gibt Ergebnisse zurück. Connector-Schreibaktionen lehnt er ab. Direkte GitHub-Werkzeuge und explizite Agent-Secrets nutzen andere Wege und brauchen eine eigene Prüfung. diff --git a/docs/en/develop/connectors.md b/docs/en/develop/connectors.md index d8bbe24c73..560cc8b6cb 100644 --- a/docs/en/develop/connectors.md +++ b/docs/en/develop/connectors.md @@ -34,7 +34,7 @@ auth: | `allowedHosts` in per-credential mode | Host suffixes: `atlassian.net` allows its subdomains | | `configFields` | Non-secret per-credential values such as server host, port, region, or API version | -Confluence and Shopify use per-credential origins. Keep secrets out of `configFields`; use the encrypted credential payload. For JavaScript actions, `ctx.http` enforces the declared HTTP destination boundary. Native backends, such as mailbox protocols, implement their own transport checks; an HTTP allowlist alone does not describe their whole security boundary. +Confluence, GlitchTip and Shopify use per-credential origins. Keep secrets out of `configFields`; use the encrypted credential payload. For JavaScript actions, `ctx.http` enforces the declared HTTP destination boundary. Native backends, such as mailbox protocols, implement their own transport checks; an HTTP allowlist alone does not describe their whole security boundary. diff --git a/docs/en/platform/admin/connectors.md b/docs/en/platform/admin/connectors.md index 8f10fa6d04..3872dadb73 100644 --- a/docs/en/platform/admin/connectors.md +++ b/docs/en/platform/admin/connectors.md @@ -18,12 +18,12 @@ The connector determines which fields appear. Use the account's actual credentia | Method | Required information | | --- | --- | -| API key | The key issued by the service, such as Tavily or Shopify. | -| Token | A service token, such as a GitHub personal access token or Discord bot token. | +| API key | The key issued by the service, such as Tavily or Shopify. Jev decisions takes an OpenRouter API key. | +| Token | A service token, such as a GitHub personal access token, a Discord bot token, or a GlitchTip API token with `project:read` and `event:read`. | | Username and password | The service's expected pair. This can be a login and app password, or a vendor-specific ID and token. | | OAuth | Authorization in the vendor's browser flow; Tale stores the returned authorization. | -Some connectors also require an instance address. For Confluence, use the Atlassian site origin. For Shopify, use the store's `myshopify.com` origin, not the customer-facing storefront domain. +Some connectors also require an instance address. For Confluence, use the Atlassian site origin. For GlitchTip, use the instance origin, such as `https://app.glitchtip.com`; a self-hosted instance must also be allowed by the deployment's connector host policy. For Shopify, use the store's `myshopify.com` origin, not the customer-facing storefront domain. ## Choose the default diff --git a/docs/en/platform/connectors/overview.md b/docs/en/platform/connectors/overview.md index 346f6a7380..51a792dba1 100644 --- a/docs/en/platform/connectors/overview.md +++ b/docs/en/platform/connectors/overview.md @@ -16,9 +16,11 @@ Use a connector when Tale needs to read or change data in an external service. T | Confluence | Import Confluence Cloud pages into knowledge. | Username and password/token pair. | | Discord | Work with messages and channels. | Token. | | GitHub | Read or manage repositories, issues and pull requests. | Token. | +| GlitchTip | Read a project's issues so the GlitchTip importer can turn them into tasks. | Token and an Instance URL. | | Gmail | Read, send and organize mail. | OAuth. | | Google Drive | Import files into knowledge. | OAuth. | | IMAP / SMTP Mailbox | Read or send mail through a private mail service. | Username and password. | +| Jev decisions | Answer typed questions about a workflow's data with calibrated probabilities, to decide whether to act. | API key (an OpenRouter key). | | Microsoft Outlook | Work with mail, calendars and contacts. | OAuth. | | Shopify | Work with products, customers and orders. | API key. | | Slack | Work with messages and channels. | OAuth. | @@ -35,7 +37,7 @@ Knowledge imports use the [document indexing pipeline](/platform/knowledge/docum Select **Add credential**, search for the service and choose its card. Connectors with existing credentials appear first, but you can add another account for the same service. The form asks for the authentication that connector supports. - + ![The Add credential dialog over the Settings > Connectors table, listing the shipped connectors as cards with their category tags and action counts, a search field at the top, and the already-configured Tavily connector at the head of the list.](/images/platform/connectors-add-credential.webp) @@ -43,7 +45,7 @@ Select **Add credential**, search for the service and choose its card. Connector The **Name** field starts with the connector’s name. When you add several accounts for the same service, change it to one that identifies the purpose, such as `Support inbox` or `Release bot`. Use the external service’s credentials, not a Tale API key. For OAuth, sign in to the provider as the account you want to add and complete its consent. Each connection adds a new credential named after the connector and numbered (`Gmail`, then `Gmail 2`); Slack keeps one per workspace. Rename a new credential so the accounts stay distinguishable. If consent cannot start, an administrator may need to configure its OAuth app first. -Confluence and Shopify require an **Instance URL** per credential. Use the Atlassian site origin or the store’s `myshopify.com` origin, rather than an unrelated page or customer-facing domain. [Connector credentials](/platform/admin/connectors) covers setup fields, reconnection and rotation. +Confluence, GlitchTip and Shopify require an **Instance URL** per credential. Use the Atlassian site origin, the GlitchTip instance origin such as `https://app.glitchtip.com`, or the store’s `myshopify.com` origin, rather than an unrelated page or customer-facing domain. A self-hosted GlitchTip instance must also be allowed by the deployment's connector host policy. [Connector credentials](/platform/admin/connectors) covers setup fields, reconnection and rotation. ## Choose which account an action uses @@ -55,7 +57,7 @@ Disabling a credential retains its configuration but stops use through it. Repla ## Understand reads and writes -Automations use connector actions as workflow nodes. Each action declares an input schema, output and read or write effect. In a test run, connector responses are mocked. In a live run, a write can send a message or change external data and is subject to the organization’s approval policy. +Automations use connector actions as workflow nodes. Each action declares an input schema, output and read or write effect. GlitchTip and Jev decisions only read: the GlitchTip importer writes Tale tasks and never changes the upstream issue, and a Jev decision answers each question with its probabilities and writes nothing. Each decision is billed to the OpenRouter account whose key the credential holds. In a test run, connector responses are mocked. In a live run, a write can send a message or change external data and is subject to the organization’s approval policy. Equipped project agents receive supported read actions through Tale’s connector broker. It keeps those connector credentials outside the sandbox and returns results. The broker refuses connector writes. Direct GitHub tooling or explicit agent secrets use separate paths and must be reviewed separately. diff --git a/docs/fr/develop/connectors.md b/docs/fr/develop/connectors.md index ad31b26397..6cea6c1663 100644 --- a/docs/fr/develop/connectors.md +++ b/docs/fr/develop/connectors.md @@ -34,7 +34,7 @@ auth: | `allowedHosts` en mode per-credential | Suffixes d'hôtes : `atlassian.net` autorise ses sous-domaines | | `configFields` | Valeurs non secrètes propres à l'identifiant : hôte, port, région ou version d'API | -Confluence et Shopify utilisent des origines propres à chaque identifiant. Les secrets n'ont pas leur place dans `configFields` : conserve-les dans les données d'identification chiffrées. Pour les actions JavaScript, `ctx.http` applique la restriction des destinations HTTP. Les backends natifs, comme les protocoles de messagerie, appliquent leurs propres contrôles ; une liste HTTP ne décrit pas toute leur sécurité réseau. +Confluence, GlitchTip et Shopify utilisent des origines propres à chaque identifiant. Les secrets n'ont pas leur place dans `configFields` : conserve-les dans les données d'identification chiffrées. Pour les actions JavaScript, `ctx.http` applique la restriction des destinations HTTP. Les backends natifs, comme les protocoles de messagerie, appliquent leurs propres contrôles ; une liste HTTP ne décrit pas toute leur sécurité réseau. diff --git a/docs/fr/platform/admin/connectors.md b/docs/fr/platform/admin/connectors.md index 0ca7ad37fa..b37dcf7846 100644 --- a/docs/fr/platform/admin/connectors.md +++ b/docs/fr/platform/admin/connectors.md @@ -18,12 +18,12 @@ Le connecteur détermine les champs. Utilise les identifiants du compte externe, | Méthode | Informations nécessaires | | --- | --- | -| Clé API | La clé fournie par le service, par exemple Tavily ou Shopify. | -| Token | Un jeton du service, comme un token d’accès personnel GitHub ou un token de bot Discord. | +| Clé API | La clé fournie par le service, par exemple Tavily ou Shopify. Jev decisions demande une clé API OpenRouter. | +| Token | Un jeton du service, comme un token d’accès personnel GitHub, un token de bot Discord ou un token d’API GlitchTip avec `project:read` et `event:read`. | | Nom d’utilisateur et mot de passe | La paire attendue par le service : connexion et mot de passe d’application, ou identifiant et token propres au fournisseur. | | OAuth | Une autorisation dans le navigateur du fournisseur, ensuite conservée par Tale. | -Certains connecteurs demandent aussi l’adresse de l’instance. Pour Confluence, utilise l’adresse de base du site Atlassian. Pour Shopify, utilise l’adresse `myshopify.com` de la boutique, pas son domaine public destiné aux clients. +Certains connecteurs demandent aussi l’adresse de l’instance. Pour Confluence, utilise l’adresse de base du site Atlassian. Pour GlitchTip, utilise l’origine de l’instance, par exemple `https://app.glitchtip.com` ; une instance auto-hébergée doit aussi être autorisée par la politique d’hôtes des connectors du déploiement. Pour Shopify, utilise l’adresse `myshopify.com` de la boutique, pas son domaine public destiné aux clients. ## Choisir les identifiants par défaut diff --git a/docs/fr/platform/connectors/overview.md b/docs/fr/platform/connectors/overview.md index e744184499..96c0b8c4ae 100644 --- a/docs/fr/platform/connectors/overview.md +++ b/docs/fr/platform/connectors/overview.md @@ -16,9 +16,11 @@ Utilise un connector lorsque Tale doit lire ou modifier les données d’un serv | Confluence | Importer des pages Confluence Cloud dans les connaissances. | Nom d’utilisateur avec mot de passe ou jeton. | | Discord | Travailler avec les messages et canaux. | Jeton. | | GitHub | Lire ou gérer dépôts, issues et pull requests. | Jeton. | +| GlitchTip | Lire les issues d’un projet pour que l’import GlitchTip en fasse des tâches. | Jeton et une URL de l'instance. | | Gmail | Lire, envoyer et organiser le courrier. | OAuth. | | Google Drive | Importer des fichiers dans les connaissances. | OAuth. | | IMAP / SMTP Mailbox | Lire ou envoyer du courrier via un service privé. | Nom d’utilisateur et mot de passe. | +| Jev decisions | Répondre à des questions typées sur les données d’un workflow avec des probabilités calibrées, pour décider s’il faut agir. | Clé API (une clé OpenRouter). | | Microsoft Outlook | Travailler avec courrier, calendriers et contacts. | OAuth. | | Shopify | Travailler avec produits, clients et commandes. | Clé API. | | Slack | Travailler avec les messages et canaux. | OAuth. | @@ -35,7 +37,7 @@ Les imports de connaissances utilisent l’[indexation des documents](/fr/platfo Choisis **Ajouter des identifiants**, recherche le service et ouvre sa carte. Les connectors déjà configurés apparaissent en premier, mais tu peux ajouter un autre compte pour le même service. Le formulaire demande l’authentification prise en charge. - + ![La boîte de dialogue Ajouter des identifiants par-dessus la table de Paramètres > Connectors, qui liste les connecteurs livrés sous forme de cartes avec leurs catégories et leur nombre d’actions, un champ de recherche en haut et le connecteur Tavily déjà configuré en tête de liste.](/images/platform/connectors-add-credential.webp) @@ -43,7 +45,7 @@ Choisis **Ajouter des identifiants**, recherche le service et ouvre sa carte. Le Le champ **Nom** est prérempli avec le nom du connecteur. Si tu ajoutes plusieurs comptes pour le même service, remplace-le par un nom qui indique l’usage, par exemple `Boîte support` ou `Bot de publication`. Utilise ceux du service externe, pas une clé API Tale. Pour OAuth, connecte-toi chez le fournisseur avec le compte à ajouter et termine le consentement. Chaque connexion ajoute de nouveaux identifiants, nommés d’après le connecteur puis numérotés (`Gmail`, puis `Gmail 2`) ; Slack en garde un seul jeu par espace. Renomme les nouveaux identifiants pour distinguer les comptes. Si le parcours ne démarre pas, un administrateur doit peut-être configurer l’app OAuth d’abord. -Confluence et Shopify demandent une **URL de l'instance** pour chaque compte. Utilise l’origine du site Atlassian ou l’adresse `myshopify.com` de la boutique, pas une page quelconque ni le domaine destiné aux clients. [Identifiants des connectors](/fr/platform/admin/connectors) explique les champs, la reconnexion et le renouvellement des secrets. +Confluence, GlitchTip et Shopify demandent une **URL de l'instance** pour chaque compte. Utilise l’origine du site Atlassian, l’origine de l’instance GlitchTip comme `https://app.glitchtip.com` ou l’adresse `myshopify.com` de la boutique, pas une page quelconque ni le domaine destiné aux clients. Une instance GlitchTip auto-hébergée doit aussi être autorisée par la politique d’hôtes des connectors du déploiement. [Identifiants des connectors](/fr/platform/admin/connectors) explique les champs, la reconnexion et le renouvellement des secrets. ## Déterminer le compte utilisé @@ -55,7 +57,7 @@ Désactiver des identifiants conserve leur configuration mais empêche leur usag ## Distinguer lectures et écritures -Les automatisations utilisent les actions comme nœuds de workflow. Chaque action définit son schéma d’entrée, sa sortie et son effet de lecture ou d’écriture. Les essais simulent les réponses. Lors d’une exécution réelle, une écriture peut envoyer un message ou modifier des données externes et suit la politique d’approbation de l’organisation. +Les automatisations utilisent les actions comme nœuds de workflow. Chaque action définit son schéma d’entrée, sa sortie et son effet de lecture ou d’écriture. GlitchTip et Jev decisions ne font que lire : l’import GlitchTip crée des tâches Tale sans jamais modifier l’issue d’origine, et une décision Jev répond à chaque question avec ses probabilités sans rien écrire. Chaque décision est facturée au compte OpenRouter dont la clé figure dans les identifiants. Les essais simulent les réponses. Lors d’une exécution réelle, une écriture peut envoyer un message ou modifier des données externes et suit la politique d’approbation de l’organisation. Les agents de projet dont les connectors sont configurés reçoivent les actions de lecture prises en charge via le broker de Tale. Il conserve ces identifiants hors de la sandbox et renvoie les résultats. Il refuse les écritures des connectors. Les outils GitHub directs et les secrets explicitement accordés suivent d’autres voies et demandent une vérification distincte. diff --git a/services/platform/app/features/settings/connectors/credential-adapter.tsx b/services/platform/app/features/settings/connectors/credential-adapter.tsx index 32e6fa3de6..cffa33cab9 100644 --- a/services/platform/app/features/settings/connectors/credential-adapter.tsx +++ b/services/platform/app/features/settings/connectors/credential-adapter.tsx @@ -93,8 +93,8 @@ export function toConnectorVendor(summary: ConnectorSummary): ConnectorVendor { key: summary.slug, displayName: summary.displayName, iconUrl: summary.iconUrl, - // Confluence and Shopify name their own instance per credential; the - // others talk to one fixed vendor host. + // Confluence, GlitchTip and Shopify name their own instance per + // credential; the others talk to one fixed vendor host. needsEndpoint: summary.endpointMode === 'per-credential', summary, }; diff --git a/services/platform/app/features/settings/connectors/labels.ts b/services/platform/app/features/settings/connectors/labels.ts index 5fd8d866ea..e3165b79a7 100644 --- a/services/platform/app/features/settings/connectors/labels.ts +++ b/services/platform/app/features/settings/connectors/labels.ts @@ -53,6 +53,8 @@ export function endpointHelp(t: Translator, connectorSlug: string): string { return t('connectors.dialog.endpointHelpConfluence'); case 'shopify': return t('connectors.dialog.endpointHelpShopify'); + case 'glitchtip': + return t('connectors.dialog.endpointHelpGlitchtip'); default: return t('connectors.dialog.endpointHelpGeneric'); } @@ -66,6 +68,8 @@ export function endpointPlaceholder(connectorSlug: string): string { return 'https://your-site.atlassian.net'; case 'shopify': return 'https://your-store.myshopify.com'; + case 'glitchtip': + return 'https://app.glitchtip.com'; default: return 'https://api.example.com'; } diff --git a/services/platform/backend/core/connector_credentials/catalog_docs.test.ts b/services/platform/backend/core/connector_credentials/catalog_docs.test.ts new file mode 100644 index 0000000000..63adf64802 --- /dev/null +++ b/services/platform/backend/core/connector_credentials/catalog_docs.test.ts @@ -0,0 +1,148 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { describe, expect, it } from 'vitest'; +import { z } from 'zod'; + +import deMessages from '../../../messages/de.yml'; +import enMessages from '../../../messages/en.yml'; +import frMessages from '../../../messages/fr.yml'; +import { listConnectorSummaries } from './connector_catalog'; + +/** + * #3716: the Add credential picker offered fifteen connectors while the user + * docs — the behaviour oracle a manual round judges against — and the manual + * suite described thirteen. GlitchTip and Jev decisions appeared nowhere, and + * the Instance URL guidance named only Confluence and Shopify. This holds the + * pages to the listing the picker serves (`listConnectorSummaries`): + * + * - each locale's connector table names every connector the picker offers, + * by the name it shows, and nothing it does not; + * - every connector whose credentials name their own instance is named + * where the overview explains the **Instance URL** and where the admin + * guide explains the instance address; + * - the manual suite counts and lists the same picker. + * + * The docs pages are outside this workspace: `services/platform/turbo.json` + * hashes them for this suite. + */ + +const REPO_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../../..', +); + +const catalogSchema = z.object({ + settings: z.object({ + connectors: z.object({ + dialog: z.object({ endpointUrl: z.string() }), + }), + }), +}); + +const LOCALES = { + en: { + messages: catalogSchema.parse(enMessages), + // Where the admin guide explains the instance address. + instanceAddress: 'Some connectors also require an instance address.', + }, + de: { + messages: catalogSchema.parse(deMessages), + instanceAddress: + 'Manche Connectors benötigen zusätzlich die Adresse der Instanz.', + }, + fr: { + messages: catalogSchema.parse(frMessages), + instanceAddress: + 'Certains connecteurs demandent aussi l’adresse de l’instance.', + }, +} as const; + +const read = (repoPath: string) => + readFileSync(path.join(REPO_ROOT, repoPath), 'utf8'); + +/** The first cell of each row of the page's first table. */ +function tableNames(page: string): string[] { + const lines = page.split('\n'); + const separator = lines.findIndex((line) => /^\|\s*-{3,}/.test(line)); + if (separator < 1) return []; + const names: string[] = []; + for (const line of lines.slice(separator + 1)) { + if (!line.startsWith('|')) break; + names.push(line.split('|')[1]?.trim() ?? ''); + } + return names; +} + +/** The paragraph (a line of the page) that contains `needle`. */ +const paragraphWith = (page: string, needle: string) => + page.split('\n').find((line) => line.includes(needle)) ?? ''; + +const shipped = listConnectorSummaries(); +const byName = [...shipped].sort((a, b) => a.slug.localeCompare(b.slug)); +const perCredential = shipped.filter( + (connector) => connector.endpointMode === 'per-credential', +); + +describe('the connector docs describe the catalog the picker offers', () => { + it('lists a picker with GlitchTip and Jev decisions in it', () => { + // A catalog that lost its files would pass the checks below vacuously. + expect(shipped.map((connector) => connector.displayName)).toEqual( + expect.arrayContaining(['GlitchTip', 'Jev decisions', 'Confluence']), + ); + }); + + for (const [locale, { messages, instanceAddress }] of Object.entries( + LOCALES, + )) { + it(`docs/${locale}/platform/connectors/overview.md tables every offered connector`, () => { + const page = read(`docs/${locale}/platform/connectors/overview.md`); + expect([...tableNames(page)].sort()).toEqual( + shipped.map((connector) => connector.displayName).sort(), + ); + }); + + it(`docs/${locale} names every per-credential connector beside its instance guidance`, () => { + const label = messages.settings.connectors.dialog.endpointUrl; + const overview = paragraphWith( + read(`docs/${locale}/platform/connectors/overview.md`), + `**${label}**`, + ); + const admin = paragraphWith( + read(`docs/${locale}/platform/admin/connectors.md`), + instanceAddress, + ); + for (const connector of perCredential) { + expect({ page: 'overview', names: overview }).toEqual({ + page: 'overview', + names: expect.stringContaining(connector.displayName), + }); + expect({ page: 'admin', names: admin }).toEqual({ + page: 'admin', + names: expect.stringContaining(connector.displayName), + }); + } + }); + } + + it('the manual connectors suite counts and names the same picker', () => { + const suite = readFileSync( + path.join( + REPO_ROOT, + 'services/platform/tests/manual/suites/connectors.md', + ), + 'utf8', + ); + const offers = /picker offers \*\*(\d+)\*\* vendors:\s*([^.]+)\./.exec( + suite, + ); + expect(Number(offers?.[1])).toBe(shipped.length); + const listed = (offers?.[2] ?? '') + .replace(/\([^)]*\)/g, '') + .split(',') + .map((slug) => slug.trim()); + expect(listed).toEqual(byName.map((connector) => connector.slug)); + expect(suite).toContain(`${shipped.length} vendors in one list`); + }); +}); diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index 83df774816..6a4e6ec951 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -5809,6 +5809,10 @@ settings: endpointHelpShopify: Die myshopify.com-Adresse deines Shops — die Admin-Adresse, nicht die Storefront-Domain. + endpointHelpGlitchtip: + Die Adresse deiner GlitchTip-Instanz, etwa https://app.glitchtip.com. + Eine selbst betriebene Instanz funktioniert, sobald die Bereitstellung + ihren Host erlaubt. endpointHelpGeneric: Der https-Ursprung der Instanz, zu der dieser Eintrag gehört. enterpriseSso: connected: Die Anmeldung ist aktiviert. diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index 3f452aeab9..42370b986a 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -5982,6 +5982,9 @@ settings: endpointHelpShopify: Your store's myshopify.com origin — the admin address, not the storefront domain. + endpointHelpGlitchtip: + Your GlitchTip instance origin, such as https://app.glitchtip.com. A + self-hosted instance works once the deployment allows its host. endpointHelpGeneric: The https origin of the instance this credential belongs to. enterpriseSso: connected: Sign-in is enabled. diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index ae86607a35..47d29a07b5 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -5898,6 +5898,10 @@ settings: endpointHelpShopify: L'adresse myshopify.com de ta boutique — l'adresse d'administration, pas le domaine de la vitrine. + endpointHelpGlitchtip: + L'adresse de ton instance GlitchTip, par exemple + https://app.glitchtip.com. Une instance auto-hébergée fonctionne dès + que le déploiement autorise son hôte. endpointHelpGeneric: L'origine https de l'instance à laquelle appartiennent ces identifiants. enterpriseSso: connected: La connexion est activée. diff --git a/services/platform/tests/guards/turbo-inputs.guard.test.ts b/services/platform/tests/guards/turbo-inputs.guard.test.ts index 76288d40dd..cad4765801 100644 --- a/services/platform/tests/guards/turbo-inputs.guard.test.ts +++ b/services/platform/tests/guards/turbo-inputs.guard.test.ts @@ -70,6 +70,16 @@ const OUTSIDE_READS = [ readers: 'the shipped connector, model, provider, harness and PII catalog suites', }, + { + // The connector guides, which table the catalog the picker offers and + // name the connectors whose credentials carry an instance URL. + path: 'docs/*/platform/admin/connectors.md', + readers: 'backend/core/connector_credentials/catalog_docs.test.ts', + }, + { + path: 'docs/*/platform/connectors/overview.md', + readers: 'backend/core/connector_credentials/catalog_docs.test.ts', + }, { // The user docs' task page, which states the task caps in each locale. path: 'docs/*/platform/projects/tasks.md', diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index d5e6dbbf93..c5d7cf5f31 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -253,6 +253,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [connectors](../suites/connectors.md) | `CONN-F1`, `CONN-F3`–`CONN-F10`, `CONN-F5a`, `CONN-F13`, `CONN-F14`, `CONN-F22`, `CONN-B1`, `CONN-B4`, `CONN-B5` | 🔶 component | `app/features/settings/connectors/components/connectors-settings.test.tsx` (rows, add flow and its suggested name, row actions, what deleting the default says, denial) | | [connectors](../suites/connectors.md) | `CONN-F22` (the backend half, #3713): one rule decides the default a delete hands on — the oldest active credential of the connector, never a disabled or needs-reauth one, ties by id; the listing names it on the default's row and the delete applies it under the pair lock | ✅ unit | `backend/domains/connector_credentials/service.default-successor.test.ts` | | [connectors](../suites/connectors.md) | `CONN-F1`–`CONN-F3` (empty state, picker, search) | ✅ automated | `settings.spec.ts` ("connectors: empty credentials surface and the add-catalog picker") | +| [connectors](../suites/connectors.md) | `CONN-F3`, `CONN-F6` (what the docs and this suite say the picker ships, #3716): each locale's connector overview tables exactly the connectors the picker lists, by the names it shows; every per-credential connector (Confluence, GlitchTip, Shopify) is named beside the overview's **Instance URL** and the admin guide's instance address; this suite's count and slug list match the picker | ✅ unit | `backend/core/connector_credentials/catalog_docs.test.ts` | | [connectors](../suites/connectors.md) | `CONN-F7`, `CONN-B1` (required-config gating) | 🔶 component | `app/features/settings/connectors/config-fields.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F17` | 🔶 component | `app/features/settings/connectors/components/mcp-endpoint-section.test.tsx` | | [connectors](../suites/connectors.md) | `CONN-F11`, `CONN-F12`, `CONN-F18`, `CONN-B2`, `CONN-B3`, `CONN-B6` | ⛔ manual-only | — (persistence reloads, live consent round trip, redirects, server refusals) | diff --git a/services/platform/tests/manual/suites/connectors.md b/services/platform/tests/manual/suites/connectors.md index 7f2be643c6..5c109216f1 100644 --- a/services/platform/tests/manual/suites/connectors.md +++ b/services/platform/tests/manual/suites/connectors.md @@ -35,12 +35,12 @@ facet** seeded FROM the URL, not bound to it: the facet is multi-select, so the moment the operator touches the facet (or clears filters) the param is removed from the URL and the facet takes over. -- The catalog ships 17 connector definitions +- The catalog ships 19 connector definitions (`configs/platform/system/connectors/`), but the four **platform-auth** connectors (conversation, document, sandbox, task) never reach the client — - the listing drops them, so the add-dialog picker offers **13** vendors: - confluence, discord, github, gmail, google-drive, imap-smtp, outlook, - shopify, slack, tavily, teams, twilio, webdav. + the listing drops them, so the add-dialog picker offers **15** vendors: + confluence, discord, github, glitchtip, gmail, google-drive, imap-smtp, jev + (**Jev decisions**), outlook, shopify, slack, tavily, teams, twilio, webdav. - Both legacy MCP routes redirect in **one hop** to `…/settings/connectors`. The MCP **endpoint** section (the platform's own inbound MCP surface) renders on `/dashboard/{org}/settings/api/mcp`. @@ -100,7 +100,7 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability the way in — never a bare empty grid. - [ ] `CONN-F3` · **Catalog picker (step 1)** — **Add credential** → A dialog titled **Add credential** (`settings.credentials.catalog.title`) with its - own search (`settings.connectors.searchPlaceholder`). 13 vendors in one list + own search (`settings.connectors.searchPlaceholder`). 15 vendors in one list (each row: icon, name, tags + action count meta `settings.connectors.card.actionCount`); configured vendors carry a **Configured** badge (`settings.credentials.catalog.configured`). The @@ -130,7 +130,9 @@ Sign in as an owner/admin — the page requires the `developerSettings` ability (`settings.connectors.dialog.endpointHelpConfluence`) and placeholder `https://your-site.atlassian.net`. Submit stays disabled until it is filled. Shopify behaves the same with its store origin - (`settings.connectors.dialog.endpointHelpShopify`). + (`settings.connectors.dialog.endpointHelpShopify`), and GlitchTip with its + instance origin (`settings.connectors.dialog.endpointHelpGlitchtip`, + placeholder `https://app.glitchtip.com`) beside a masked **Token**. - [ ] `CONN-F7` · **Mailbox connector config** — Picker → **IMAP / SMTP Mailbox** → Beyond username/password, the connector's declared config fields render: **IMAP server** (required), **IMAP port** (placeholder `993`), diff --git a/services/platform/turbo.json b/services/platform/turbo.json index dbd8682421..e292132d37 100644 --- a/services/platform/turbo.json +++ b/services/platform/turbo.json @@ -10,6 +10,8 @@ "$TURBO_ROOT$/compose.yml", "$TURBO_ROOT$/compose.dev.yml", "$TURBO_ROOT$/configs/platform/**", + "$TURBO_ROOT$/docs/*/platform/admin/connectors.md", + "$TURBO_ROOT$/docs/*/platform/connectors/overview.md", "$TURBO_ROOT$/docs/*/platform/projects/tasks.md", "$TURBO_ROOT$/knip.config.ts", "$TURBO_ROOT$/packages/ui/src/**", From d1fdc59b8b5c7ae93907ab38c7d6350e92e713d8 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:24:00 +0000 Subject: [PATCH 6/9] test(manual): cover row-menu focus return CONN-A4 and A11Y-A19 judge what #3715's fix owes a keyboard user: a dialog opened from a row's actions menu, closed by Escape or Cancel, returns focus to that row's menu button on every table, never . The automation register names the unit, real-browser and component suites that hold the hook, and pins.md records why the hook, not each call site, finds the button. The suite table counts the five boxes this branch adds (CONN-F21, CONN-F22, CONN-B11, CONN-A4, A11Y-A19). --- services/platform/tests/manual/readme.md | 6 +++--- services/platform/tests/manual/reference/automation.md | 1 + services/platform/tests/manual/reference/pins.md | 1 + services/platform/tests/manual/suites/accessibility.md | 9 ++++++++- services/platform/tests/manual/suites/connectors.md | 7 ++++++- 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/services/platform/tests/manual/readme.md b/services/platform/tests/manual/readme.md index 9800f916c6..f5efc3e787 100644 --- a/services/platform/tests/manual/readme.md +++ b/services/platform/tests/manual/readme.md @@ -29,18 +29,18 @@ tale-project standard ([`AGENTS.md`](../../../../AGENTS.md) "Manual tests"), and ## The suites -945 boxes across 21 suites. Every suite declares the ID prefix its +950 boxes across 21 suites. Every suite declares the ID prefix its boxes carry, in its header blockquote; a box ID is unique across this whole directory and greppable as one token. | Suite | Prefix | Area | Boxes | |---|---|---|---| -| [accessibility](suites/accessibility.md) | `A11Y-` | cross-cutting WCAG 2.1 AA sweep | 26 | +| [accessibility](suites/accessibility.md) | `A11Y-` | cross-cutting WCAG 2.1 AA sweep | 27 | | [approvals](suites/approvals.md) | `APV-` | human-in-the-loop: run approval/ask cards, task review gate, DSAR dual-approval | 20 | | [auth](suites/auth.md) | `AUTH-` | login, SSO, 2FA, passkeys, password policy, first-run setup, RBAC | 50 | | [automations](suites/automations.md) | `AUTO-` | draft→deploy→version automations: list, builder, upload, trigger, runs, bindings | 75 | | [chat](suites/chat.md) | `CHAT-` | messages, attachments, tools + approvals, arena, share, reasoning, the chat header and rows | 90 | -| [connectors](suites/connectors.md) | `CONN-` | credential table + catalog picker; mailbox (IMAP/SMTP), OAuth, MCP endpoint | 36 | +| [connectors](suites/connectors.md) | `CONN-` | credential table + catalog picker; mailbox (IMAP/SMTP), OAuth, MCP endpoint | 40 | | [conversations](suites/conversations.md) | `CONV-` | the shared Inbox: statuses, priority, search, mailbox sync | 56 | | [data-residency](suites/data-residency.md) | `DATA-` | BYO knowledge database + object storage, embedding settings | 26 | | [governance](suites/governance.md) | `GOV-` | content models, guardrails, policies, legal hold, DSAR, logs, trash | 58 | diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index c5d7cf5f31..cb88e56568 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -252,6 +252,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [chat](../suites/chat.md) | `CHAT-F43` — an arena round shows in the column as its own optimistic send the moment it is sent, the send-snap glides it to the column's top with the reply's room beneath it, and the real rows take the bubble over in place (one copy, same node) | 🔶 browser | `app/features/chat/components/arena/arena-column.browser.test.tsx` (real Chromium geometry, the transcript read served as a subscription); the fan-out against two live models and the verdict gating stay manual | | [connectors](../suites/connectors.md) | `CONN-F1`, `CONN-F3`–`CONN-F10`, `CONN-F5a`, `CONN-F13`, `CONN-F14`, `CONN-F22`, `CONN-B1`, `CONN-B4`, `CONN-B5` | 🔶 component | `app/features/settings/connectors/components/connectors-settings.test.tsx` (rows, add flow and its suggested name, row actions, what deleting the default says, denial) | | [connectors](../suites/connectors.md) | `CONN-F22` (the backend half, #3713): one rule decides the default a delete hands on — the oldest active credential of the connector, never a disabled or needs-reauth one, ties by id; the listing names it on the default's row and the delete applies it under the pair lock | ✅ unit | `backend/domains/connector_credentials/service.default-successor.test.ts` | +| [connectors](../suites/connectors.md) / [accessibility](../suites/accessibility.md) | `CONN-A4`, `A11Y-A19` (#3715): a dialog opened from a menu item returns focus to the menu's button without a restore ref — the menu names it (`aria-labelledby` / `aria-controls` + `aria-haspopup`), a submenu climbs to the outermost button, a caller's `restoreFocusRef` wins, a label that opens nothing is never taken; in real Chromium for Escape and **Cancel** on an `EntityRowActions` row with an edit and a delete dialog; on the connectors page for Edit credential, Replace token and Delete | 🔶 unit + browser + component | `packages/ui/src/hooks/use-restore-focus.test.ts`, `packages/ui/src/components/dialog/dialog.browser.test.tsx`, `app/features/settings/connectors/components/connectors-settings.test.tsx` — every other table's row menu stays a manual keyboard round | | [connectors](../suites/connectors.md) | `CONN-F1`–`CONN-F3` (empty state, picker, search) | ✅ automated | `settings.spec.ts` ("connectors: empty credentials surface and the add-catalog picker") | | [connectors](../suites/connectors.md) | `CONN-F3`, `CONN-F6` (what the docs and this suite say the picker ships, #3716): each locale's connector overview tables exactly the connectors the picker lists, by the names it shows; every per-credential connector (Confluence, GlitchTip, Shopify) is named beside the overview's **Instance URL** and the admin guide's instance address; this suite's count and slug list match the picker | ✅ unit | `backend/core/connector_credentials/catalog_docs.test.ts` | | [connectors](../suites/connectors.md) | `CONN-F7`, `CONN-B1` (required-config gating) | 🔶 component | `app/features/settings/connectors/config-fields.test.tsx` | diff --git a/services/platform/tests/manual/reference/pins.md b/services/platform/tests/manual/reference/pins.md index 9cd5d261f2..c704f9c088 100644 --- a/services/platform/tests/manual/reference/pins.md +++ b/services/platform/tests/manual/reference/pins.md @@ -36,6 +36,7 @@ time you are tempted to shorten one. | `NAV-F11` | The public docs moved to a separate origin. `app/components/user-button.test.tsx` pins the shared canonical constant and safe new-tab attributes; the box no longer expects the old marketing-site subpath. | | `KNOW-F16` | The hub folder listing decorated only `active` sync configs, so a config in `error` lost its "(synced)" label and read as a plain folder — a dead grant froze the mirror with nothing on screen and nobody told (2026-09-15). The listing now decorates errored configs too, the Source cell carries the health badge, and the owner gets one bell + email per failure episode; `sync-health.test.ts` and `service.failure-notify.test.ts` hold the episode rule, the itest lane `onedrive dead grant…` holds it end to end. The badge must also disappear WITHOUT a reload: the engine now emits `folder`/`document` hints, which it never did before. | | `KNOW-F19` | The Source cell spelled its source out, so "OneDrive (synchronisiert)" wrapped onto two lines at the column's minimum width and ran into RAG status; Google Drive alone showed a bare mark that never said whether it synced, and the preview sidebar kept its own three-provider map that printed `google_drive` for the rest (2026-09-15). The cell is now the vendor mark plus a synced / not-synced / failure glyph, from one map the preview reads too, with the words on hover, on focus and as the accessible name; `use-document-source.test.tsx` and `use-documents-table-config.test.tsx` hold the names and glyphs, while the fit, the preview sidebar and the dark theme stay manual. | +| `CONN-A4` / `A11Y-A19` | A dialog opened from a row's actions menu dropped focus to `` on close on ten tables (#3715): the menu item that opened it is gone by then, and `useRestoreFocus` only returned to a `restoreFocusRef` the caller passed, which most row menus never did, and the wired ones missed dialogs (Documents' Delete, Move, Team tags). The hook now reads the button the item's menu names (WAI-ARIA menu button: `aria-labelledby` / `aria-controls` + `aria-haspopup`) when the dialog opens and returns there, so no call site can forget it; `restoreFocusRef` stays for openers that move or unmount. A confirmed delete that removes the row, and with it the button, is #3791. | | `CONN-F14` / `CONN-F22` | Deleting a connector's default never left it without one while an active credential remained: the server hands the default to the oldest active credential (a 0.4 continuity rule — an unnamed call keeps working), and skips disabled and needs-reauth rows. The shared delete dialog said the opposite, "leaves no default", which is true only for AI providers, and CONN-F14 reached its no-default state by deleting the default (#3713). The rule is now one function (`defaultSuccessor` in `backend/domains/connector_credentials/service.ts`): the delete applies it and the listing names its answer on the default's row, which the confirm reads. `service.default-successor.test.ts` and `connectors-settings.test.tsx` hold both halves; CONN-F14 now reaches no default by disabling it. | | `RESP-F2` / `TASK-F25` | The mobile More sheet (retired with the four-tab bar) was a `Sheet` opened from state — no Radix trigger — and `Sheet` never ran `useRestoreFocus`, so Escape dropped the document on ``. The primitive now restores the opener (`sheet.test.tsx`). The task page's phone details sheet is opened from state the same way, so `TASK-F25` now judges the **Show details** button regaining focus. | | `CONV-F4` / `CONV-F12` / `CONV-F16` / `CONV-F20` / `CONV-F25` | Desktop and phone keep the facets in different places on purpose: the Home panel's Inbox view stands beside every Home route (a chat, a task, a project), so its facets cannot ride the inbox route's URL — it remembers them per device instead; the phone's list is the inbox page itself and keeps `?read=` / `?assignee=` / `?channel=` / `?mailbox=`. Both run on `useInboxList`, so the facet semantics must not differ. The team and channel chips are drawn by the phone list's rows only — the panel's rows share one anatomy with chats and tasks — which is why `CONV-F12` / `CONV-F19` / `CONV-F21` judge them at 390 px. | diff --git a/services/platform/tests/manual/suites/accessibility.md b/services/platform/tests/manual/suites/accessibility.md index 0fb99fcab5..7cb8aca28f 100644 --- a/services/platform/tests/manual/suites/accessibility.md +++ b/services/platform/tests/manual/suites/accessibility.md @@ -1,6 +1,6 @@ # Accessibility (cross-cutting) -> **Prefix** `A11Y-` · **Reset** none · **Cost** 26 boxes +> **Prefix** `A11Y-` · **Reset** none · **Cost** 27 boxes A WCAG 2.1 **Level AA** sweep across the whole app. Tale's standard (root [`AGENTS.md`](../../../AGENTS.md) → Accessibility) is mandatory, not @@ -65,6 +65,13 @@ component-level axe coverage comes from `vitest-axe` via - [ ] `A11Y-A5` · **Focus return** — Open a dialog (create/delete); press `Esc` → Focus is trapped inside the open dialog; on close it returns to the triggering control (`document.activeElement` === the trigger) +- [ ] `A11Y-A19` · **Focus return from a row menu** — Keyboard only, on each + table whose rows carry an actions menu (Settings → Connectors, AI providers, + Members, Teams, API keys; Projects; Documents): open a dialog from a row + menu item, then Escape or **Cancel** → Focus returns to that row's menu + button (`document.activeElement` === it), never `` — the menu item + that opened the dialog is gone by then. A confirmed delete that removes the + row is a separate case. - [ ] `A11Y-A6` · **Icon buttons** — Query all `