Skip to content

Commit 60a4b3b

Browse files
committed
fix(app-shell): the view panel's read-only verdict is the one that drew its Manage views row
The panel read a second, per-view package verdict that answers "not read-only" until its own read settles. A shipped row's "View config" opened from another package's view could draw an editable frame, and a verdict landing after an edit stranded that edit with no Discard. - ObjectView judges the panel from the same refusingPackages set the rows are flagged from, for the open view and for the view the panel was opened for (the view switch lands in a transition, after the panel opens). - ViewConfigPanel discards unsaved edits when it turns read-only: the list's preview is restored and the panel shows the stored view. - usePackagesRefusingSaves keeps each package's answer as it lands, so a change to the list of ids never makes an open panel savable again. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv
1 parent eb72cf0 commit 60a4b3b

6 files changed

Lines changed: 170 additions & 40 deletions

File tree

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

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
* @module
7878
*/
7979

80-
import { useEffect, useState } from 'react';
80+
import { useEffect, useMemo, useState } from 'react';
8181
import { useAuth, useWorkspaceAdminStatus } from '@object-ui/auth';
8282
import { useCanAuthorMetadata } from './useCanAuthorMetadata.js';
8383
import { fetchSessionPackages, type PkgEntry } from '../views/studio-design/packages-io.js';
@@ -214,39 +214,50 @@ const NO_REFUSING_PACKAGES: ReadonlySet<string> = new Set();
214214
* objectstack#35974 — {@link usePackageRefusesSaves} for a list of packages
215215
* at once, for a surface that draws one row per view (Manage views): the ids
216216
* among `packageIds` the package list carries as read-only. The same
217-
* `writable` verdict, the same session-held read (one request, answered per id
218-
* by `fetchSessionPackages`) and the same fail-open: an id still being read, an
217+
* `writable` verdict, the same session-held read (`fetchSessionPackages`: at
218+
* most one `GET /api/v1/packages` per new package id per session, concurrent
219+
* asks sharing it) and the same fail-open: an id still being read, an
219220
* id whose read failed and an id the list leaves out are not in the answer, so
220221
* that row keeps what it offered before this read.
221222
*
222223
* Keyed on the ids themselves, never on the array's identity: callers may hand
223-
* a fresh array each render.
224+
* a fresh array each render. Each id's answer is kept for the session as it
225+
* lands, so a change to the list of ids (a refetch that brings a view of a new
226+
* package) never takes back what is already known: a surface reading this
227+
* while open, such as the view panel, cannot flip back to savable.
224228
*/
225229
export function usePackagesRefusingSaves(packageIds: readonly string[]): ReadonlySet<string> {
226230
const session = usePackageListSession();
227231
const key = JSON.stringify([...new Set(packageIds)].sort());
228-
const [verdict, setVerdict] = useState<{
229-
key: string;
232+
const [answers, setAnswers] = useState<{
230233
session: string;
231-
refusing: ReadonlySet<string>;
234+
refuses: ReadonlyMap<string, boolean>;
232235
} | null>(null);
233236
useEffect(() => {
234237
const ids = JSON.parse(key) as string[];
235-
if (ids.length === 0) return undefined;
236238
let cancelled = false;
237-
void Promise.allSettled(ids.map((id) => fetchSessionPackages(session, id))).then((answers) => {
238-
if (cancelled) return;
239-
const refusing = new Set<string>();
240-
answers.forEach((answer, i) => {
241-
if (answer.status === 'fulfilled' && packageStudioPosture(answer.value, ids[i]) === 'view') {
242-
refusing.add(ids[i]);
243-
}
239+
for (const id of ids) {
240+
fetchSessionPackages(session, id).then((list) => {
241+
if (cancelled) return;
242+
const refuses = packageStudioPosture(list, id) === 'view';
243+
setAnswers((prev) => {
244+
const known = prev && prev.session === session ? prev.refuses : new Map<string, boolean>();
245+
if (known.get(id) === refuses) return prev;
246+
const next = new Map(known);
247+
next.set(id, refuses);
248+
return { session, refuses: next };
249+
});
250+
}, () => {
251+
// A failed read answers nothing: the id keeps what it offered.
244252
});
245-
setVerdict({ key, session, refusing });
246-
});
253+
}
247254
return () => {
248255
cancelled = true;
249256
};
250257
}, [key, session]);
251-
return verdict && verdict.key === key && verdict.session === session ? verdict.refusing : NO_REFUSING_PACKAGES;
258+
return useMemo(() => {
259+
if (!answers || answers.session !== session) return NO_REFUSING_PACKAGES;
260+
const refusing = (JSON.parse(key) as string[]).filter((id) => answers.refuses.get(id) === true);
261+
return refusing.length === 0 ? NO_REFUSING_PACKAGES : new Set(refusing);
262+
}, [answers, key, session]);
252263
}

‎ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
*
1313
* The verdict is objectstack#35933's: the package the row was served under
1414
* (`listViews()` carries `_packageId`) and the session-held package list
15-
* (`fetchSessionPackages`), stubbed here.
15+
* (`fetchSessionPackages`), stubbed here. The panel's read-only verdict is
16+
* the very answer that drew the row (`usePackagesRefusingSaves`), so the two
17+
* cannot disagree, and that answer is kept per package as it lands.
1618
*
1719
* What runs: the real `ObjectView` on a stub data source. `ListView` is a
1820
* stand-in (the list itself is not under test). The real `ManageViewsDialog`
@@ -93,11 +95,12 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => {
9395
};
9496
});
9597

96-
/** The props the view panel was last handed. */
97-
const panelProps = vi.hoisted(() => ({ current: null as Record<string, any> | null }));
98+
/** The props the view panel was last handed, and every render's, in order. */
99+
const panelProps = vi.hoisted(() => ({ current: null as Record<string, any> | null, renders: [] as Record<string, any>[] }));
98100
vi.mock('./ViewConfigPanel', () => ({
99101
ViewConfigPanel: (props: any) => {
100102
panelProps.current = props;
103+
panelProps.renders.push(props);
101104
return null;
102105
},
103106
}));
@@ -111,6 +114,7 @@ vi.mock('./studio-design/packages-io', async (importOriginal) => ({
111114

112115
import { ObjectView } from './ObjectView';
113116
import { ExpressionProvider } from '../providers/ExpressionProvider';
117+
import { usePackagesRefusingSaves } from '../hooks/useStudioDesignGate';
114118

115119
const OBJECT = 'showcase_task';
116120
const SHIPPED_PACKAGE = 'com.example.showcase';
@@ -216,6 +220,7 @@ async function clickConfig(id: string) {
216220

217221
beforeEach(() => {
218222
panelProps.current = null;
223+
panelProps.renders = [];
219224
packageList.answer = () => Promise.resolve(PACKAGES);
220225
localStorage.clear();
221226
});
@@ -244,6 +249,21 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
244249
expect(panelProps.current?.mode).toBe('edit');
245250
});
246251

252+
it('"View config" on a shipped row while another package\'s view is open: no render of the open panel is editable', async () => {
253+
mount(CUSTOM.name);
254+
await settle();
255+
await waitFor(async () => expect((await rowOffers(SHIPPED.name)).configLabel).toBe('View config'));
256+
const before = panelProps.renders.length;
257+
await clickConfig(SHIPPED.name);
258+
await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name));
259+
await waitFor(() => expect(panelProps.current?.open).toBe(true));
260+
const opened = panelProps.renders.slice(before).filter((props) => props.open);
261+
expect(opened.length).toBeGreaterThan(0);
262+
// The first render after the click already reads the row's own verdict:
263+
// no switch-first answer for the newly open view is waited for.
264+
expect(opened.map((props) => props.readOnly)).toEqual(opened.map(() => true));
265+
});
266+
247267
it('the custom row\'s "Edit view config" opens the panel savable', async () => {
248268
mount(SHIPPED.name);
249269
await settle();
@@ -296,3 +316,27 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o
296316
expect(panelProps.current?.readOnly).toBe(false);
297317
});
298318
});
319+
320+
describe('objectstack#35974 — the verdict is kept per package as it lands', () => {
321+
function Probe({ ids }: { ids: string[] }) {
322+
const refusing = usePackagesRefusingSaves(ids);
323+
return <span data-testid="refusing">{[...refusing].sort().join(',')}</span>;
324+
}
325+
326+
it('a new package id joining the list takes back none of what is known', async () => {
327+
const pending: Array<(rows: any[]) => void> = [];
328+
packageList.answer = () => Promise.resolve(PACKAGES);
329+
const view = render(<Probe ids={[SHIPPED_PACKAGE]} />);
330+
await waitFor(() => expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE));
331+
// A refetch brings a view of a package whose answer is still on the wire.
332+
packageList.answer = () => new Promise<any[]>((resolve) => { pending.push(resolve); });
333+
view.rerender(<Probe ids={[SHIPPED_PACKAGE, 'com.example.other']} />);
334+
expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE);
335+
await settle();
336+
expect(screen.getByTestId('refusing').textContent).toBe(SHIPPED_PACKAGE);
337+
expect(pending.length).toBeGreaterThan(0);
338+
const rows = [...PACKAGES, { id: 'com.example.other', name: 'Other', writable: false }];
339+
await act(async () => { pending.forEach((resolve) => resolve(rows)); });
340+
await waitFor(() => expect(screen.getByTestId('refusing').textContent).toBe(`com.example.other,${SHIPPED_PACKAGE}`));
341+
});
342+
});

