Skip to content

Commit acc9c57

Browse files
fix(app-shell): show the explain refusal's message instead of blanking the Access panel (#27012)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ85kpgfqxzRKnovzXGcQbacp)_ Fixes #26805 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:Studio「权限说明」面板在服务端返回非 403 拒绝时,改为读取错误信封里的 message 显示,而不是整个面板消失。 - **为什么改**:管理员把对象名打错(404)、参数不合法(400)或服务端出错(500)时,面板直接变空白、没有任何提示,无从下手。 - **风险与回滚**:风险低,只改一个面板的出错文案读取,复用已有的共享读取器;回滚即还原本 PR 的一个提交。 - **先看**:`AccessExplainPanel.tsx` 的 `if (!res.ok)` 分支与 `catch`;新测试 `AccessExplainPanel.refusalEnvelope-26805.test.tsx`。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/AccessExplainPanel.refusalEnvelope-26805.test.tsx`,预期 8 个用例全绿。 - **需要你做的**:无,席位落地。 ## What changes `AccessExplainPanel` (Studio Access pillar) built its failure text from `data.message || data.error`. The explain door refuses in the ADR-0112 envelope, `{ success: false, error: { code, message } }`, where `error` is an object: it reached `setError`, rendered as a React child and unmounted the sheet, so any non-403 refusal left a blank panel. - The `!res.ok` branch now asks the shared app-shell reader `readEnvelopeFailureText` (`utils/apiErrorEnvelope.ts`) first, the same reader the package surfaces and the AI publish path use. ⛔ No new copy, and the shared reader is unchanged: it returns `null` for non-envelope bodies by design, and its header asks each caller to keep its own legacy rungs and fallback on its own line. So the panel keeps its two flat rungs (top-level `message`, bare-string `error`), now typed so only a string can pass, then the existing `HTTP STATUS STATUS_TEXT` line. This is the `PackagesPage` publish call site's spelling. - The `catch` hands `setError` a string only: an `Error`'s non-empty message, otherwise `String(err)`. Before, a rejection whose `message` was not a string reached state as-is. - The 403 branch is untouched: it still shows the localized delegated-scope sentence. - No server change and no change to the explain request. ## Tests New file `AccessExplainPanel.refusalEnvelope-26805.test.tsx` (8 cases), on the existing panel harness (faked authenticated fetch): - nested envelope 404 `OBJECT_NOT_FOUND`, 400 `VALIDATION_FAILED`, 500 `INTERNAL_ERROR`: the alert carries the server message and code, never `[object Object]`, and the panel's form is still mounted; - flat `{ message }` 404 still shows its message; - non-JSON 500 falls back to `HTTP 500 Internal Server Error`; - 403 in the nested envelope keeps the delegated-scope sentence; - a rejected request shows its `Error` message; a non-`Error` rejection leaves the panel mounted with an alert. ## Acceptance notes - The shared reader appends the declared code in parentheses (`Object 'x' not found (OBJECT_NOT_FOUND)`), as on every other surface that uses it. - Seven pre-existing eslint warnings in `AccessExplainPanel.tsx` sit on lines this diff does not touch; none are added. ## Verification All runs on head `b394f525`, worktree from `origin/main` `fd246c22`, after building the `@object-ui/app-shell` dependency closure under the verify lock (exit 0). <details><summary>Tests, typecheck, lint</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/app-shell/src/views/metadata-admin/AccessExplainPanel packages/app-shell/src/utils/apiErrorEnvelope.test.ts`: Test Files 8 passed (8), Tests 70 passed (70), lock VERDICT command-exit 0. - `pnpm --filter @object-ui/app-shell run type-check` (both `tsc --noEmit` and `tsconfig.test.json`): VERDICT command-exit 0. - `pnpm --dir ui exec eslint` on both files: exit 0, 0 errors, 7 warnings, all pre-existing. - `pnpm --dir ui run check:new-line-citations`: 0 new citations, exit 0. </details> <details><summary>Ablations (scripts/ablation-replace.mjs, restored to the HEAD blob each time)</summary> 1. The `!res.ok` expression restored to the old `(data?.message as string) || (data?.error as string) ||`: the three nested-envelope cases go red (404, 400, 500), the other 5 stay green. Restore verified: blob `c46dd278cdf3` equals HEAD, `git diff HEAD` empty. 2. The `catch` restored to `(err as Error)?.message ?? String(err)`: the non-`Error` rejection case goes red, 7 stay green. Same restore proof. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 24 commands; each ran with its exit captured before any pipe (`pnpm --dir ui exec vitest run scripts/` under the verify lock). `--ran` reconciliation: 24 derived, 24 run, 0 NOT-MEASURED, 0 UNRUN. Model tier: no path-derived mandate. - `node scripts/check-closing-keyword-parity.mjs` exit 0 - `node scripts/check-closing-keyword-parity.mjs --self-test` exit 0 - `node scripts/check-comment-mask-corpus.mjs` exit 0 - `node scripts/check-sdui-manifest.mjs` exit 0 - `node scripts/check-sdui-manifest.mjs --self-test` exit 0 - `pnpm --dir ui exec vitest run scripts/` exit 0 - `pnpm --filter @objectstack/spec run check:duration-unit-keys` exit 0 - `pnpm check:cross-package-test-inputs` exit 0 - `pnpm check:dispatcher-error-vocabulary` exit 0 - `pnpm check:driver-memory-census` exit 0 - `pnpm check:engine-double-contract` exit 0 - `pnpm check:gitlink-declared` exit 0 - `pnpm check:nul-bytes` exit 0 - `pnpm check:published-files` exit 0 - `pnpm check:query-options-erasure` exit 0 - `pnpm check:refd-timer-probe` exit 0 - `pnpm check:skill-identifier-liveness` exit 0 - `pnpm check:test-source-alias` exit 0 - `pnpm check:tier-file-adoption` exit 0 - `pnpm check:type-check-coverage` exit 0 - `pnpm check:type-check-debt` exit 0 - `pnpm check:undeclared-dep-imports` exit 0 - `pnpm check:watch-hint-literal` exit 0 - `pnpm check:where-matcher` exit 0 </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (changed files linted; repo-wide lint is CI's) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset. (`@object-ui/app-shell` is private: no changeset) - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the maintainer summary is Chinese by the dispatch contract). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbWZov36PsY1JbrTDA6)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4bce21d commit acc9c57

