Skip to content

Commit e32db46

Browse files
committed
fix(app-shell): no drafts-ledger read for a member, no published read for a new draft
Home's drafts row now reads GET /meta/_drafts only for a session holding a capability the ledger admits (studio.access, setup.access or manage_metadata), through the new useCanReadPendingDrafts(). The pending-changes sheet's drill-in waits for its new-or-update classification and does not ask a new draft for its published body, which could only answer 404. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011fs46jjQVe98Y5YTfDTixa
1 parent 39a78b1 commit e32db46

10 files changed

Lines changed: 385 additions & 7 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): the Console no longer sends two requests it knows will be refused, the drafts ledger for a member and the published body of a new draft
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **Home's drafts row** read `GET /api/v1/meta/_drafts` for whoever opened Home. A member holding none of the capabilities the ledger admits (`studio.access`, `setup.access` or `manage_metadata`) got a 403, and the console logged it as a failed request on every visit. The row now reads the ledger only for a session that holds one of them, through the new `useCanReadPendingDrafts()`. An unreported capability set still reads it, and the server still enforces the gate.
11+
- **The pending-changes sheet** (Studio's Publish and Changes, and the draft-preview bar's Changes) read each draft's published body beside its draft. Under Publish, where every row opens expanded, that read was sent before the sheet knew which drafts are new, so a draft-only object such as one just saved from New object got `GET /api/v1/meta/object/NAME?package=PKG` → 404. A row now waits for its new-or-update classification, and a new draft is not asked for a published body. A row whose classification read failed is read both ways, as before.
12+
13+
What to do: nothing. The pages render exactly as before.