‎ui/packages/app-shell/src/views/ObjectView.tsx‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,7 +1020,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
10201020

10211021
// objectstack#27594: the list title is the view switcher, which replaced the
10221022
// view tab strip; the view items `ManageViewsDialog` lists come with it.
1023-
const { viewTabItems, titleSwitcher } = useObjectViewTitleSwitcher({
1023+
const { viewTabItems, titleSwitcher, refusingPackages } = useObjectViewTitleSwitcher({
10241024
views,
10251025
savedViews,
10261026
objectDef,
@@ -1061,6 +1061,28 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
10611061
onDeletePersonalView: personalViewsReady ? (id: string) => { void handleDeletePersonalView(id); } : undefined,
10621062
});
10631063

1064+
// objectstack#35974 — the view panel is read-only on a view a read-only
1065+
// package ships, judged from the SAME answer that drew its Manage views
1066+
// row (`refusingPackages`), so the row's "View config" never opens an
1067+
// editable panel. The view it was opened for counts as well as the open
1068+
// one: a row of another view switches views in a transition, and the
1069+
// panel opens before the switch lands.
1070+
const [configTargetId, setConfigTargetId] = useState<string | null>(null);
1071+
useEffect(() => {
1072+
if (!showViewConfigPanel) setConfigTargetId(null);
1073+
}, [showViewConfigPanel]);
1074+
const viewRefusesSaves = (id: string | null | undefined): boolean => {
1075+
if (!isAdmin || !id) return false;
1076+
const packageId = studioPackageId(savedViews.find((sv: any) => viewRowId(sv) === id));
1077+
return packageId !== null && refusingPackages.has(packageId);
1078+
};
1079+
const viewConfigPanelReadOnly = viewConfigPanelMode === 'edit'
1080+
&& (viewRefusesSaves(activeView?.id) || viewRefusesSaves(configTargetId));
1081+
const handleConfigViewFromRow = (id: string) => {
1082+
setConfigTargetId(id);
1083+
handleConfigView(id);
1084+
};
1085+
10641086
// objectstack#35878 — the page bar's props, for the view bar's right end
10651087
// (`viewBarTrailing` below). Filled on every render once the header chrome
10661088
// is known; the end reads it when it draws, after this render.
@@ -1402,7 +1424,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
14021424
onSetPinned={handlePinView}
14031425
onReorder={handleReorderViews}
14041426
onAddView={handleAddView}
1405-
onConfigView={handleConfigView}
1427+
onConfigView={handleConfigViewFromRow}
14061428
/>
14071429
)}
14081430

