Skip to content

Commit 942ffb2

Browse files
fix(app-shell): an edit a Studio pillar holds unsent guards departure like a dirty pillar (#26839)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8WL2sva4QpvpyNanwaBxGsw)_ Fixes #26705 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:Studio 把「暂存未发的编辑」(还不能保存的字段、步骤、组件)也算作未保存工作;离开支柱、刷新页面、在左侧栏切换到别的对象/流程/页面时,会先弹出与 Access 相同的确认框。 - 为什么改:之前 Data、Automations、Interfaces 支柱暂存的编辑只拦发布,不拦离开,一次误点就静默丢失;分诊裁决是「confirm 加 beforeunload,共用一个守卫」。 - 风险与回滚:只多问一句,不改保存与发布逻辑;暂存与否沿用已有判定。有问题直接 revert 本 PR。 - 先看:`StudioDesignSurface.tsx` 里的 `confirmDropUnsavedWork` 和 `unsavedPillarWork`,然后三处左侧栏 onClick / onPick 的守卫行,最后 `StudioDesignSurface.heldDataLeave-26705.test.tsx`。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataLeave-26705.test.tsx`,预期 4 个测试全绿。 - 需要你做的:无,席位落地。 ## What changes Base `607d3bb1`, then `origin/main` `55b5042e` merged in (no conflict; nothing it brought touches these files). Then `d33bfcf7`: the zh catalogue preload in two metadata-admin suites (test-only, scope widened by the seat, Claim 6452362760). One shared guard, read by every departure that drops a pillar's buffer: - **`confirmDropUnsavedWork(unsaved, locale)`**, a module function beside `useHeldEditReport`: the one question (`engine.edit.unsavedLeaveConfirm`, the text Access already asks) or `true` when nothing would be lost. Access's own `confirmDiscardEdits` now calls it too, so the question has one spelling. - **Surface:** `heldEdit` moves up beside `pillarDirty`, and `unsavedPillarWork = pillarDirty || heldEdit !== null` replaces `pillarDirty` in `confirmLeavePillar`, the `beforeunload` effect and `useRegisterUnsavedEdits`. That covers the pillar links (the shell seam's link guard asks while registered), Home, the package switcher, the cross-pillar `?surface=` request, Create app, the shell's own departures and reload. Pillars already take their held report back on unmount, so a confirmed leave clears the guard. - **Rail item switch** (a pillar-local path the surface cannot see; another item's load replaces the one buffer the held edit lives in): the Data object rail asks on `objHeld`, the Automations flow rail on `flowHeld`, the Interfaces nav rail on `leafHeld`. Re-picking the open item (same object, same flow, an entry for the same leaf) drops nothing and asks nothing, mirroring Access's rail. - Unchanged by design: how a held edit is judged and saved, and Publish's refusal while one is held. ## Why Triage first grade on the card, verbatim: "Guard departure the way the Access pillar and the Interfaces navigation already do (confirm plus `beforeunload`), with one shared guard." A held edit lives only in the pillar's buffer, so before this change one stray click dropped a half-added field, step or widget that the strip had just promised was "kept here". ## Tests Three new files, one per pillar, each through the real `StudioDesignSurface` on the real route shape (the held edit is produced the way an author does it: a Picklist with no option, a Notify step with no Title, a Metric widget with no dataset): - `StudioDesignSurface.heldDataLeave-26705.test.tsx`, `StudioDesignSurface.heldFlowLeave-26705.test.tsx`, `StudioDesignSurface.heldWidgetLeave-26705.test.tsx`, four cases each: leaving the pillar asks (Cancel keeps the held edit, OK leaves, and walking back asks nothing); the rail switch asks (Cancel keeps it, re-picking the open item asks nothing, OK opens the other item and the hold is gone); a reload asks only once the edit is held; and the CONTROL: with nothing held, the rail, the reload and the pillar link never ask. <details><summary>Runs</summary> - New files: 3 files, 12/12 passed (lock VERDICT command-exit 0). - `pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/ packages/app-shell/src/chrome/`: 244 files, 1773/1773 passed, exit 0 (pre-merge head `d2e66f47`). - After merging `origin/main`: the three new files plus `pillarNavGuard`, `heldPublish-11786`, `heldWidgetPublish-11910`, re-run on the merge head `b8d23d79`: 6 files, 28/28 passed, exit 0. - Two metadata-admin suites, `ResourceEditPage.discardDraftLabel-12690` and `PackageFormDialog.validationTiming`, now load the zh studio catalogue at module scope (`await loadStudioCatalogue('zh')`), as other zh-reading suites do since the studio namespace became lazy (#25922). The first went red on `Test UI` at `0a856a7d`. With the zh catalogue held back 4 s, each is red without its preload (1/3, 3/5) and green with it (3/3, 5/5). - `pnpm --filter @object-ui/app-shell type-check`: exit 0. </details> <details><summary>Ablation (one-shot, through scripts/ablation-replace.mjs; each leg restored to the HEAD blob with an empty git diff HEAD)</summary> - Leg A, drop the held term from the surface (`unsavedPillarWork = pillarDirty`): 6 of 12 red, exactly the leave and reload cases of all three pillars; the rail and control cases stay green. - Leg B, drop the held term from each rail guard (replace `objHeld !== null` / `flowHeld !== null` / `leafHeld !== null` with `false`): each pillar's rail-switch case red (1 of 4 per file), nothing else. </details> ## Acceptance notes - Not guarded, measured and left as they were: creating a new object, flow or Interfaces item while another item's edit is held opens the new item (the create has already been written), and a same-pillar `?surface=` request from the pending-changes sheet opens the requested item without asking. Both drop the held edit the same way a rail switch did. The card names leaving the pillar, the rail switch and reload; these two are left for a follow-up if wanted. - Browser Back/Forward is still not vetoed, as the shell seam's docblock already states for every page. - `@object-ui/app-shell` is `private: true`, so no changeset. ## Verification Gates derived by `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 24 families, all run, reconciled with `--ran` (24 run, 0 NOT-MEASURED). `pnpm --dir ui exec vitest run scripts/` reported one timeout in `check-vi-mock-inherit.test.ts` (15 s, shared box under load) and passed 83/83 when that file was re-run alone. `pnpm check:new-line-citations` (ui): 0 new citations. ## 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. (eslint on the four files: 0 errors; `StudioDesignSurface.tsx` carries the same 16 warnings as on the base, the three tests none.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. (Publishes nothing: `@object-ui/app-shell` is private.) - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [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, apart from the maintainer brief above. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbZJiPgbGWj5B2jNkYx)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1d7816d commit 942ffb2

6 files changed

Lines changed: 773 additions & 18 deletions

‎ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.validationTiming.test.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ import * as React from 'react';
2020
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2121
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
2222
import { PackageFormDialog } from './PackageFormDialog';
23+
// The package form rows this suite reads in zh live in `@object-ui/i18n`'s `studio`
24+
// namespace, whose `zh` catalogue is fetched on demand (objectstack#25922).
25+
// Resident before any case, so the zh rows below read synchronously.
26+
import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio';
27+
await loadStudioCatalogue('zh');
2328

2429
let localeFixture: 'en-US' | 'zh-CN' = 'zh-CN';
2530
vi.mock('./i18n', async (importOriginal) => ({

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.discardDraftLabel-12690.test.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ import { MetadataResourceEditPage } from './ResourceEditPage';
103103
import { registerDefaultMetadataSchemas } from './default-schemas';
104104
import { registerBuiltinPreviews } from './previews';
105105
import { tFormat } from './i18n';
106+
// The editor rows this suite reads in zh live in `@object-ui/i18n`'s `studio`
107+
// namespace, whose `zh` catalogue is fetched on demand (objectstack#25922).
108+
// Resident before any case, so the zh rows below read synchronously.
109+
import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio';
110+
await loadStudioCatalogue('zh');
106111

107112
const DOC_JSON_SCHEMA = z.toJSONSchema(DocSchema as unknown as z.ZodType) as Record<string, unknown>;
108113
client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch });
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#26705 — an edit the Data pillar holds unsent is unsaved work:
5+
* every departure that would drop it asks first.
6+
*
7+
* The autosave holds a Picklist added before it has an option
8+
* (objectui#11786). Before this card only Publish read that hold; leaving the
9+
* pillar, opening another object in the rail or reloading dropped the field
10+
* with no question. Now the surface folds the held edit into the guard a dirty
11+
* pillar already raises (the leave confirm, the shell's link guard and
12+
* `beforeunload`), and the rail asks before it opens another object.
13+
*
14+
* Rendered through the REAL `StudioDesignSurface` on the real route shape; the
15+
* field is added the way the pillar offers it (`dataPillarAddField`).
16+
*/
17+
18+
import '@testing-library/jest-dom/vitest';
19+
import * as React from 'react';
20+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
21+
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
22+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
23+
24+
const PKG = 'com.acme.app';
25+
26+
const OBJECTS: Record<string, Record<string, unknown>> = {
27+
acme_task: { name: 'acme_task', label: 'Task', fields: [{ name: 'title', label: 'Title', type: 'text' }] },
28+
acme_note: { name: 'acme_note', label: 'Note', fields: [{ name: 'body', label: 'Body', type: 'text' }] },
29+
};
30+
31+
const mockClient = vi.hoisted(() => ({
32+
list: vi.fn(async (_type: string) => [] as unknown[]),
33+
listDrafts: vi.fn(async () => []),
34+
listTypes: vi.fn(async () => ({ entries: [] })),
35+
get: vi.fn(async () => null),
36+
references: vi.fn(async () => []),
37+
layered: vi.fn(async (_type: string, _name: string) => ({ code: null, overlay: null, overlayScope: null, effective: null as unknown })),
38+
getDraft: vi.fn(async () => null),
39+
save: vi.fn(async () => ({ success: true })),
40+
publishDraft: vi.fn(async () => ({ success: true })),
41+
publishPackageDrafts: vi.fn(async () => ({ success: true, failed: [] })),
42+
publish: vi.fn(async () => ({ success: true })),
43+
reset: vi.fn(async () => ({})),
44+
}));
45+
46+
vi.mock('../metadata-admin/useMetadata', async (importOriginal) => {
47+
const mod = await importOriginal<typeof import('../metadata-admin/useMetadata')>();
48+
return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) };
49+
});
50+
51+
vi.mock('./packages-io', async (importOriginal) => {
52+
const mod = await importOriginal<typeof import('./packages-io')>();
53+
return {
54+
...mod,
55+
fetchPackages: vi.fn(async () => [{ id: 'com.acme.app', name: 'Acme', writable: true, namespace: 'acme' }]),
56+
};
57+
});
58+
59+
vi.mock('@object-ui/react', async (importOriginal) => {
60+
const mod = await importOriginal<typeof import('@object-ui/react')>();
61+
return { ...mod, useAdapter: () => dataSource };
62+
});
63+
64+
vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null }));
65+
vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null }));
66+
67+
import { StudioDesignSurface } from './StudioDesignSurface';
68+
import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField';
69+
import { createEmptyDataSource } from './__tests__/emptyDataSource';
70+
import { registerBuiltinInspectors } from '../metadata-admin/inspectors';
71+
import { t } from '../metadata-admin/i18n';
72+
73+
const dataSource = createEmptyDataSource();
74+
registerBuiltinInspectors();
75+
76+
vi.stubGlobal(
77+
'fetch',
78+
vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })),
79+
);
80+
81+
window.matchMedia = ((query: string) => ({
82+
matches: false,
83+
media: query,
84+
onchange: null,
85+
addEventListener: () => {},
86+
removeEventListener: () => {},
87+
addListener: () => {},
88+
removeListener: () => {},
89+
dispatchEvent: () => false,
90+
})) as unknown as typeof window.matchMedia;
91+
(globalThis as { ResizeObserver?: unknown }).ResizeObserver =
92+
(globalThis as { ResizeObserver?: unknown }).ResizeObserver ??
93+
class {
94+
observe() {}
95+
unobserve() {}
96+
disconnect() {}
97+
};
98+
99+
// This jsdom environment ships no window.confirm — install a mock outright.
100+
let confirmSpy: ReturnType<typeof vi.fn>;
101+
const LEAVE_QUESTION = t('engine.edit.unsavedLeaveConfirm', 'en');
102+
103+
beforeEach(() => {
104+
for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear();
105+
mockClient.list.mockImplementation(async (type: string) =>
106+
type === 'object' ? Object.values(OBJECTS).map((o) => ({ name: o.name, label: o.label, _packageId: PKG })) : [],
107+
);
108+
mockClient.layered.mockImplementation(async (type: string, name: string) => ({
109+
code: null,
110+
overlay: null,
111+
overlayScope: null,
112+
effective: type === 'object' && OBJECTS[name] ? JSON.parse(JSON.stringify(OBJECTS[name])) : null,
113+
}));
114+
confirmSpy = vi.fn();
115+
window.confirm = confirmSpy as unknown as typeof window.confirm;
116+
});
117+
118+
afterEach(() => {
119+
cleanup();
120+
localStorage.clear();
121+
window.history.replaceState(null, '', '/');
122+
});
123+
124+
/** The object the header names: its api-name chip. */
125+
async function openObjectIs(name: string): Promise<void> {
126+
await waitFor(
127+
() => expect(within(screen.getByTestId('data-object-header')).getByTestId('studio-item-api-name')).toHaveTextContent(name),
128+
{ timeout: 8000 },
129+
);
130+
}
131+
132+
async function openTask(): Promise<void> {
133+
// The shell's link guard reads the window's URL to skip a link to the page
134+
// already shown; `BrowserRouter` keeps the two equal, so this does too.
135+
window.history.replaceState(null, '', `/studio/${PKG}/data`);
136+
render(
137+
<MemoryRouter initialEntries={[`/studio/${PKG}/data`]}>
138+
<Routes>
139+
<Route path="/studio/:packageId/:tab" element={<StudioDesignSurface />} />
140+
</Routes>
141+
</MemoryRouter>,
142+
);
143+
await openObjectIs('acme_task');
144+
}
145+
146+
/** The card's repro: add a Picklist "Priority" with no option yet; the autosave holds it. */
147+
async function holdAPicklist(): Promise<void> {
148+
fireEvent.click(await screen.findByRole('button', { name: 'Form' }));
149+
await addFieldFromFormToolbar(undefined, { label: 'Priority', type: /^Picklist$/ });
150+
await screen.findByTestId('studio-held', undefined, { timeout: 8000 });
151+
}
152+
153+
/** Whether a reload / tab close would be asked about. */
154+
function reloadAsks(): boolean {
155+
const e = new Event('beforeunload', { cancelable: true });
156+
window.dispatchEvent(e);
157+
return e.defaultPrevented;
158+
}
159+
160+
const pillarLink = (name: string) => within(screen.getByTestId('studio-pillar-nav')).getByRole('link', { name });
161+
const railRow = (label: string) => within(screen.getByTestId('studio-rail-data')).getByRole('button', { name: label });
162+
163+
describe('a held Data field guards every departure (objectstack#26705)', () => {
164+
it('leaving the pillar asks; Cancel keeps the held field, OK leaves and clears the guard', async () => {
165+
await openTask();
166+
await holdAPicklist();
167+
168+
confirmSpy.mockReturnValueOnce(false);
169+
fireEvent.click(pillarLink('Automations'));
170+
expect(confirmSpy).toHaveBeenCalledTimes(1);
171+
expect(confirmSpy).toHaveBeenCalledWith(LEAVE_QUESTION);
172+
expect(screen.getByTestId('studio-held')).toBeInTheDocument();
173+
expect(screen.getByTestId('studio-rail-data')).toBeInTheDocument();
174+
175+
confirmSpy.mockReturnValueOnce(true);
176+
fireEvent.click(pillarLink('Automations'));
177+
expect(confirmSpy).toHaveBeenCalledTimes(2);
178+
await screen.findByTestId('studio-rail-automations');
179+
// The unmounted pillar took its hold back: nothing is asked any more.
180+
expect(reloadAsks()).toBe(false);
181+
fireEvent.click(pillarLink('Data'));
182+
expect(confirmSpy).toHaveBeenCalledTimes(2);
183+
});
184+
185+
it('opening another object in the rail asks; Cancel keeps the held field, OK opens the other object', async () => {
186+
await openTask();
187+
await holdAPicklist();
188+
189+
confirmSpy.mockReturnValueOnce(false);
190+
fireEvent.click(railRow('Note'));
191+
expect(confirmSpy).toHaveBeenCalledTimes(1);
192+
expect(confirmSpy).toHaveBeenCalledWith(LEAVE_QUESTION);
193+
await openObjectIs('acme_task');
194+
expect(screen.getByTestId('studio-held')).toBeInTheDocument();
195+
196+
// Re-picking the open object drops nothing, so it asks nothing.
197+
fireEvent.click(railRow('Task'));
198+
expect(confirmSpy).toHaveBeenCalledTimes(1);
199+
200+
confirmSpy.mockReturnValueOnce(true);
201+
fireEvent.click(railRow('Note'));
202+
expect(confirmSpy).toHaveBeenCalledTimes(2);
203+
await openObjectIs('acme_note');
204+
expect(screen.queryByTestId('studio-held')).toBeNull();
205+
});
206+
207+
it('a reload asks while the field is held', async () => {
208+
await openTask();
209+
expect(reloadAsks()).toBe(false);
210+
await holdAPicklist();
211+
expect(reloadAsks()).toBe(true);
212+
});
213+
214+
// CONTROL: nothing held, nothing asked.
215+
it('with no edit held, the rail, the reload and the pillar link never ask', async () => {
216+
await openTask();
217+
218+
fireEvent.click(railRow('Note'));
219+
await openObjectIs('acme_note');
220+
expect(reloadAsks()).toBe(false);
221+
fireEvent.click(pillarLink('Automations'));
222+
await screen.findByTestId('studio-rail-automations');
223+
expect(confirmSpy).not.toHaveBeenCalled();
224+
});
225+
});

0 commit comments

Comments
 (0)