Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/34070-docs-conflict-candidates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/console': patch
'@object-ui/i18n': patch
---

feat(console): the docs reader lists the candidate packages when a doc name two packages ship is refused

Clause-②: yes (widening) — widened: where a doc read that names no package answers `409 RESOURCE_CONFLICT` naming its holders (`details.candidates`), the Console docs reader (`/docs/BOOK/NAME`, reached from the flat `/docs/NAME` permalink) lists those packages, each linking to that package's address `/apps/PACKAGE/docs/NAME`, where it showed "Failed to load documentation"; a flat permalink under a package container (`/apps/PACKAGE/docs/NAME`) of a name that package ships opens the doc in that package's own book; the `@object-ui/i18n` keys `help.docConflictTitle`, `help.docConflictDescription` and `help.docConflictCandidates`, in all 11 shipped locales (no key renamed or removed). A doc one package ships, and every other failure, render as before.
Metadata-protocol: none

Two enabled packages may ship one doc name. A read of it that names no package is refused with `409 RESOURCE_CONFLICT` and the holders as `details.candidates`; nothing picks one for the reader. The docs reader now shows a "Choose a package" list in place of the generic load error: each entry is the package as the portal names it (its book) with the package id beside it, and opens that package's copy, read with the package named.
82 changes: 78 additions & 4 deletions ui/apps/console/src/pages/DocPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
*/

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Navigate, useHref, useLocation, useNavigate, useParams } from 'react-router-dom';
import { AlertCircle, ChevronDown, FileQuestion, Loader2, Menu } from 'lucide-react';
import { Link, Navigate, useHref, useLocation, useNavigate, useParams } from 'react-router-dom';
import { AlertCircle, ChevronDown, FileQuestion, Layers, Loader2, Menu } from 'lucide-react';
import { useAdapter } from '@object-ui/app-shell';
import { MarkdownRenderer, extractToc } from '@object-ui/plugin-markdown';
import { useObjectTranslation } from '@object-ui/i18n';
Expand All @@ -17,7 +17,7 @@ import { DocShell } from './DocShell';
import { BookSidebar } from './BookSidebar';
import { DocRefusal } from './BookPage';
import { useBookData } from './use-book-data';
import { resolveBookTree, bookSlug, bookNamedBy, labelUncategorized, type ResolvedBook } from './book-nav';
import { resolveBookTree, bookSlug, bookNamedBy, homeBook, labelUncategorized, type ResolvedBook } from './book-nav';