2 files changed

Lines changed: 154 additions & 2 deletions

File tree

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#26805 — a non-403 refusal from `POST /api/v1/security/explain`
5+
* must show the server's message, not blank the panel.
6+
*
7+
* The door answers in the ADR-0112 envelope, `{ success: false, error: { code,
8+
* message } }`. The panel used to read `data.message || data.error`; on that
9+
* envelope `data.error` is the OBJECT, which reached `setError`, rendered as a
10+
* React child and unmounted the whole sheet — no alert, no form. The panel now
11+
* asks the shared envelope reader (`readEnvelopeFailureText`, pinned in
12+
* `utils/apiErrorEnvelope.test.ts`); this file pins that THIS call site asks it,
13+
* for each status band the door sends, and that the panel's older readings
14+
* (a flat `{ message }`, a non-JSON body, the 403 sentence) are unchanged.
15+
*/
16+
17+
import '@testing-library/jest-dom/vitest';
18+
import { afterEach, describe, expect, it, vi } from 'vitest';
19+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
20+
21+
const fetchSpy = vi.fn();
22+
23+
vi.mock('@object-ui/auth', async (importOriginal) => ({
24+
...(await importOriginal<Record<string, unknown>>()),
25+
createAuthenticatedFetch: () => fetchSpy,
26+
}));
27+
vi.mock('@object-ui/react', async (importOriginal) => ({
28+
...(await importOriginal<Record<string, unknown>>()),
29+
useAdapter: () => ({ find: vi.fn(async () => []) }),
30+
}));
31+
vi.mock('./useMetadata', () => ({
32+
useMetadataClient: () => ({ list: async () => [] }),
33+
}));
34+
vi.mock('@object-ui/fields', async (importOriginal) => ({
35+
...(await importOriginal<typeof import('@object-ui/fields')>()),
36+
RecordPickerDialog: () => null,
37+
}));
38+
39+
import { AccessExplainPanel } from './AccessExplainPanel';
40+
41+
afterEach(() => {
42+
cleanup();
43+
fetchSpy.mockReset();
44+
});
45+
46+
const STATUS_TEXT: Record<number, string> = {
47+
400: 'Bad Request',
48+
403: 'Forbidden',
49+
404: 'Not Found',
50+
500: 'Internal Server Error',
51+
};
52+
53+
const jsonResponse = (status: number, body: unknown) => ({
54+
ok: status >= 200 && status < 300,
55+
status,
56+
statusText: STATUS_TEXT[status] ?? '',
57+
json: async () => body,
58+
});
59+
60+
/** A body exactly as `sendError` writes it. */
61+
const envelope = (code: string, message: string) => ({ success: false, error: { code, message } });
62+
63+
async function explain(object: string) {
64+
render(<AccessExplainPanel open onOpenChange={() => {}} />);
65+
fireEvent.change(screen.getByLabelText('Object'), { target: { value: object } });
66+
fireEvent.click(screen.getByRole('button', { name: /explain$/i }));
67+
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
68+
return screen.getByRole('alert').textContent ?? '';
69+
}
70+
71+
/** The sheet is still there: its form survived the refusal. */
72+
function expectPanelMounted() {
73+
expect(screen.getByLabelText('Object')).toBeInTheDocument();
74+
expect(screen.getByRole('button', { name: /explain$/i })).toBeInTheDocument();
75+
expect(screen.queryByTestId('explain-verdict')).not.toBeInTheDocument();
76+
}
77+
78+
describe('AccessExplainPanel — a refusal in the nested envelope shows its message', () => {
79+
it.each([
80+
[404, 'OBJECT_NOT_FOUND', "Object 'crm_leed' not found"],
81+
[400, 'VALIDATION_FAILED', "operation must be one of 'read', 'create', 'update', 'delete'"],
82+
[500, 'INTERNAL_ERROR', 'Internal server error'],
83+
])('%i %s — the alert carries the server message and the panel stays mounted', async (status, code, message) => {
84+
fetchSpy.mockResolvedValue(jsonResponse(status, envelope(code, message)));
85+
const alert = await explain('crm_leed');
86+
87+
expect(alert).toContain(message);
88+
expect(alert).toContain(code);
89+
expect(alert).not.toContain('[object Object]');
90+
expectPanelMounted();
91+
});
92+
});
93+
94+
describe('AccessExplainPanel — the readings that predate the envelope', () => {
95+
it('a flat `{ message }` body still shows its message', async () => {
96+
fetchSpy.mockResolvedValue(jsonResponse(404, { message: 'Unknown object x' }));
97+
const alert = await explain('x');
98+
99+
expect(alert).toContain('Unknown object x');
100+
expectPanelMounted();
101+
});
102+
103+
it('a non-JSON 500 falls back to the HTTP status line', async () => {
104+
fetchSpy.mockResolvedValue({
105+
ok: false,
106+
status: 500,
107+
statusText: 'Internal Server Error',
108+
json: async () => {
109+
throw new SyntaxError('Unexpected token < in JSON at position 0');
110+
},
111+
});
112+
const alert = await explain('crm_lead');
113+
114+
expect(alert).toContain('HTTP 500 Internal Server Error');
115+
expectPanelMounted();
116+
});
117+
118+
it('a 403 in the nested envelope keeps the friendly delegated-scope sentence', async () => {
119+
fetchSpy.mockResolvedValue(jsonResponse(403, envelope('PERMISSION_DENIED', '[Security] Access denied: …')));
120+
const alert = await explain('crm_lead');
121+
122+
expect(alert).toMatch(/manage_users|delegated admin scope/i);
123+
expect(alert).not.toContain('PERMISSION_DENIED');
124+
expectPanelMounted();
125+
});
126+
});
127+
128+
describe('AccessExplainPanel — a thrown failure reaches the alert as a string', () => {
129+
it('a rejected request shows its Error message', async () => {
130+
fetchSpy.mockRejectedValue(new TypeError('Failed to fetch'));
131+
const alert = await explain('crm_lead');
132+
133+
expect(alert).toContain('Failed to fetch');
134+
expectPanelMounted();
135+
});
136+
137+
it('a non-Error rejection still leaves the panel mounted with an alert', async () => {
138+
fetchSpy.mockRejectedValue({ message: { code: 'NETWORK' } });
139+
await explain('crm_lead');
140+
141+
expectPanelMounted();
142+
});
143+
});