‎ui/packages/app-shell/src/console/home/HomePage.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import { useAgents, isAskAgent, agentHasCapability } from '@object-ui/plugin-cha
3030
// May this session author metadata? Shared with the chat surfaces since the
3131
// maker convergence (cloud#1674) — the doctrine (objectstack#8270 posture,
3232
// unknown→fail-open) lives with the hook.
33-
import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js';
33+
import { useCanAuthorMetadata, useCanReadPendingDrafts } from '../../hooks/useCanAuthorMetadata.js';
3434
import { HomeAppsStrip } from './HomeAppsStrip.js';
3535
import { appSegmentOf, lastOpenedByApp } from './appLastOpened.js';
3636
import { recentItemObject, recentItemTypeLabel } from './recentItemTypeLabel.js';
@@ -292,10 +292,16 @@ function usePackageName(packageId: string | null): string | undefined {
292292
* publish. `usePublishAllDrafts` is the shared one-click publish, also run by
293293
* the ADR-0037 draft-preview bar. Returns the row, or `null` with nothing to
294294
* publish.
295+
*
296+
* Read only for a session the ledger admits (objectstack-ai/objectstack#25894):
297+
* Home is every member's landing, and a member holding none of the ledger's
298+
* capabilities was sent a `GET /meta/_drafts` that answers 403 on every visit.
299+
* Held, the read is held too, so the row is `null`, as with nothing to publish.
295300
*/
296301
function usePendingDraftsRow(t: (key: string, opts?: any) => string, language: string): React.ReactNode {
297302
const { publishAll, publishing } = usePublishAllDrafts(t);
298-
const { count, entries } = usePendingDrafts({});
303+
const canReadDrafts = useCanReadPendingDrafts();
304+
const { count, entries } = usePendingDrafts({ enabled: canReadDrafts });
299305
const drafted = (count ?? 0) > 0;
300306
// Named only when every draft is in one package: a row naming one package
301307
// for drafts spread over several would misplace the rest. Named by the name
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack-ai/objectstack#25894 — Home reads the pending-drafts ledger only
5+
* for a session the ledger admits.
6+
*
7+
* Measured on the 2026-10-25 browser pass: signed in as a member with no
8+
* metadata capability, the console sent `GET /api/v1/meta/_drafts` and logged
9+
* its 403 as a resource error. Home is every member's landing (the approvals
10+
* inbox lives here), and its drafts row read the env-wide ledger for whoever
11+
* opened it. The door admits `studio.access`, `setup.access` or
12+
* `manage_metadata` (`mayReadPendingDrafts`); a session holding none of them
13+
* is now sent no read.
14+
*
15+
* Drives the REAL `MePermissionsProvider` over a `/me/permissions` payload, as
16+
* `HomePage.authoringCapabilityGate.test.tsx` does, so the gate consumes the
17+
* server's answer through `hasCapabilities`.
18+
*
19+
* Pinned:
20+
* - a reported set holding none of the three: no `_drafts` read, no row;
21+
* - CONTROL: each of the three alone reads the ledger and renders the row;
22+
* - CONTROL: an unreported set (no `systemPermissions`) fails OPEN and reads.
23+
*/
24+
25+
import '@testing-library/jest-dom/vitest';
26+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27+
import React from 'react';
28+
import { act, render, screen, cleanup } from '@testing-library/react';
29+
import { MePermissionsProvider, type MePermissionsResponse } from '@object-ui/permissions';
30+
31+
vi.mock('react-router-dom', async () => {
32+
const { createElement } = await import('react');
33+
return {
34+
useNavigate: () => vi.fn(),
35+
Link: ({ to, ...rest }: { to: string } & Record<string, unknown>) => createElement('a', { ...rest, href: to }),
36+
};
37+
});
38+
39+
vi.mock('@object-ui/i18n', async (importOriginal) => ({
40+
...(await importOriginal<Record<string, unknown>>()),
41+
useObjectTranslation: () => ({ t: (key: string) => `«${key}»`, language: 'en' }),
42+
useObjectLabel: () => ({ appLabel: (app: any) => String(app?.label ?? app?.name ?? '') }),
43+
}));
44+
45+
vi.mock('@object-ui/auth', async (importOriginal) => ({
46+
...(await importOriginal<Record<string, unknown>>()),
47+
useAuth: () => ({ user: { id: 'u1', name: 'Sales Manager', email: 'sales.manager@example.com' } }),
48+
useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }),
49+
}));
50+
51+
vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
52+
...(await importOriginal<typeof import('@object-ui/plugin-chatbot/core')>()),
53+
useAgents: () => ({ agents: [] }),
54+
isAskAgent: () => false,
55+
agentHasCapability: () => false,
56+
}));
57+
58+
vi.mock('../../../providers/MetadataProvider', () => ({
59+
useMetadata: () => ({ apps: [{ name: 'crm', label: 'CRM' }], loading: false }),
60+
}));
61+
vi.mock('../../../context/NavigationContext', () => ({
62+
useNavigationContext: () => ({ currentAppName: 'crm' }),
63+
}));
64+
vi.mock('../../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) }));
65+
vi.mock('../../../hooks/useFavorites', () => ({ useFavorites: () => ({ favorites: [] }) }));
66+
vi.mock('../../../hooks/useHomeInbox', () => ({
67+
useHomeInbox: () => ({
68+
pendingApprovalsCount: 0,
69+
pendingApprovals: [],
70+
pendingApprovalsStatus: 'ready',
71+
pendingApprovalsReadable: true,
72+
notifications: [],
73+
unreadTopicCount: 0,
74+
notificationsStatus: 'ready',
75+
notificationsReadable: true,
76+
activity: { value: [], status: 'ready', readable: true },
77+
}),
78+
}));
79+
vi.mock('../../../hooks/useAiSurface', () => ({ resolveAiApiBase: () => '' }));
80+
vi.mock('../../../preview/usePublishAllDrafts', () => ({
81+
usePublishAllDrafts: () => ({ publishAll: async () => ({ ok: true }), publishing: false }),
82+
}));
83+
vi.mock('../../../runtime-config', () => ({
84+
getRuntimeConfig: () => ({ branding: { productName: 'ObjectStack' } }),
85+
isMarketplaceEnabled: () => true,
86+
isAiStudioEnabled: () => true,
87+
}));
88+
89+
import { HomePage } from '../HomePage';
90+
91+
const DRAFTS_ROUTE = '/api/v1/meta/_drafts';
92+
const routeOf = (url: string) => url.split('?')[0];
93+
94+
/** Two drafts in two packages: the row names no package, so no package list is read. */
95+
const DRAFTS = [
96+
{ type: 'object', name: 'visit', label: 'Visit', packageId: 'com.a' },
97+
{ type: 'object', name: 'invoice', label: 'Invoice', packageId: 'com.b' },
98+
];
99+
100+
let fetchCalls: string[] = [];
101+
102+
beforeEach(() => {
103+
fetchCalls = [];
104+
vi.stubGlobal(
105+
'fetch',
106+
vi.fn(async (input: unknown) => {
107+
const url = String(input);
108+
fetchCalls.push(url);
109+
if (routeOf(url) === DRAFTS_ROUTE) return { ok: true, status: 200, json: async () => ({ drafts: DRAFTS }) };
110+
return { ok: false, status: 404, json: async () => ({}) };
111+
}),
112+
);
113+
});
114+
115+
afterEach(() => {
116+
expect(fetchCalls.filter((url) => routeOf(url) !== DRAFTS_ROUTE)).toEqual([]);
117+
// Unmount before restoring the real `fetch` (objectui#7439).
118+
cleanup();
119+
vi.unstubAllGlobals();
120+
});
121+
122+
const payload = (systemPermissions?: string[]): MePermissionsResponse =>
123+
({
124+
authenticated: true,
125+
userId: 'u1',
126+
tenantId: 'acme',
127+
roles: ['everyone'],
128+
permissionSets: ['member_default'],
129+
...(systemPermissions ? { systemPermissions } : {}),
130+
objects: {},
131+
fields: {},
132+
}) as MePermissionsResponse;
133+
134+
async function renderHome(permissions: MePermissionsResponse) {
135+
render(
136+
<MePermissionsProvider initialPermissions={permissions}>
137+
<HomePage />
138+
</MePermissionsProvider>,
139+
);
140+
await act(async () => {
141+
for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
142+
});
143+
}
144+
145+
const draftsReads = () => fetchCalls.filter((url) => routeOf(url) === DRAFTS_ROUTE);
146+
147+
describe('Home reads the drafts ledger only for a session it admits (objectstack-ai/objectstack#25894)', () => {
148+
it('a member holding none of the ledger capabilities: no `_drafts` read and no row', async () => {
149+
await renderHome(payload(['export_reports']));
150+
151+
expect(screen.getByRole('heading', { level: 1 }), 'Home never rendered: the harness is dead').toBeInTheDocument();
152+
expect(draftsReads()).toEqual([]);
153+
expect(screen.queryByTestId('home-pending-drafts')).toBeNull();
154+
});
155+
156+
it('a REPORTED empty set holds none of them either: no read', async () => {
157+
await renderHome(payload([]));
158+
159+
expect(draftsReads()).toEqual([]);
160+
});
161+
162+
it.each(['setup.access', 'studio.access', 'manage_metadata'])(
163+
'CONTROL: `%s` alone reads the ledger and shows the row',
164+
async (capability) => {
165+
await renderHome(payload([capability]));
166+
167+
expect(draftsReads()).toEqual([DRAFTS_ROUTE]);
168+
expect(await screen.findByTestId('home-pending-drafts')).toBeInTheDocument();
169+
},
170+
);
171+
172+
it('CONTROL: an unreported capability set fails OPEN and reads', async () => {
173+
await renderHome(payload(undefined));
174+
175+
expect(draftsReads()).toEqual([DRAFTS_ROUTE]);
176+
expect(await screen.findByTestId('home-pending-drafts')).toBeInTheDocument();
177+
});
178+
});

‎ui/packages/app-shell/src/console/home/__tests__/HomePage.greetingAndApps-12601.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ vi.mock('../../../context/NavigationContext', () => ({
107107
}));
108108
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({
109109
useCanAuthorMetadata: () => state.canAuthorMetadata,
110+
useCanReadPendingDrafts: () => true,
110111
}));
111112
// The page's one inbox seam: the approvals count AND whether it is an answer.
112113
vi.mock('../../../hooks/useHomeInbox', () => ({

‎ui/packages/app-shell/src/console/home/__tests__/HomePage.myWork-12602.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,10 @@ vi.mock('../../../providers/MetadataProvider', () => ({
105105
vi.mock('../../../context/NavigationContext', () => ({
106106
useNavigationContext: () => ({ currentAppName: 'crm' }),
107107
}));
108-
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true }));
108+
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({
109+
useCanAuthorMetadata: () => true,
110+
useCanReadPendingDrafts: () => true,
111+
}));
109112
// The page's one inbox seam: both sources, their answers and their read grants.
110113
vi.mock('../../../hooks/useHomeInbox', () => ({
111114
useHomeInbox: () => ({

‎ui/packages/app-shell/src/console/home/__tests__/HomePage.pendingDraftsPackageName-13136.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,10 @@ vi.mock('../../../providers/MetadataProvider', () => ({
8686
vi.mock('../../../context/NavigationContext', () => ({
8787
useNavigationContext: () => ({ currentAppName: 'crm' }),
8888
}));
89-
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true }));
89+
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({
90+
useCanAuthorMetadata: () => true,
91+
useCanReadPendingDrafts: () => true,
92+
}));
9093
vi.mock('../../../hooks/useHomeInbox', () => ({
9194
useHomeInbox: () => ({
9295
pendingApprovals: [],

‎ui/packages/app-shell/src/console/home/__tests__/HomePage.recentlyAccessed-12604.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ vi.mock('../../../context/NavigationContext', () => ({
101101
}));
102102
vi.mock('../../../hooks/useCanAuthorMetadata', () => ({
103103
useCanAuthorMetadata: () => state.canAuthorMetadata,
104+
useCanReadPendingDrafts: () => true,
104105
}));
105106
// The page's one inbox seam: the approvals count AND whether it is an answer.
106107
vi.mock('../../../hooks/useHomeInbox', () => ({

‎ui/packages/app-shell/src/hooks/useCanAuthorMetadata.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,26 @@ export function useCanReadAuthoringTrail(): boolean {
7373
const { hasCapabilities } = usePermissions();
7474
return AUTHORING_TRAIL_CAPABILITIES.some((capability) => hasCapabilities([capability]));
7575
}
76+
77+
/**
78+
* objectstack-ai/objectstack#25894 — the capabilities the pending-drafts ledger
79+
* (`GET /meta/_drafts`) admits. The door asks `mayReadPendingDrafts`, the
80+
* ADR-0106 D4 mask-exemption cohort (`OBJECT_SCHEMA_MASK_EXEMPT_CAPABILITIES`
81+
* in `@objectstack/metadata-core`): the write capability plus the two
82+
* read-only exemptions. Any ONE of them opens it. `system` is a principal
83+
* flag with no client half, as for the trail above.
84+
*/
85+
export const PENDING_DRAFTS_CAPABILITIES: readonly string[] = ['studio.access', 'setup.access', AUTHORING_CAPABILITY];
86+
87+
/**
88+
* May this session read the pending-drafts ledger?
89+
*
90+
* Asked by a surface that reads the ledger for whoever opens it (Home's drafts
91+
* row), so a member the door refuses is not sent a request that always answers
92+
* 403. Unknown fails OPEN, as {@link useCanAuthorMetadata} does: the server
93+
* enforces regardless.
94+
*/
95+
export function useCanReadPendingDrafts(): boolean {
96+
const { hasCapabilities } = usePermissions();
97+
return PENDING_DRAFTS_CAPABILITIES.some((capability) => hasCapabilities([capability]));
98+
}

‎ui/packages/app-shell/src/preview/DraftChangesPanel.tsx‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -580,13 +580,22 @@ function FieldRow({
580580
* answer carries a numeric `total`: with none, the choice names no number
581581
* rather than a guessed one. What the publish actually wrote is the door's
582582
* receipt, which the host reports.
583+
*
584+
* `classifying` (objectstack-ai/objectstack#25894): the panel's new-vs-update
585+
* reads are still in flight. A NEW entry has no published body, so its
586+
* published read is not sent: it could only answer 404, logged as a failed
587+
* request on the console for every draft-only item. The drill-in waits while
588+
* the entry is unclassified and the reads are pending; one whose read failed
589+
* (still unclassified once they settle) is read both ways, as before.
583590
*/
584591
function EntryDetail({
585592
entry,
593+
classifying = false,
586594
onCompared,
587595
backfill,
588596
}: {
589597
entry: DraftChangeEntry;
598+
classifying?: boolean;
590599
onCompared?: (unchanged: boolean) => void;
591600
backfill?: EntryBackfillControl;
592601
}) {
@@ -611,13 +620,21 @@ function EntryDetail({
611620
onComparedRef.current = onCompared;
612621
});
613622

623+
const isNew = entry.kind === 'new';
624+
const awaitingKind = entry.kind === undefined && classifying;
614625
useEffect(() => {
626+
if (awaitingKind) return;
615627
let cancelled = false;
616628
(async () => {
617629
try {
618630
const [published, draft] = await Promise.all([
619-
// A NEW item 404s on the published read — that's data, not an error.
620-
fetchItemBody(entry.type, entry.name, { packageId: entry.packageId, member: entry.member }),
631+
// A NEW item has no published body: not asked
632+
// (objectstack-ai/objectstack#25894). An item the
633+
// classification could not answer still 404s here when it is new —
634+
// that's data, not an error.
635+
isNew
636+
? null
637+
: fetchItemBody(entry.type, entry.name, { packageId: entry.packageId, member: entry.member }),
621638
fetchItemBody(entry.type, entry.name, {
622639
draft: true,
623640
packageId: entry.packageId,
@@ -639,7 +656,7 @@ function EntryDetail({
639656
return () => {
640657
cancelled = true;
641658
};
642-
}, [entry.type, entry.name, entry.packageId, entry.member]);
659+
}, [entry.type, entry.name, entry.packageId, entry.member, isNew, awaitingKind]);
643660

644661
// objectui#12929 — how many records the choice would reach: asked once per
645662
// object, and only where a choice is offered.
@@ -817,6 +834,14 @@ export function DraftChangesPanel({
817834
const { t, language } = useObjectTranslation();
818835
const [entries, setEntries] = useState<DraftChangeEntry[] | null>(null);
819836
const [error, setError] = useState<string | null>(null);
837+
/**
838+
* The new-vs-update reads of the latest load are in flight
839+
* (objectstack-ai/objectstack#25894): a drill-in holds its published read
840+
* until its entry is classified or they settle. Keyed by load generation, so
841+
* an earlier load settling late does not end a later one's.
842+
*/
843+
const [classifying, setClassifying] = useState(false);
844+
const loadGenRef = useRef(0);
820845
/**
821846
* Author-time security findings that the publish door would REFUSE
822847
* (`7a90afdf9`). Surfaced here, next to the button, so the refusal is
@@ -906,6 +931,8 @@ export function DraftChangesPanel({
906931
};
907932

908933
const load = useCallback(async () => {
934+
const gen = ++loadGenRef.current;
935+
setClassifying(true);
909936
setEntries(null);
910937
setError(null);
911938
setProblems([]);
@@ -983,6 +1010,8 @@ export function DraftChangesPanel({
9831010
]);
9841011
} catch (e) {
9851012
setError((e as Error).message);
1013+
} finally {
1014+
if (loadGenRef.current === gen) setClassifying(false);
9861015
}
9871016
}, [packageId, include]);
9881017

@@ -1183,6 +1212,7 @@ export function DraftChangesPanel({
11831212
<div className="border-t bg-muted/20">
11841213
<EntryDetail
11851214
entry={entry}
1215+
classifying={classifying}
11861216
onCompared={(same) => markCompared(key, same)}
11871217
backfill={backfillControl}
11881218
/>

0 commit comments

Comments
 (0)