@@ -1448,7 +1470,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
14481470
metadataClient={metadataClient}
14491471
dataSource={dataSource}
14501472
onAfterChange={() => setRefreshKey(k => k + 1)}
1451-
readOnly={viewConfigPanelMode === 'edit' && activeViewPackageRefusesSaves}
1473+
readOnly={viewConfigPanelReadOnly}
14521474
/>
14531475
</Suspense>
14541476
</div>

‎ui/packages/app-shell/src/views/ViewConfigPanel.test.tsx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ vi.mock('./metadata-admin/inspectors/ViewVariantInspector', () => ({
2424
type="button"
2525
data-testid="mock-inspector-edit"
2626
data-readonly={String(!!readOnly)}
27+
data-columns={JSON.stringify(draft?.config?.columns ?? null)}
2728
onClick={() =>
2829
onPatch({ config: { ...(draft?.config ?? {}), columns: ['a', 'b', 'c'] } })
2930
}
@@ -119,6 +120,45 @@ describe('ViewConfigPanel — read-only (objectstack#35974)', () => {
119120
expect(props.onSave).not.toHaveBeenCalled();
120121
});
121122

123+
it('a verdict that lands after an edit: the edit is discarded, the panel stays open and shows the view', () => {
124+
const props = makeProps({ mode: 'edit' });
125+
const view = render(<ViewConfigPanel {...props} />);
126+
const opened = screen.getByTestId('mock-inspector-edit').getAttribute('data-columns');
127+
128+
// Opened editable while the package list was still being read; edited.
129+
fireEvent.click(screen.getByTestId('mock-inspector-edit'));
130+
expect(props.onViewUpdate).toHaveBeenCalledWith('columns', ['a', 'b', 'c']);
131+
expect(screen.getByTestId('mock-inspector-edit').getAttribute('data-columns')).not.toBe(opened);
132+
props.onViewUpdate.mockClear();
133+
134+
// The read-only verdict lands.
135+
view.rerender(<ViewConfigPanel {...props} readOnly />);
136+
137+
// The host's list is told to restore the opening view, as Discard would.
138+
expect(props.onViewUpdate).toHaveBeenCalledWith('columns', ['a', 'b']);
139+
expect(props.onViewUpdate).not.toHaveBeenCalledWith('columns', ['a', 'b', 'c']);
140+
// The panel shows the view, not the edit, and stays open, read-only.
141+
expect(screen.getByTestId('mock-inspector-edit').getAttribute('data-columns')).toBe(opened);
142+
expect(screen.getByTestId('mock-inspector-edit').getAttribute('data-readonly')).toBe('true');
143+
expect(screen.queryByTestId('view-config-discard')).toBeNull();
144+
expect(screen.queryByTestId('view-config-save')).toBeNull();
145+
expect(props.onClose).not.toHaveBeenCalled();
146+
147+
// Nothing more is relayed: a later edit is taken by no one.
148+
props.onViewUpdate.mockClear();
149+
fireEvent.click(screen.getByTestId('mock-inspector-edit'));
150+
expect(props.onViewUpdate).not.toHaveBeenCalled();
151+
expect(props.onSave).not.toHaveBeenCalled();
152+
});
153+
154+
it('a verdict that lands before any edit relays nothing', () => {
155+
const props = makeProps({ mode: 'edit' });
156+
const view = render(<ViewConfigPanel {...props} />);
157+
view.rerender(<ViewConfigPanel {...props} readOnly />);
158+
expect(props.onViewUpdate).not.toHaveBeenCalled();
159+
expect(screen.getByTestId('mock-inspector-edit').getAttribute('data-readonly')).toBe('true');
160+
});
161+
122162
it('a savable view (the default) keeps its editable controls, Save, Discard and the draft bar', () => {
123163
const props = makeProps({ mode: 'edit' });
124164
render(<ViewConfigPanel {...props} />);

‎ui/packages/app-shell/src/views/ViewConfigPanel.tsx‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -351,24 +351,37 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje
351351
// reach the list only through `onViewUpdate` (see `handlePatch`), so we
352352
// replay the panel's opening values — and clear any keys the edits
353353
// introduced — through the same seam, then reset the local draft.
354-
const handleDiscard = useCallback(() => {
355-
if (mode === 'edit') {
356-
if (onViewUpdate) {
357-
const original = inspectorDraftToRuntimeView(openingDraft);
358-
const edited = inspectorDraftToRuntimeView(draftRef.current);
359-
const fields = new Set([...Object.keys(edited), ...Object.keys(original)]);
360-
for (const field of fields) {
361-
if (field === 'id') continue;
362-
onViewUpdate(field, original[field]);
363-
}
354+
const revertEdits = useCallback(() => {
355+
if (onViewUpdate) {
356+
const original = inspectorDraftToRuntimeView(openingDraft);
357+
const edited = inspectorDraftToRuntimeView(draftRef.current);
358+
const fields = new Set([...Object.keys(edited), ...Object.keys(original)]);
359+
for (const field of fields) {
360+
if (field === 'id') continue;
361+
onViewUpdate(field, original[field]);
364362
}
365-
draftRef.current = initialDraft;
366-
relayedRef.current = new Set();
367-
setDraft(initialDraft);
368-
setIsDirty(false);
369363
}
364+
draftRef.current = initialDraft;
365+
relayedRef.current = new Set();
366+
setDraft(initialDraft);
367+
setIsDirty(false);
368+
}, [initialDraft, openingDraft, onViewUpdate]);
369+
const handleDiscard = useCallback(() => {
370+
if (mode === 'edit') revertEdits();
370371
onClose();
371-
}, [initialDraft, openingDraft, mode, onClose, onViewUpdate]);
372+
}, [mode, onClose, revertEdits]);
373+
374+
// objectstack#35974 — the host's read-only verdict can land after the
375+
// panel opened editable (the package list was still being read) and after
376+
// an edit. A read-only panel offers no Discard, so the edit would be
377+
// stranded on the host's list and shown here in place of the stored view.
378+
// It is discarded instead, the panel staying open.
379+
const wasReadOnlyRef = useRef(readOnly);
380+
useEffect(() => {
381+
const turnedReadOnly = readOnly && !wasReadOnlyRef.current;
382+
wasReadOnlyRef.current = readOnly;
383+
if (turnedReadOnly && mode === 'edit' && (isDirty || relayedRef.current.size > 0)) revertEdits();
384+
}, [readOnly, mode, isDirty, revertEdits]);
372385

373386
// A publish or a discard from the draft bar changes what is stored: the
374387
// buffer is read again (objectstack#35054), then the host refreshes.

‎ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,5 +430,5 @@ export function useObjectViewTitleSwitcher({
430430
/>
431431
) : null;
432432

433-
return { viewTabItems, titleSwitcher, titleLabel };
433+
return { viewTabItems, titleSwitcher, titleLabel, refusingPackages };
434434
}

0 commit comments

Comments
 (0)