Skip to content

Commit 70c3b1c

Browse files
fix(app-shell): a draft-only object's new or first-edited list view starts from its first five fields (#30507)
domain:ui#5 · os-sales · session_01L6bhgXNFpXQRAPXfpTaqkV <!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuT5kyf3nN85tsw9JVYCnhMd)_ Fixes #30317 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:Studio 界面里,一个还只是草稿的对象,第一次编辑它的默认列表视图、或用「新建视图」不选列时,视图现在从对象的前五个字段起步,和已发布对象一样;之前起步是零列。 - 为什么改:面板只从外壳的合并元数据里找对象定义来生成默认列,草稿对象不在其中,于是默认列为空:第一次编辑只写进作者刚加的那一列,新建视图一列都没有。 - 风险与回滚:只改 `useObjectListViewDraft` 的默认列这一段。合并元数据里找不到对象时,多读一次本包的草稿对象定义(`GET /meta/object/:name?preview=draft&package=`,字段选择器已在读同一个地址);已发布对象不多发请求;读失败或读不到时仍是空,和以前一样。回滚即还原本 PR。 - 先看:`ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.tsx` 里 `seedColumns` 上方新增的 `draftedDef` 一段。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/ObjectListViewInspector.draftObjectSeed-30317.test.tsx`,预期 4 个用例全绿;在 main 上同一文件 3 个失败。 - 需要你做的:无,席位落地。 ## What changes In Studio › Interfaces, `useObjectListViewDraft` seeds the columns of a list view created in the panel (the first edit of a view that does not exist yet, and New view with no columns picked) with `defaultListColumnsFromObject(objectDef, 5)`. `objectDef` came only from the shell's merged `metadata.objects`, which holds published objects, so on a draft-only object the seed was `[]`. - When the merged definition is missing, the hook now reads the object's drafted definition from this package through the same client with the drafts overlaid (`client.withPreviewDrafts(true).get('object', name, { packageId })`, the read `useObjectFields` already makes for the panel's field picker) and seeds from it. The answer is keyed on `[packageId, objectName]` and re-read after a publish. - A published object reads nothing new: the effect does not run while the merged definition is present. - A failed read, or a 404 (neither drafted nor published), seeds nothing, as before, and is never the panel's failure. - Nothing else in the hook changes: target resolution, the buffer load, the save and the view switcher are untouched, so the hunks stay away from PR #30401 and PR #30339, which edit other parts of this file. Changeset: `.changeset/30317-draft-only-object-view-seed.md`, `@object-ui/app-shell` patch. Branch: the harness-assigned `claude/project-thread-9n7hb1`, not `claude/issue-30317-*`; the card is #30317. ## Tests New file `ObjectListViewInspector.draftObjectSeed-30317.test.tsx`: the real hook over a real `MetadataClient`, whose transport is an in-memory server that serves `GET /meta/object/:name?preview=draft` in its envelope and 404 otherwise, and records the PUTs. - draft-only `acmetrial_deal` (absent from the merged metadata, a hidden field first): `seedColumns` is its first five visible fields, the canvas shows them, and the first edit (made as the panel makes it, adding `notes`) PUTs `view/acmetrial_deal.default` with those five plus `notes`; - New view (`createView` with a grid payload and no columns) PUTs `view/acmetrial_deal.open_deals` with the same five; - CONTROL: a published object seeds from the merged definition and no `GET /meta/object/...` is sent for it; - CONTROL: an object neither drafted nor published: one 404 read, seed `[]`, no failure, the buffer still loads. On `origin/main` (`989ae42d`) the file reads 3 failed, 1 passed (the seed is `[]`; the 404 control fails because no read is sent). With the fix, 4 passed. Since the pre-fix run is the same file over the unpatched hook, no separate ablation was run. <details><summary>Test runs and gates</summary> - At `0be094aa` (fix, before merging `main`): every app-shell test file importing `ObjectListViewInspector` or `StudioDesignSurface`, 241 files, `--maxWorkers=2`, under the verify lock: `Test Files 241 passed (241)`, `Tests 1751 passed (1751)`, VERDICT command-exit 0. eslint on the two touched files: 0 errors (22 warnings, all on lines this PR does not touch). - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `0be094aa` (3 paths): 35 commands, run serially, every one exit 0, including `pnpm --dir ui exec vitest run scripts/` (`Test Files 170 passed | 2 skipped (172)`, `Tests 4985 passed | 2 skipped`). `--ran` with the recorded exit codes: 35 derived, 35 run, 0 NOT-MEASURED (a derived zero). Also run: `pnpm --filter @object-ui/app-shell run type-check`, `pnpm --dir ui run check:spec-symbols`, `pnpm check:changeset-fixed`, each exit 0. - At `af914a2d` (after merging `main` `a1d0b1ee`, which carries PR #30339's edit of this file; no conflict; app-shell closure rebuilt): `pnpm --filter @object-ui/app-shell run type-check`, every test file under `packages/app-shell/src/views/studio-design/` (`Test Files 330 passed (330)`, `Tests 2473 passed (2473)`) and `pnpm --dir ui run check:spec-symbols`, one chained run, VERDICT command-exit 0. </details> Not run locally: the full ui suite (CI's Test UI shards run it). ## Verification Dev boot of `examples/app-showcase` (`objectstack dev --seed-admin --fresh`) after the `@object-ui/app-shell` and showcase build closure, console Vite pointed at it, Playwright Chromium at 1440×900, signed in as the dev admin. Seeded over REST: writable package `com.example.acme-trial` (`POST /api/v1/packages`), then with `?mode=draft` the object `acmetrial_deal` (fields name, amount, stage, close_date, probability, notes) and the app `acmetrial_app`, whose one nav entry is the object. Opened the entry in Studio › Interfaces. Before = `origin/main`'s hook; after = this branch's, served by Vite HMR; the view drafts were discarded (`DELETE …?state=draft`) between the two. | | Before | After | |:--|:--|:--| | Panel on opening the entry | "Columns 0 · No columns yet" | Columns 5: Deal name, Amount, Stage, Close date, Probability | | First edit (Add field → Notes) PUTs `view/acmetrial_deal.default` with columns | `[{ field: notes }]` | `[name, amount, stage, close_date, probability, notes]` | | New view (Grid, "Open deals", no columns picked) PUTs `view/acmetrial_deal.open_deals` with columns | `[]` | `[name, amount, stage, close_date, probability]` | Shots (1440 wide) and the recorded PUT bodies are in the project's `issue-30317/` folder (`before-1-opened-1440.png`, `before-2-first-edit-1440.png`, `before-3-new-view-1440.png`, the three `after-*` shots, `puts.json`); this repository has no place to commit them, per `ui/AGENTS.md` Housekeeping. ## Acceptance notes - The drafted read is asynchronous and is sent when the leaf opens, beside the view-drafts read that already gates a default entry. An edit made before it answers would still start from no columns; on the dev boot it answered before the panel finished loading. - The before leg's first edit wrote the column as `{ field, label }` and the after leg's as a bare name: the column editor keeps the shape of the list it is handed, and the seed is bare names, as it is for a published object today. Not changed here. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgXNFpXQRAPXfpTaqkV)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgXNFpXQRAPXfpTaqkV Co-authored-by: Claude <noreply@anthropic.com>
1 parent 400b41b commit 70c3b1c

