Skip to content

Commit b4eea88

Browse files
feat(console): the docs reader lists the candidate packages when a doc name two packages ship is refused (#34109)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9RpEW8k6PfkxHahidoPk4Au)_ Fixes #34070 Waits-on: #34036 — satisfied: merged to main as `5af956f3`; this branch merged `origin/main` at `37ea190a`. 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 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 of a name that package ships opens the doc in that package's own book; three `@object-ui/i18n` keys (`help.docConflictTitle`, `help.docConflictDescription`, `help.docConflictCandidates`) in all 11 shipped locales, none renamed or removed. A doc one package ships, and every other failure, render as before. Metadata-protocol: none ## 维护者速读 - 改了什么:两个启用的包发布同名文档时,Console 文档页不再显示笼统的「Failed to load documentation」,而是列出提供该文档的各个包(先显示包在文档门户里的名字,旁边是包 id),点哪个就在那个包的地址 `/apps/包id/docs/文档名` 下打开那一份,并且侧边栏是那个包自己的书。 - 为什么改:落实裁决 6893582352(#33264):服务端在 PR #34036 合并后,不指明包读取同名文档会回 409 并列出候选包,Console 要把候选包显示出来让用户选,而不是报错。 - 风险与回滚:只在读取返回 409 `RESOURCE_CONFLICT` 且带候选包时生效;单持有者的文档、401/403、404 和其他错误都照旧。另含一处小修:在包容器下打开同名文档时,首页书按该包自己的那份来定(否则会落进另一个包的书)。回滚即还原本 PR。 - 先看:`ui/apps/console/src/pages/DocPage.tsx` 的 `conflictCandidates` 与 `state === 'conflict'` 分支;`ui/apps/console/src/pages/DocsSlug.tsx` 的 `ownCopy` 一行;`docs-portal.test.tsx` 末尾新增的 describe。 - 两分钟验证:`pnpm --dir ui exec vitest run apps/console/src/pages/docs-portal.test.tsx -t objectstack#34070`,预期 4 个用例通过。 - 需要你做的:无,席位落地(#34036 已合并,本分支已并入 main)。 ## What changes PR #34036 (merged as `5af956f3`; read first at its head `e4b68eb2b`) makes a doc read that names no package, of a name two or more enabled packages ship, answer `409 RESOURCE_CONFLICT` with every holder named. The envelope this PR reads, and where it was read: - The thrown refusal: `PackageScopedNameRefusedError` (`code = 'RESOURCE_CONFLICT'`, `status = 409`, `refusal.candidates`) in `packages/core/src/package-scoped-resolution.ts`; #34036 throws it from `readMetaItem` through `refuseAmbiguousBareDocRead` (`packages/metadata-protocol/src/protocol-meta-item-reads.ts` on its head; on main the judge call in `readMetaItem` is unchanged — the file differs from that head only by an unrelated action-artifact hunk). - The wire: the `GET /meta/:type/:name` handler answers it with `handleRouteError(res, error, undefined, { packageScopedCandidates: true })` (`packages/rest/src/meta-item-read-routes.ts`), which puts the holders at `details.candidates` (`packageScopedCandidatesMember`, `packages/rest/src/error-response.ts`). - The client: `unwrapResponse` in `packages/client/src/index.ts` sets `err.code`, `err.httpStatus` and `err.details = errorBody.details` on the rejection. - The docs: `content/docs/api/client-sdk.mdx`, the `/meta` 409 section ("The server picks no holder for you"): `err.httpStatus === 409 && err.code === 'RESOURCE_CONFLICT'`, then `err.details?.candidates` = `[{ kind: 'package', packageId }, …]`. The head and the docs agree. Where the 409 lands in the Console: a flat `/docs/NAME` permalink of a name in the member's doc list redirects (DocsSlug) to `/docs/BOOK/NAME`, and DocPage's read there names no package, so the refusal reaches DocPage, which rendered "Failed to load documentation". The change sits there: - `DocPage.tsx`: `conflictCandidates(err)` reads a `409` `RESOURCE_CONFLICT` rejection's `details.candidates` and keeps the `package` holders. Non-empty ⇒ a `conflict` state: a "Choose a package" list, each entry labelled as the portal names the package (its home book for this doc, `homeBook(name, books, docs, packageId)`), the package id beside it, linking to `/apps/PACKAGE/docs/NAME` (the package container's flat permalink, the address the app header's docs link already uses). Every other failure keeps today's branch. - `DocsSlug.tsx` + `book-nav.ts`: `homeBook` takes an optional `packageId`. Under `/apps/PACKAGE/docs/NAME`, when that package ships `NAME`, its own copy decides the home book. Without this, the redirect took the first listed doc of the name, so a candidate link landed in the OTHER package's book (content right, since DocPage reads with `?package=`, sidebar wrong). No other URL changes its answer: the package is passed only when the container ships the name. - `@object-ui/i18n`: `help.docConflictTitle`, `help.docConflictDescription` (`{{name}}`), `help.docConflictCandidates`, in all 11 locale packs; `zh-Hant.ts` regenerated with `gen-zh-hant.mjs` from `zh-Hans.ts`. Candidates of another kind (`environment`, `platform`, `residual`) are not listed: for a `doc` the environment's own item answers first (#34036), so a doc refusal names packages only; a refusal naming no package keeps today's error state. ## Tests New top-level describe in the shared harness `ui/apps/console/src/pages/docs-portal.test.tsx` (real DocsLayout / DocsSlug / DocPage under the real route table, `/docs` and `/apps/:appName/docs`), with a third adapter world: `shared_guide` shipped by `com.example.beta` (listed first) and `com.example.alpha`; a read of it with no package rejects the way `@objectstack/client` does on the 409 (`httpStatus`, `code`, `details.candidates`); with a package it answers that package's copy. - a 409 with two candidates lists both, each linking to `/apps/PACKAGE/docs/shared_guide`, labelled `Alpha` / `Beta` with the id beside it; no doc body, no load error. - each candidate opens that package's doc in that package's book: alpha lands on `/apps/com.example.alpha/docs/com.example.alpha/shared_guide` with alpha's body, beta likewise. - CONTROL: a doc one package ships renders as today, no list. - CONTROL: a non-409 failure (500) keeps today's "Failed to load documentation" with the server's message, no list. No existing test was edited (the hoisted adapter gained the third world, switched on only inside the new describe). <details><summary>Ablation (two legs, each red, each restored)</summary> Both through `scripts/ablation-replace.mjs`, pins run with `-t objectstack#34070` (ui vitest resolves `@object-ui/*` and the Console to `src/`, so no build sits between mutation and run): - A, the conflict branch never taken (`if (holders) {` to `if (holders && (false as boolean)) {` in DocPage): anchor 1 to 0, blob `217c8533` to `19bdbb86`; 2 failed, 2 passed (both candidate pins: `Unable to find role="list"`). Restored: blob equal to HEAD, `git diff HEAD` empty. - B, the container no longer decides the home book (`homeBook(slug, books, docs, ownCopy ? appName : undefined)` to `homeBook(slug, books, docs, undefined)` in DocsSlug): anchor 1 to 0, blob `6164bc8b` to `37d661e1`; 1 failed, 3 passed (`expected '/apps/com.example.alpha/docs/com.example.beta/shared_guide'` where alpha's book was pinned). Restored: blob equal to HEAD, `git diff HEAD` empty. </details> ## Acceptance notes - The card names `DocsSlug.tsx` / `DocShell.tsx` "as located"; the refusal lands in `DocPage.tsx` (the reader's read is the one that names no package), so the chooser is there. DocsSlug's single-name probe (`refusalFor`, run only for a name the member's lists do not carry) still reads only 401 / 403 as an answer; a 409 there keeps today's fallback. Not exercised: a name both holders ship is in the member's list, so that probe does not run for it. - The candidate's label is the package's home book label for this doc (the implicit book's humanized id, or an authored book's label): the Console has no package-label source; the id is shown beside it. - Candidate links depend on the exact `?package=` doc read answering that package's doc. #34040 tracks a composed artifact server answering the other holder's doc there; not in this PR. - Sequencing: built against #34036's head while it was open; #34036 has since merged (`5af956f3`), `origin/main` was merged into this branch at `37ea190a` and the pins re-run there (Verification, round 2). ## Verification **Round 2, after #34036 merged — head `37ea190a`** (merge of `origin/main` `385ea1cc` into `be6b38f6`, no conflict): the envelope files are byte-identical to the #34036 head read in round 1 (`git diff --quiet` exit 0 for `packages/core/src/package-scoped-resolution.ts`, `packages/rest/src/meta-item-read-routes.ts`, `packages/rest/src/error-response.ts`, `packages/client/src/index.ts`, `content/docs/api/client-sdk.mdx`); `packages/metadata-protocol/src/protocol-meta-item-reads.ts` and `packages/objectql/src/registry.ts` equal the merge commit `5af956f3`'s, with `refuseAmbiguousBareDocRead` called at the same spot. The branch delta against `origin/main` is still these 16 files (+264 / -14). After `pnpm install --frozen-lockfile` and rebuilding `@objectstack/client...`, `@objectstack/formula...`, `@objectstack/sdui-parser...` (`VERDICT command-exit 0`): pins `-t objectstack#34070` 4 passed; `apps/console/src/pages/` 159 files, 1333 tests passed; `packages/i18n/` 102 files, 1894 passed, 13 skipped. **Round 1:** All readings at head `be6b38f6` (this branch), objectstack-ai/objectstack, base `63db7240`. The ablation legs ran at `9854afce`, whose `ui/apps/console` tree is byte-identical at this head (`git diff --quiet` exit 0; the later commits add the changeset and regenerate `zh-Hant.ts`); the pins were re-run at this head. <details><summary>Suites, lint, gates</summary> - `pnpm --dir ui exec vitest run apps/console/src/pages/docs-portal.test.tsx`: 28 passed (24 existing + 4 new). - `pnpm --dir ui exec vitest run packages/i18n/`: 102 files, 1894 passed, 13 skipped (`zh-hant-generated`, `all-locales-key-parity` included). - `node ui/scripts/check-i18n-call-site-keys.mjs`, `check-i18n-dead-keys.mjs`, `check-i18n-en-drift.mjs`: each exit 0. - `pnpm check:new-line-citations` (ui): 0 new, exit 0. `eslint` on the four console files: 0 errors (2 existing `any` warnings on untouched lines). - `dispatch-gates.mjs --commands` (no paths, at `be6b38f6`): 39 derived, 39 run, each exit 0 (under the verify lock, `VERDICT command-exit 0`); `--ran` reconciliation: 39 accounted, 0 NOT-MEASURED. - `pnpm --dir ui exec vitest run apps/console/src/pages/` at `be6b38f6`: 159 files, 1333 tests passed. - Console `pnpm run type-check` (`tsc --noEmit` and `tsc -b tsconfig.node.json`) after building `@object-ui/console^...`: `VERDICT command-exit 0`; `--listFiles` holds all four edited console files. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmP4uQusF8yrKtRnvqJ <!-- signed: domain:ui#1 · os-steve · session_01ADHkmP4uQusF8yrKtRnvqJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e08aad7 commit b4eea88

16 files changed

Lines changed: 264 additions & 14 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/console': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(console): the docs reader lists the candidate packages when a doc name two packages ship is refused
7+
8+
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.
9+
Metadata-protocol: none
10+
11+
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.

‎ui/apps/console/src/pages/DocPage.tsx‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
*/
88

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

2222
interface DocItem {
2323
name: string;
@@ -32,6 +32,24 @@ function scrollHeadingIntoView(id: string): boolean {
3232
return target !== null;
3333
}
3434

35+
/**
36+
* The packages a `409 RESOURCE_CONFLICT` doc read names as holders of the
37+
* name: `@objectstack/client` carries the refusal's `details.candidates` on the
38+
* rejection (`{ kind: 'package', packageId }` per package). Null for any other
39+
* failure, and for a refusal that names no package, so those keep their state.
40+
*/
41+
function conflictCandidates(err: unknown): string[] | null {
42+
const e = err as { httpStatus?: unknown; code?: unknown; details?: { candidates?: unknown } } | null;
43+
if (e?.httpStatus !== 409 || e.code !== 'RESOURCE_CONFLICT') return null;
44+
const candidates = e.details?.candidates;
45+
if (!Array.isArray(candidates)) return null;
46+
const packageIds = candidates
47+
.filter((c): c is { kind: 'package'; packageId: string } =>
48+
c?.kind === 'package' && typeof c.packageId === 'string' && c.packageId !== '')
49+
.map((c) => c.packageId);
50+
return packageIds.length > 0 ? packageIds : null;
51+
}
52+
3553
/**
3654
* `/docs/:name` — render one package-doc metadata item (ADR-0046).
3755
*
@@ -48,6 +66,12 @@ function scrollHeadingIntoView(id: string): boolean {
4866
* A doc the member may not read is a different answer: the server refuses it
4967
* with 401 / 403 (ADR-0046 §6.7), and the page shows that refusal, with the
5068
* server's reason, rather than "not found" or a load failure (objectui#10188).
69+
*
70+
* A name two or more enabled packages ship is refused by a read that names no
71+
* package, `409 RESOURCE_CONFLICT` with the holders as candidates (ADR-0150
72+
* D3). Nothing picks one: the page lists the candidates, each opening that
73+
* package's copy at its package address `/apps/<packageId>/docs/<name>`, where
74+
* the read names the package.
5175
*/
5276
export default function DocPage() {
5377
// Route is `/docs/:slug/:name` (`:slug` = book, `:name` = doc). `appName` is
@@ -72,8 +96,9 @@ export default function DocPage() {
7296
const adapter = useAdapter();
7397
const { t } = useObjectTranslation();
7498
const [doc, setDoc] = useState<DocItem | null>(null);
75-
const [state, setState] = useState<'loading' | 'ready' | 'missing' | 'refused' | 'error'>('loading');
99+
const [state, setState] = useState<'loading' | 'ready' | 'missing' | 'refused' | 'conflict' | 'error'>('loading');
76100
const [errorMessage, setErrorMessage] = useState<string>('');
101+
const [candidates, setCandidates] = useState<string[]>([]);
77102

78103
useEffect(() => {
79104
let cancelled = false;
@@ -104,6 +129,14 @@ export default function DocPage() {
104129
setState('refused');
105130
return;
106131
}
132+
// Two or more packages ship this name and the read named none of
133+
// them: the server names the holders, and the reader picks one.
134+
const holders = conflictCandidates(err);
135+
if (holders) {
136+
setCandidates(holders);
137+
setState('conflict');
138+
return;
139+
}
107140
// The metadata API answers 404 for unknown names — that is the
108141
// ADR-mandated soft-degrade path, not an error.
109142
if (status === 404 || /not found/i.test(err?.message ?? '')) {
@@ -249,6 +282,47 @@ export default function DocPage() {
249282
return <DocRefusal name={name} message={errorMessage} />;
250283
}
251284

285+
if (state === 'conflict') {
286+
return (
287+
<DocShell breadcrumb={name}>
288+
<div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center">
289+
<Layers className="h-10 w-10 text-muted-foreground" />
290+
<h1 className="text-lg font-semibold">
291+
{t('help.docConflictTitle', { defaultValue: 'Choose a package' })}
292+
</h1>
293+
<p className="text-sm text-muted-foreground">
294+
{t('help.docConflictDescription', {
295+
defaultValue: 'More than one installed package provides a document named {{name}}. Open the one you want to read.',
296+
name,
297+
})}
298+
</p>
299+
<ul
300+
aria-label={t('help.docConflictCandidates', { defaultValue: 'Packages that provide this document' })}
301+
className="mt-2 flex w-full max-w-md flex-col gap-2 text-left"
302+
>
303+
{candidates.map((packageId) => {
304+
// The package as the portal names it: its home book for this doc.
305+
const label = (name ? homeBook(name, books, allDocs, packageId)?.label : undefined) ?? packageId;
306+
return (
307+
<li key={packageId}>
308+
<Link
309+
to={{ pathname: `/apps/${packageId}/docs/${name}`, hash }}
310+
className="flex flex-col rounded-md border px-4 py-3 hover:bg-muted/50"
311+
>
312+
<span className="text-sm font-medium">{label}</span>
313+
{label !== packageId ? (
314+
<span className="text-xs text-muted-foreground">{packageId}</span>
315+
) : null}
316+
</Link>
317+
</li>
318+
);
319+
})}
320+
</ul>
321+
</div>
322+
</DocShell>
323+
);
324+
}
325+
252326
if (state === 'error') {
253327
return (
254328
<DocShell breadcrumb={name}>

‎ui/apps/console/src/pages/DocsSlug.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { useAdapter } from '@object-ui/app-shell';
1414
import { DocShell } from './DocShell';
1515
import BookPage, { DocRefusal } from './BookPage';
1616
import { useBookData } from './use-book-data';
17-
import { bookNamedBy, bookSlug, homeBook } from './book-nav';
17+
import { bookNamedBy, bookSlug, homeBook, pkgOf } from './book-nav';
1818

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

115115
// Otherwise a flat doc permalink → redirect to its canonical in-book URL.
116116
const base = appName ? `/apps/${appName}/docs` : '/docs';
117-
const hb = slug ? homeBook(slug, books, docs) : null;
117+
// Under a package container that ships this name, its own copy decides the
118+
// home book: two packages may ship one doc name, and the doc read there names
119+
// the container's package (objectstack#34070), so the book must be its too.
120+
const ownCopy = !!appName && docs.some((d) => d.name === slug && pkgOf(d) === appName);
121+
const hb = slug ? homeBook(slug, books, docs, ownCopy ? appName : undefined) : null;
118122
if (hb && slug && docs.some((d) => d.name === slug)) {
119123
return <Navigate to={{ pathname: `${base}/${bookSlug(hb)}/${slug}`, hash }} replace />;
120124
}

‎ui/apps/console/src/pages/book-nav.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -453,10 +453,14 @@ function humanizePackageId(pkg: string): string {
453453
* navigation entry opens the page in its book's context (objectui#10188, the
454454
* card's addendum). Only a doc no book of its package claims falls back to the
455455
* package's first book in display order, as before.
456+
*
457+
* Two packages may ship one doc name (objectstack#34070). `packageId` then
458+
* names whose copy is meant, so the home book is that package's; without it
459+
* the package is the first listed doc of the name's, as before.
456460
*/
457-
export function homeBook(docName: string, portalBooks: Book[], docs: ResolverDoc[]): Book | null {
461+
export function homeBook(docName: string, portalBooks: Book[], docs: ResolverDoc[], packageId?: string): Book | null {
458462
const doc = docs.find((d) => d.name === docName);
459-
const pkg = doc ? pkgOf(doc) : namePrefix(docName);
463+
const pkg = packageId ?? (doc ? pkgOf(doc) : namePrefix(docName));
460464
const ownBooks = sortBooks(portalBooks).filter((b) => pkgOfBook(b) === pkg);
461465
return findBookContainingDoc(ownBooks, docs, docName)?.book ?? ownBooks[0] ?? null;
462466
}

‎ui/apps/console/src/pages/docs-portal.test.tsx‎

Lines changed: 130 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
*/
1919

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

2424
// ── Sample metadata the mocked adapter serves (two packages, no books) ──────
@@ -72,17 +72,48 @@ const { ADAPTER, WORLD } = vi.hoisted(() => {
7272
acme_intro: 'ACME BODY',
7373
ops_setup: 'OPS BODY',
7474
};
75-
const WORLD = { authored: false };
75+
// objectstack#34070 — a third world, switched on only by the "two packages
76+
// ship one doc name" block: `shared_guide` is shipped by alpha AND beta (beta
77+
// listed first), and a read of it that names no package is refused the way
78+
// the server refuses it, `409 RESOURCE_CONFLICT` naming both holders.
79+
const CONFLICT_DOCS = [
80+
{ name: 'shared_guide', label: 'Shared Guide', _packageId: 'com.example.beta' },
81+
{ name: 'beta_start', label: 'Beta Start', _packageId: 'com.example.beta' },
82+
{ name: 'shared_guide', label: 'Shared Guide', _packageId: 'com.example.alpha' },
83+
{ name: 'alpha_welcome', label: 'Alpha Welcome', _packageId: 'com.example.alpha' },
84+
];
85+
const CONFLICT_CONTENT: Record<string, Record<string, string>> = {
86+
'com.example.alpha': { shared_guide: 'ALPHA SHARED BODY', alpha_welcome: 'ALPHA BODY' },
87+
'com.example.beta': { shared_guide: 'BETA SHARED BODY', beta_start: 'BETA BODY' },
88+
};
89+
/** A rejection shaped like `@objectstack/client`'s on a non-2xx response. */
90+
const failure = (httpStatus: number, code: string, message: string, details?: unknown) =>
91+
Object.assign(new Error(message), { httpStatus, code, details });
92+
const conflictRead = (name: string, packageId: string | undefined) => {
93+
if (name === 'broken_doc') throw failure(500, 'INTERNAL_ERROR', 'The metadata service is unavailable');
94+
const holders = Object.keys(CONFLICT_CONTENT).filter((p) => name in CONFLICT_CONTENT[p]);
95+
if (packageId) return { item: { name, content: CONFLICT_CONTENT[packageId]?.[name] } };
96+
if (holders.length > 1) {
97+
throw failure(409, 'RESOURCE_CONFLICT', `doc "${name}" is held by ${holders.length} packages`, {
98+
candidates: holders.map((p) => ({ kind: 'package', packageId: p })),
99+
});
100+
}
101+
return { item: { name, content: holders.length ? CONFLICT_CONTENT[holders[0]][name] : undefined } };
102+
};
103+
const WORLD = { authored: false, conflict: false };
76104
const ADAPTER = {
77105
getClient: () => ({
78106
meta: {
79107
getItems: async (type: string) =>
80-
WORLD.authored
108+
WORLD.conflict
109+
? (type === 'doc' ? CONFLICT_DOCS : []) // implicit books only
110+
: WORLD.authored
81111
? (type === 'doc' ? AUTHORED_DOCS : type === 'book' ? AUTHORED_BOOKS : [])
82112
: (type === 'doc' ? DOCS : []), // no authored books
83-
getItem: async (_type: string, name: string) => ({
84-
item: { name, content: (WORLD.authored ? AUTHORED_CONTENT : CONTENT)[name] },
85-
}),
113+
getItem: async (_type: string, name: string, options?: { packageId?: string }) =>
114+
WORLD.conflict
115+
? conflictRead(name, options?.packageId)
116+
: { item: { name, content: (WORLD.authored ? AUTHORED_CONTENT : CONTENT)[name] } },
86117
},
87118
}),
88119
};
@@ -436,3 +467,96 @@ describe('objectstack#33055 — the #section survives the flat → canonical red
436467
await waitFor(() => expect(scrolled).toEqual(['lead-scoring']));
437468
});
438469
});
470+
471+
472+
// ─────────────────────────────────────────────────────────────────────────────
473+
// objectstack#34070 — a doc name two packages ship: the reader picks the package
474+
// ─────────────────────────────────────────────────────────────────────────────
475+
476+
/**
477+
* Two enabled packages may ship one doc name. A read of it that names no
478+
* package is refused, `409 RESOURCE_CONFLICT`, with the holders in the
479+
* refusal's `details.candidates` (ADR-0150 D3; the `/meta` 409 section of
480+
* `content/docs/api/client-sdk.mdx`). The portal lists those candidates, each
481+
* linking to its package address `/apps/PACKAGE/docs/NAME`, where the read names
482+
* the package and the doc opens in that package's own book. One holder, and
483+
* any other failure, answer as they did.
484+
*/
485+
describe('objectstack#34070 — a doc name two packages ship lists its candidate packages', () => {
486+
function Where() {
487+
return <div data-testid="where">{useLocation().pathname}</div>;
488+
}
489+
function Portal({ entry }: { entry: string }) {
490+
const children = (
491+
<>
492+
<Route path=":slug" element={<DocsSlug />} />
493+
<Route path=":slug/:name" element={<DocPage />} />
494+
</>
495+
);
496+
return (
497+
<MemoryRouter initialEntries={[entry]}>
498+
<Where />
499+
<Routes>
500+
<Route path="/docs" element={<DocsLayout />}>
501+
<Route index element={<DocsIndex />} />
502+
{children}
503+
</Route>
504+
<Route path="/apps/:appName/docs" element={<DocsLayout />}>
505+
{children}
506+
</Route>
507+
</Routes>
508+
</MemoryRouter>
509+
);
510+
}
511+
const candidateList = () => screen.findByRole('list', { name: 'Packages that provide this document' });
512+
513+
beforeEach(() => {
514+
WORLD.conflict = true;
515+
});
516+
afterEach(() => {
517+
WORLD.conflict = false;
518+
});
519+
520+
it('a 409 with two candidates lists both, each linking to its package address', async () => {
521+
render(<Portal entry="/docs/shared_guide" />);
522+
const list = await candidateList();
523+
expect(screen.getByRole('heading', { name: 'Choose a package' })).toBeInTheDocument();
524+
const links = within(list).getAllByRole('link');
525+
expect(links.map((l) => l.getAttribute('href'))).toEqual([
526+
'/apps/com.example.alpha/docs/shared_guide',
527+
'/apps/com.example.beta/docs/shared_guide',
528+
]);
529+
// The package as the portal names it (its book), with its id beside it.
530+
expect(links.map((l) => l.textContent)).toEqual(['Alphacom.example.alpha', 'Betacom.example.beta']);
531+
expect(screen.queryByTestId('doc-content')).toBeNull();
532+
expect(screen.queryByText('Failed to load documentation')).toBeNull();
533+
});
534+
535+
it('each candidate opens that package\'s doc, in that package\'s book', async () => {
536+
render(<Portal entry="/docs/shared_guide" />);
537+
fireEvent.click(within(await candidateList()).getByRole('link', { name: /com\.example\.alpha/ }));
538+
expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA SHARED BODY');
539+
// Beta is listed first by the server; the package container decides the book.
540+
expect(screen.getByTestId('where').textContent).toBe('/apps/com.example.alpha/docs/com.example.alpha/shared_guide');
541+
cleanup();
542+
543+
render(<Portal entry="/docs/shared_guide" />);
544+
fireEvent.click(within(await candidateList()).getByRole('link', { name: /com\.example\.beta/ }));
545+
expect(await screen.findByTestId('doc-content')).toHaveTextContent('BETA SHARED BODY');
546+
expect(screen.getByTestId('where').textContent).toBe('/apps/com.example.beta/docs/com.example.beta/shared_guide');
547+
});
548+
549+
it('CONTROL: a doc one package ships renders as today, with no candidate list', async () => {
550+
render(<Portal entry="/docs/alpha_welcome" />);
551+
expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA BODY');
552+
expect(screen.getByTestId('where').textContent).toBe('/docs/com.example.alpha/alpha_welcome');
553+
expect(screen.queryByRole('list', { name: 'Packages that provide this document' })).toBeNull();
554+
});
555+
556+
it('CONTROL: a failure that is not the 409 keeps today\'s error state', async () => {
557+
render(<Portal entry="/docs/com.example.alpha/broken_doc" />);
558+
expect(await screen.findByText('Failed to load documentation')).toBeInTheDocument();
559+
expect(screen.getByText('The metadata service is unavailable')).toBeInTheDocument();
560+
expect(screen.queryByRole('list', { name: 'Packages that provide this document' })).toBeNull();
561+
});
562+
});

‎ui/packages/i18n/src/locales/ar.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3409,6 +3409,9 @@ const ar = {
34093409
allDocs: 'كل الوثائق',
34103410
onlineDocs: 'الوثائق عبر الإنترنت',
34113411
loadingDocumentation: 'جارٍ تحميل الوثائق',
3412+
docConflictTitle: 'اختر حزمة',
3413+
docConflictDescription: 'توفّر أكثر من حزمة مثبّتة مستندًا باسم {{name}}. افتح المستند الذي تريد قراءته.',
3414+
docConflictCandidates: 'الحزم التي توفّر هذا المستند',
34123415
documentation: 'الوثائق',
34133416
uncategorized: 'غير مصنف',
34143417
about: 'حول',

‎ui/packages/i18n/src/locales/de.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3135,6 +3135,9 @@ const de = {
31353135
allDocs: 'Gesamte Dokumentation',
31363136
onlineDocs: 'Online-Dokumentation',
31373137
loadingDocumentation: 'Dokumentation wird geladen',
3138+
docConflictTitle: 'Paket auswählen',
3139+
docConflictDescription: 'Mehr als ein installiertes Paket stellt ein Dokument namens {{name}} bereit. Öffnen Sie das gewünschte.',
3140+
docConflictCandidates: 'Pakete, die dieses Dokument bereitstellen',
31383141
documentation: 'Dokumentation',
31393142
uncategorized: 'Nicht kategorisiert',
31403143
about: 'Über',

‎ui/packages/i18n/src/locales/en.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3794,6 +3794,9 @@ const en = {
37943794
keyboardShortcuts: 'Keyboard shortcuts',
37953795
onlineDocs: 'Online documentation',
37963796
loadingDocumentation: 'Loading documentation',
3797+
docConflictTitle: 'Choose a package',
3798+
docConflictDescription: 'More than one installed package provides a document named {{name}}. Open the one you want to read.',
3799+
docConflictCandidates: 'Packages that provide this document',
37973800
documentation: 'Documentation',
37983801
uncategorized: 'Uncategorized',
37993802
about: 'About',

0 commit comments

Comments
 (0)