‎ui/packages/app-shell/src/views/metadata-admin/AccessExplainPanel.tsx‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import {
5757
} from 'lucide-react';
5858
import { t, tFormat, useMetadataLocale } from './i18n.js';
5959
import { useMetadataClient } from './useMetadata.js';
60+
import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js';
6061

6162
/**
6263
* The explain-report vocabulary is OWNED by `@objectstack/spec/security` and
@@ -458,8 +459,16 @@ export function AccessExplainPanel({ open, onOpenChange, defaultObject, packageI
458459
return;
459460
}
460461
if (!res.ok) {
462+
// The door refuses in the ADR-0112 envelope, `{ success: false, error:
463+
// { code, message } }`, so `error` is an OBJECT there — handed to
464+
// `setError` it rendered as a React child and unmounted the panel. The
465+
// shared reader asks the envelope; the two typed rungs below it keep the
466+
// flat bodies this panel already read, and only a string reaches state.
461467
const detail =
462-
(data?.message as string) || (data?.error as string) || `HTTP ${res.status} ${res.statusText}`.trim();
468+
readEnvelopeFailureText(data) ||
469+
(typeof data?.message === 'string' ? data.message : '') ||
470+
(typeof data?.error === 'string' ? data.error : '') ||
471+
`HTTP ${res.status} ${res.statusText}`.trim();
463472
setError(detail);
464473
return;
465474
}
@@ -468,7 +477,7 @@ export function AccessExplainPanel({ open, onOpenChange, defaultObject, packageI
468477
void lookUpPeople(decided);
469478
void lookUpItemLabels(decided);
470479
} catch (err) {
471-
setError((err as Error)?.message ?? String(err));
480+
setError(err instanceof Error && err.message ? err.message : String(err));
472481
} finally {
473482
setBusy(false);
474483
}

0 commit comments

Comments
 (0)