3 files changed

Lines changed: 252 additions & 2 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(studio): on a draft-only object, a new or first-edited list view starts from the object's first five fields
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
In Studio Interfaces, a list view created on an object that so far exists only as a draft in the package started with no columns. The first edit of a default view that did not exist yet wrote only the column the author touched, and New view with no columns picked wrote none. The list-view panel seeded those columns from the shell's merged objects, which hold published objects only. When the merged definition is missing, the panel now reads the object's drafted definition from this package (`GET /meta/object/:name?preview=draft&package=`, the read the field picker already makes) and seeds from it, so both start from the same first five fields a published object gets. A published object reads nothing new. If the drafted read fails or finds nothing, the seed stays empty as before.
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#30317 — on a draft-only object, a list view created in Studio
5+
* Interfaces starts from the object's first five fields, as one of a
6+
* published object does.
7+
*
8+
* Measured on #30177's dev boot: the first edit of `acmetrial_deal.default`
9+
* (a draft-only object, no view yet) wrote `columns: [amount]`, the one
10+
* column the author touched, and New view fell back to the same empty seed.
11+
* The shell's merged `metadata.objects` holds published objects only, so the
12+
* hook found no definition to seed from. It now reads the object's drafted
13+
* definition through the same client with the drafts overlaid when the merged
14+
* one is missing.
15+
*
16+
* The REAL hook over a REAL `MetadataClient`, whose transport is an in-memory
17+
* server answering as the framework does (`GET /meta/object/<name>?preview=draft`
18+
* serves the pending draft in its envelope; 404 for a name with neither).
19+
*
20+
* Pinned:
21+
* - a draft-only object: the seed is its drafted definition's first five
22+
* fields, the first edit of the default view writes them plus the edit,
23+
* and New view with no columns picked writes them too;
24+
* - CONTROL: a published object seeds from the merged definition, and no
25+
* object read is sent for it;
26+
* - CONTROL: an object neither published nor drafted (404) seeds nothing and
27+
* the panel does not fail on it.
28+
*/
29+
30+
import '@testing-library/jest-dom/vitest';
31+
import * as React from 'react';
32+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
33+
import { act, cleanup, render } from '@testing-library/react';
34+
import { MetadataCtx, type MetadataContextValue } from '@object-ui/react';
35+
import { MetadataClient } from '@object-ui/data-objectstack';
36+
import { newListViewItem, useObjectListViewDraft, type DraftOnlyObjects, type ObjectListViewDraft } from './ObjectListViewInspector';
37+
import type { Surface } from './navSurface';
38+
39+
const PKG = 'com.example.acme-trial';
40+
const DEAL = 'acmetrial_deal';
41+
const CASE = 'acmetrial_case';
42+
const GHOST = 'acmetrial_ghost';
43+
44+
const dealDraft = {
45+
name: DEAL,
46+
label: 'Deal',
47+
fields: {
48+
internal_score: { name: 'internal_score', type: 'number', hidden: true },
49+
name: { name: 'name', type: 'text' },
50+
amount: { name: 'amount', type: 'currency' },
51+
stage: { name: 'stage', type: 'select' },
52+
close_date: { name: 'close_date', type: 'date' },
53+
probability: { name: 'probability', type: 'percent' },
54+
notes: { name: 'notes', type: 'textarea' },
55+
},
56+
};
57+
const DEAL_SEED = ['name', 'amount', 'stage', 'close_date', 'probability'];
58+
59+
const caseDef = {
60+
name: CASE,
61+
label: 'Case',
62+
fields: { subject: { name: 'subject', type: 'text' }, priority: { name: 'priority', type: 'select' } },
63+
};
64+
65+
const server = {
66+
objectDrafts: new Map<string, Record<string, unknown>>(),
67+
requests: [] as Array<{ method: string; path: string; search: string; status: number }>,
68+
writes: [] as Array<{ path: string; body: Record<string, unknown> }>,
69+
};
70+
71+
const json = (status: number, body: unknown) =>
72+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
73+
74+
async function serve(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
75+
const method = (init?.method ?? 'GET').toUpperCase();
76+
const url = new URL(String(input), 'http://studio.test');
77+
let status = 200;
78+
let body: unknown = [];
79+
const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/);
80+
if (meta) {
81+
const seg = meta[1].split('/').map(decodeURIComponent);
82+
if (method === 'PUT' && seg.length === 2) {
83+
server.writes.push({ path: `${seg[0]}/${seg[1]}`, body: JSON.parse(String(init?.body ?? '{}')) });
84+
body = { success: true, version: 'v2', state: 'draft' };
85+
} else if (seg.length === 1) {
86+
// `_drafts`, the published lists and the draft-overlaid lists: nothing pending, nothing published.
87+
body = [];
88+
} else if (seg.length === 2 && seg[0] === 'object') {
89+
const draft = url.searchParams.get('preview') === 'draft' ? server.objectDrafts.get(seg[1]) : undefined;
90+
if (draft) body = { type: 'object', name: seg[1], item: { ...draft, _draft: true } };
91+
else [status, body] = [404, { error: { code: 'NOT_FOUND', message: 'absent' } }];
92+
} else if (seg.length === 2) {
93+
[status, body] = [404, { error: { code: 'NO_DRAFT', message: 'absent' } }];
94+
}
95+
}
96+
server.requests.push({ method, path: url.pathname, search: url.search, status });
97+
return json(status, body);
98+
}
99+
100+
const client = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch });
101+
102+
// The shell's metadata cache holds published objects only: the draft-only one is absent.
103+
const METADATA: MetadataContextValue = {
104+
apps: [],
105+
objects: [caseDef],
106+
dashboards: [],
107+
reports: [],
108+
pages: [],
109+
loading: false,
110+
error: null,
111+
refresh: async () => {},
112+
invalidate: () => {},
113+
ensureType: async () => [],
114+
getItem: async () => null,
115+
getItemsByType: () => [],
116+
};
117+
118+
const known: DraftOnlyObjects = { publishNonce: 0, names: new Set([DEAL, GHOST]) };
119+
120+
let latest: ObjectListViewDraft | null = null;
121+
function HookProbe({ object }: { object: string }) {
122+
const leaf: Surface = { type: 'object', name: object, label: object };
123+
const d = useObjectListViewDraft({ client, packageId: PKG, leaf, publishNonce: 0, draftOnlyObjects: known });
124+
React.useLayoutEffect(() => {
125+
latest = d;
126+
});
127+
return null;
128+
}
129+
130+
const settle = () =>
131+
act(async () => {
132+
for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
133+
});
134+
135+
async function mount(object: string) {
136+
render(
137+
<MetadataCtx.Provider value={METADATA}>
138+
<HookProbe object={object} />
139+
</MetadataCtx.Provider>,
140+
);
141+
await settle();
142+
return () => latest!;
143+
}
144+
145+
/** The panel's first edit, as the panel makes it: one column added to the view it shows. */
146+
async function firstEdit(d: () => ObjectListViewDraft, column: string) {
147+
const { target, row, seedColumns } = d();
148+
const working = row ?? newListViewItem(target!, seedColumns);
149+
const config = working.config as Record<string, unknown>;
150+
await act(async () => {
151+
d().edit({ ...working, config: { ...config, columns: [...(config.columns as unknown[]), column] } });
152+
});
153+
await act(async () => {
154+
await d().save({ unmoved: () => true });
155+
});
156+
await settle();
157+
}
158+
159+
const objectReads = (name: string) =>
160+
server.requests.filter((r) => r.method === 'GET' && r.path === `/api/v1/meta/object/${name}`);
161+
162+
beforeEach(() => {
163+
server.objectDrafts.clear();
164+
server.requests = [];
165+
server.writes = [];
166+
latest = null;
167+
});
168+
afterEach(cleanup);
169+
170+
describe('useObjectListViewDraft — a draft-only object seeds a new view from its drafted definition (objectstack#30317)', () => {
171+
it('the first edit of the default view writes the drafted object\'s first five fields, then the edit', async () => {
172+
server.objectDrafts.set(DEAL, dealDraft);
173+
const d = await mount(DEAL);
174+
175+
expect(d().target).toEqual({ objectName: DEAL, viewId: `${DEAL}.default`, isDefault: true });
176+
expect(d().seedColumns).toEqual(DEAL_SEED);
177+
expect(d().canvas?.view).toMatchObject({ columns: DEAL_SEED });
178+
179+
await firstEdit(d, 'notes');
180+
expect(server.writes.map((w) => w.path)).toEqual([`view/${DEAL}.default`]);
181+
expect((server.writes[0]!.body.config as Record<string, unknown>).columns).toEqual([...DEAL_SEED, 'notes']);
182+
});
183+
184+
it('New view with no columns picked writes the drafted object\'s first five fields', async () => {
185+
server.objectDrafts.set(DEAL, dealDraft);
186+
const d = await mount(DEAL);
187+
188+
let refusal: unknown = 'pending';
189+
await act(async () => {
190+
refusal = await d().createView({ type: 'grid', label: 'Open deals', name: `${DEAL}.open_deals` });
191+
});
192+
expect(refusal).toBeNull();
193+
expect(server.writes.map((w) => w.path)).toEqual([`view/${DEAL}.open_deals`]);
194+
expect((server.writes[0]!.body.config as Record<string, unknown>).columns).toEqual(DEAL_SEED);
195+
});
196+
197+
it('CONTROL: a published object seeds from the merged definition, and no object read is sent for it', async () => {
198+
const d = await mount(CASE);
199+
200+
expect(d().seedColumns).toEqual(['subject', 'priority']);
201+
expect(objectReads(CASE)).toEqual([]);
202+
});
203+
204+
it('CONTROL: an object with neither a draft nor a published row seeds nothing, and the panel does not fail', async () => {
205+
const d = await mount(GHOST);
206+
207+
expect(objectReads(GHOST).map((r) => r.status)).toEqual([404]);
208+
expect(d().seedColumns).toEqual([]);
209+
expect(d().failure).toBeNull();
210+
expect(d().loadedFor).toBe(`listView:${GHOST}.default`);
211+
});
212+
});