interface DocItem {
name: string;
Expand All @@ -32,6 +32,24 @@ function scrollHeadingIntoView(id: string): boolean {
return target !== null;
}

/**
* The packages a `409 RESOURCE_CONFLICT` doc read names as holders of the
* name: `@objectstack/client` carries the refusal's `details.candidates` on the
* rejection (`{ kind: 'package', packageId }` per package). Null for any other
* failure, and for a refusal that names no package, so those keep their state.
*/
function conflictCandidates(err: unknown): string[] | null {
const e = err as { httpStatus?: unknown; code?: unknown; details?: { candidates?: unknown } } | null;
if (e?.httpStatus !== 409 || e.code !== 'RESOURCE_CONFLICT') return null;
const candidates = e.details?.candidates;
if (!Array.isArray(candidates)) return null;
const packageIds = candidates
.filter((c): c is { kind: 'package'; packageId: string } =>
c?.kind === 'package' && typeof c.packageId === 'string' && c.packageId !== '')
.map((c) => c.packageId);
return packageIds.length > 0 ? packageIds : null;
}

/**
* `/docs/:name` — render one package-doc metadata item (ADR-0046).
*
Expand All @@ -48,6 +66,12 @@ function scrollHeadingIntoView(id: string): boolean {
* A doc the member may not read is a different answer: the server refuses it
* with 401 / 403 (ADR-0046 §6.7), and the page shows that refusal, with the
* server's reason, rather than "not found" or a load failure (objectui#10188).
*
* A name two or more enabled packages ship is refused by a read that names no
* package, `409 RESOURCE_CONFLICT` with the holders as candidates (ADR-0150
* D3). Nothing picks one: the page lists the candidates, each opening that
* package's copy at its package address `/apps/<packageId>/docs/<name>`, where
* the read names the package.
*/
export default function DocPage() {
// Route is `/docs/:slug/:name` (`:slug` = book, `:name` = doc). `appName` is
Expand All @@ -72,8 +96,9 @@ export default function DocPage() {
const adapter = useAdapter();
const { t } = useObjectTranslation();
const [doc, setDoc] = useState<DocItem | null>(null);
const [state, setState] = useState<'loading' | 'ready' | 'missing' | 'refused' | 'error'>('loading');
const [state, setState] = useState<'loading' | 'ready' | 'missing' | 'refused' | 'conflict' | 'error'>('loading');
const [errorMessage, setErrorMessage] = useState<string>('');
const [candidates, setCandidates] = useState<string[]>([]);

useEffect(() => {
let cancelled = false;
Expand Down Expand Up @@ -104,6 +129,14 @@ export default function DocPage() {
setState('refused');
return;
}
// Two or more packages ship this name and the read named none of
// them: the server names the holders, and the reader picks one.
const holders = conflictCandidates(err);
if (holders) {
setCandidates(holders);
setState('conflict');
return;
}
// The metadata API answers 404 for unknown names — that is the
// ADR-mandated soft-degrade path, not an error.
if (status === 404 || /not found/i.test(err?.message ?? '')) {
Expand Down Expand Up @@ -249,6 +282,47 @@ export default function DocPage() {
return <DocRefusal name={name} message={errorMessage} />;
}

if (state === 'conflict') {
return (
<DocShell breadcrumb={name}>
<div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center">
<Layers className="h-10 w-10 text-muted-foreground" />
<h1 className="text-lg font-semibold">
{t('help.docConflictTitle', { defaultValue: 'Choose a package' })}
</h1>
<p className="text-sm text-muted-foreground">
{t('help.docConflictDescription', {
defaultValue: 'More than one installed package provides a document named {{name}}. Open the one you want to read.',
name,
})}
</p>
<ul
aria-label={t('help.docConflictCandidates', { defaultValue: 'Packages that provide this document' })}
className="mt-2 flex w-full max-w-md flex-col gap-2 text-left"
>
{candidates.map((packageId) => {
// The package as the portal names it: its home book for this doc.
const label = (name ? homeBook(name, books, allDocs, packageId)?.label : undefined) ?? packageId;
return (
<li key={packageId}>
<Link
to={{ pathname: `/apps/${packageId}/docs/${name}`, hash }}
className="flex flex-col rounded-md border px-4 py-3 hover:bg-muted/50"
>
<span className="text-sm font-medium">{label}</span>
{label !== packageId ? (
<span className="text-xs text-muted-foreground">{packageId}</span>
) : null}
</Link>
</li>
);
})}
</ul>
</div>
</DocShell>
);
}

if (state === 'error') {
return (
<DocShell breadcrumb={name}>
Expand Down
8 changes: 6 additions & 2 deletions ui/apps/console/src/pages/DocsSlug.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { useAdapter } from '@object-ui/app-shell';
import { DocShell } from './DocShell';
import BookPage, { DocRefusal } from './BookPage';
import { useBookData } from './use-book-data';
import { bookNamedBy, bookSlug, homeBook } from './book-nav';
import { bookNamedBy, bookSlug, homeBook, pkgOf } from './book-nav';

/** What the server says about one segment the member's lists do not answer. */
type SegmentAnswer = { slug: string; refusal: string | null };
Expand Down Expand Up @@ -114,7 +114,11 @@ export default function DocsSlug() {

// Otherwise a flat doc permalink → redirect to its canonical in-book URL.
const base = appName ? `/apps/${appName}/docs` : '/docs';
const hb = slug ? homeBook(slug, books, docs) : null;
// Under a package container that ships this name, its own copy decides the
// home book: two packages may ship one doc name, and the doc read there names
// the container's package (objectstack#34070), so the book must be its too.
const ownCopy = !!appName && docs.some((d) => d.name === slug && pkgOf(d) === appName);
const hb = slug ? homeBook(slug, books, docs, ownCopy ? appName : undefined) : null;
if (hb && slug && docs.some((d) => d.name === slug)) {
return <Navigate to={{ pathname: `${base}/${bookSlug(hb)}/${slug}`, hash }} replace />;
}
Expand Down
8 changes: 6 additions & 2 deletions ui/apps/console/src/pages/book-nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,10 +453,14 @@ function humanizePackageId(pkg: string): string {
* navigation entry opens the page in its book's context (objectui#10188, the
* card's addendum). Only a doc no book of its package claims falls back to the
* package's first book in display order, as before.
*
* Two packages may ship one doc name (objectstack#34070). `packageId` then
* names whose copy is meant, so the home book is that package's; without it
* the package is the first listed doc of the name's, as before.
*/
export function homeBook(docName: string, portalBooks: Book[], docs: ResolverDoc[]): Book | null {
export function homeBook(docName: string, portalBooks: Book[], docs: ResolverDoc[], packageId?: string): Book | null {
const doc = docs.find((d) => d.name === docName);
const pkg = doc ? pkgOf(doc) : namePrefix(docName);
const pkg = packageId ?? (doc ? pkgOf(doc) : namePrefix(docName));
const ownBooks = sortBooks(portalBooks).filter((b) => pkgOfBook(b) === pkg);
return findBookContainingDoc(ownBooks, docs, docName)?.book ?? ownBooks[0] ?? null;
}
Expand Down
136 changes: 130 additions & 6 deletions ui/apps/console/src/pages/docs-portal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';

// ── Sample metadata the mocked adapter serves (two packages, no books) ──────
Expand Down Expand Up @@ -72,17 +72,48 @@ const { ADAPTER, WORLD } = vi.hoisted(() => {
acme_intro: 'ACME BODY',
ops_setup: 'OPS BODY',
};
const WORLD = { authored: false };
// objectstack#34070 — a third world, switched on only by the "two packages
// ship one doc name" block: `shared_guide` is shipped by alpha AND beta (beta
// listed first), and a read of it that names no package is refused the way
// the server refuses it, `409 RESOURCE_CONFLICT` naming both holders.
const CONFLICT_DOCS = [
{ name: 'shared_guide', label: 'Shared Guide', _packageId: 'com.example.beta' },
{ name: 'beta_start', label: 'Beta Start', _packageId: 'com.example.beta' },
{ name: 'shared_guide', label: 'Shared Guide', _packageId: 'com.example.alpha' },
{ name: 'alpha_welcome', label: 'Alpha Welcome', _packageId: 'com.example.alpha' },
];
const CONFLICT_CONTENT: Record<string, Record<string, string>> = {
'com.example.alpha': { shared_guide: 'ALPHA SHARED BODY', alpha_welcome: 'ALPHA BODY' },
'com.example.beta': { shared_guide: 'BETA SHARED BODY', beta_start: 'BETA BODY' },
};
/** A rejection shaped like `@objectstack/client`'s on a non-2xx response. */
const failure = (httpStatus: number, code: string, message: string, details?: unknown) =>
Object.assign(new Error(message), { httpStatus, code, details });
const conflictRead = (name: string, packageId: string | undefined) => {
if (name === 'broken_doc') throw failure(500, 'INTERNAL_ERROR', 'The metadata service is unavailable');
const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p]);
if (packageId) return { item: { name, content: CONFLICT_CONTENT[packageId]?.[name] } };
if (holders.length > 1) {
throw failure(409, 'RESOURCE_CONFLICT', `doc "${name}" is held by ${holders.length} packages`, {
candidates: holders.map((p) => ({ kind: 'package', packageId: p })),
});
}
return { item: { name, content: holders.length ? CONFLICT_CONTENT[holders[0]][name] : undefined } };
};
const WORLD = { authored: false, conflict: false };
const ADAPTER = {
getClient: () => ({
meta: {
getItems: async (type: string) =>
WORLD.authored
WORLD.conflict
? (type === 'doc' ? CONFLICT_DOCS : []) // implicit books only
: WORLD.authored
? (type === 'doc' ? AUTHORED_DOCS : type === 'book' ? AUTHORED_BOOKS : [])
: (type === 'doc' ? DOCS : []), // no authored books
getItem: async (_type: string, name: string) => ({
item: { name, content: (WORLD.authored ? AUTHORED_CONTENT : CONTENT)[name] },
}),
getItem: async (_type: string, name: string, options?: { packageId?: string }) =>
WORLD.conflict
? conflictRead(name, options?.packageId)
: { item: { name, content: (WORLD.authored ? AUTHORED_CONTENT : CONTENT)[name] } },
},
}),
};
Expand Down Expand Up @@ -436,3 +467,96 @@ describe('objectstack#33055 — the #section survives the flat → canonical red
await waitFor(() => expect(scrolled).toEqual(['lead-scoring']));
});
});


// ─────────────────────────────────────────────────────────────────────────────
// objectstack#34070 — a doc name two packages ship: the reader picks the package
// ─────────────────────────────────────────────────────────────────────────────

/**
* Two enabled packages may ship one doc name. A read of it that names no
* package is refused, `409 RESOURCE_CONFLICT`, with the holders in the
* refusal's `details.candidates` (ADR-0150 D3; the `/meta` 409 section of
* `content/docs/api/client-sdk.mdx`). The portal lists those candidates, each
* linking to its package address `/apps/PACKAGE/docs/NAME`, where the read names
* the package and the doc opens in that package's own book. One holder, and
* any other failure, answer as they did.
*/
describe('objectstack#34070 — a doc name two packages ship lists its candidate packages', () => {
function Where() {
return <div data-testid="where">{useLocation().pathname}</div>;
}
function Portal({ entry }: { entry: string }) {
const children = (
<>
<Route path=":slug" element={<DocsSlug />} />
<Route path=":slug/:name" element={<DocPage />} />
</>
);
return (
<MemoryRouter initialEntries={[entry]}>
<Where />
<Routes>
<Route path="/docs" element={<DocsLayout />}>
<Route index element={<DocsIndex />} />
{children}
</Route>
<Route path="/apps/:appName/docs" element={<DocsLayout />}>
{children}
</Route>
</Routes>
</MemoryRouter>
);
}
const candidateList = () => screen.findByRole('list', { name: 'Packages that provide this document' });

beforeEach(() => {
WORLD.conflict = true;
});
afterEach(() => {
WORLD.conflict = false;
});

it('a 409 with two candidates lists both, each linking to its package address', async () => {
render(<Portal entry="/docs/shared_guide" />);
const list = await candidateList();
expect(screen.getByRole('heading', { name: 'Choose a package' })).toBeInTheDocument();
const links = within(list).getAllByRole('link');
expect(links.map((l) => l.getAttribute('href'))).toEqual([
'/apps/com.example.alpha/docs/shared_guide',
'/apps/com.example.beta/docs/shared_guide',
]);
// The package as the portal names it (its book), with its id beside it.
expect(links.map((l) => l.textContent)).toEqual(['Alphacom.example.alpha', 'Betacom.example.beta']);
expect(screen.queryByTestId('doc-content')).toBeNull();
expect(screen.queryByText('Failed to load documentation')).toBeNull();
});

it('each candidate opens that package\'s doc, in that package\'s book', async () => {
render(<Portal entry="/docs/shared_guide" />);
fireEvent.click(within(await candidateList()).getByRole('link', { name: /com\.example\.alpha/ }));
expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA SHARED BODY');
// Beta is listed first by the server; the package container decides the book.
expect(screen.getByTestId('where').textContent).toBe('/apps/com.example.alpha/docs/com.example.alpha/shared_guide');
cleanup();

render(<Portal entry="/docs/shared_guide" />);
fireEvent.click(within(await candidateList()).getByRole('link', { name: /com\.example\.beta/ }));
expect(await screen.findByTestId('doc-content')).toHaveTextContent('BETA SHARED BODY');
expect(screen.getByTestId('where').textContent).toBe('/apps/com.example.beta/docs/com.example.beta/shared_guide');
});

it('CONTROL: a doc one package ships renders as today, with no candidate list', async () => {
render(<Portal entry="/docs/alpha_welcome" />);
expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA BODY');
expect(screen.getByTestId('where').textContent).toBe('/docs/com.example.alpha/alpha_welcome');
expect(screen.queryByRole('list', { name: 'Packages that provide this document' })).toBeNull();
});

it('CONTROL: a failure that is not the 409 keeps today\'s error state', async () => {
render(<Portal entry="/docs/com.example.alpha/broken_doc" />);
expect(await screen.findByText('Failed to load documentation')).toBeInTheDocument();
expect(screen.getByText('The metadata service is unavailable')).toBeInTheDocument();
expect(screen.queryByRole('list', { name: 'Packages that provide this document' })).toBeNull();
});
});
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3409,6 +3409,9 @@ const ar = {
allDocs: 'كل الوثائق',
onlineDocs: 'الوثائق عبر الإنترنت',
loadingDocumentation: 'جارٍ تحميل الوثائق',
docConflictTitle: 'اختر حزمة',
docConflictDescription: 'توفّر أكثر من حزمة مثبّتة مستندًا باسم {{name}}. افتح المستند الذي تريد قراءته.',
docConflictCandidates: 'الحزم التي توفّر هذا المستند',
documentation: 'الوثائق',
uncategorized: 'غير مصنف',
about: 'حول',
Expand Down
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3135,6 +3135,9 @@ const de = {
allDocs: 'Gesamte Dokumentation',
onlineDocs: 'Online-Dokumentation',
loadingDocumentation: 'Dokumentation wird geladen',
docConflictTitle: 'Paket auswählen',
docConflictDescription: 'Mehr als ein installiertes Paket stellt ein Dokument namens {{name}} bereit. Öffnen Sie das gewünschte.',
docConflictCandidates: 'Pakete, die dieses Dokument bereitstellen',
documentation: 'Dokumentation',
uncategorized: 'Nicht kategorisiert',
about: 'Über',
Expand Down
3 changes: 3 additions & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3794,6 +3794,9 @@ const en = {
keyboardShortcuts: 'Keyboard shortcuts',
onlineDocs: 'Online documentation',
loadingDocumentation: 'Loading documentation',
docConflictTitle: 'Choose a package',
docConflictDescription: 'More than one installed package provides a document named {{name}}. Open the one you want to read.',
docConflictCandidates: 'Packages that provide this document',
documentation: 'Documentation',
uncategorized: 'Uncategorized',
about: 'About',
Expand Down
Loading
Loading