‎ui/packages/app-shell/src/views/studio-design/ObjectListViewInspector.tsx‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@
3636
* packageId })`) under its own version guard (objectui#11773), debounced by the
3737
* pillar's autosave like every other Studio editor. A view that does not exist
3838
* yet is created by the first edit, seeded with the columns the running app
39-
* shows an object that has no view (`defaultListColumnsFromObject`).
39+
* shows an object that has no view (`defaultListColumnsFromObject`); for a
40+
* draft-only object, from this package's drafted definition (objectstack#30317).
4041
*
4142
* ## Switching views, and adding one
4243
*
@@ -567,7 +568,34 @@ export function useObjectListViewDraft({
567568
objectName && !holding ? listViewChoicesOf(objectName, publishedViews, draftViewRows, entryTarget, target) : [];
568569
const viewId = target?.viewId ?? '';
569570
const targetKey = viewId ? listViewBufferKey(viewId) : '';
570-
const seedColumns = React.useMemo(() => defaultListColumnsFromObject(objectDef, 5), [objectDef]);
571+
// objectstack#30317 — a draft-only object is absent from the merged
572+
// metadata, so the columns a view created here starts with are read off
573+
// this package's drafted definition, read with the drafts overlaid (the
574+
// read `useObjectFields` makes for the panel's field picker). Only when the
575+
// merged definition is missing; a failed or empty answer seeds nothing.
576+
const [draftedDef, setDraftedDef] = React.useState<{ for: string; def: Row | null }>({ for: '', def: null });
577+
const needsDraftedDef = !!objectName && !objectDef;
578+
React.useEffect(() => {
579+
if (!objectName || !needsDraftedDef) return;
580+
let cancelled = false;
581+
const forKey = JSON.stringify([packageId, objectName]);
582+
client
583+
.withPreviewDrafts(true)
584+
.get<Row>('object', objectName, { packageId })
585+
.then(
586+
(def) => {
587+
if (!cancelled) setDraftedDef({ for: forKey, def: isPlainObject(def) ? def : null });
588+
},
589+
() => {
590+
if (!cancelled) setDraftedDef({ for: forKey, def: null });
591+
},
592+
);
593+
return () => {
594+
cancelled = true;
595+
};
596+
}, [client, packageId, objectName, needsDraftedDef, publishNonce]);
597+
const seedDef = objectDef ?? (needsDraftedDef && draftedDef.for === viewDraftsKey ? draftedDef.def : undefined);
598+
const seedColumns = React.useMemo(() => defaultListColumnsFromObject(seedDef, 5), [seedDef]);
571599

572600
const [buffer, setBuffer] = React.useState<{
573601
for: string;

0 commit comments

Comments
 (0)