From 6b05361087dd2f8e690c85628efba13ad210c122 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:06:58 +0000 Subject: [PATCH 1/9] feat(studio): generic detail Save publishes the item at once Save writes the item's draft, then publishes that one item, pinned to the published version the page loaded. The auto-save switch is gone. An AI-written draft shows the designers' notice and its discard; a person's pending draft is marked as unpublished changes with its own Publish and Discard. A refused publish shows its reason. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- .../views/metadata-admin/ResourceEditPage.tsx | 400 ++++++++++-------- .../views/metadata-admin/detailSaveAtOnce.ts | 104 +++++ ui/packages/i18n/src/namespaces/studio/en.ts | 5 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 5 +- 4 files changed, 332 insertions(+), 182 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 0aa6c362c83..e917a4a7fb0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -8,9 +8,11 @@ * sees code vs overlay vs effective. * 2. Renders a SchemaForm against the JSONSchema in the type's * `/meta/types` registry row. - * 3. Save → PUT, with automatic destructive-change handling: a 409 - * `destructive_change` response opens a confirmation dialog - * listing the issues, and on confirm we retry with `?force=true`. + * 3. Save → the item's draft PUT, then that one item's publish, so a + * Save takes effect at once (objectstack#36902), with automatic + * destructive-change handling: a 409 `destructive_change` response + * opens a confirmation dialog listing the issues, and on confirm we + * retry with `?force=true`. * 4. Reset overlay → DELETE (overlay only). * 5. References tab → calls `client.references()` and lists * back-pointers so admins know what will break before deleting. @@ -40,10 +42,7 @@ import { MousePointer2, SlidersHorizontal, FileCode2, - Zap, - ZapOff, Send, - Undo2, Lock, } from 'lucide-react'; import { toast } from 'sonner'; @@ -86,7 +85,7 @@ import type { // The ONE draft-envelope reader (objectui#8181). Its docblock carries the // read-decoration contract objectui#7603 established here; it was hoisted so // the three sibling copies could stop re-deriving it. -import { extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack'; +import { extractDraftBody, formatMetadataError, readDraftChanges, type DraftChange } from '@object-ui/data-objectstack'; import { PageShell, WritabilityBadge } from './PageShell.js'; import { ResourceDetailHeader } from './ResourceDetailHeader.js'; import { @@ -123,10 +122,14 @@ import { type RichMetadataTypeEntry, } from './useMetadata.js'; // objectui#11773 — the draft save's optimistic-concurrency guard and its dialog. -import { readDraftForSave, useDraftSaveGuard } from './DraftConflictDialog.js'; +import { isPublishConflictKeptEditing, publishedPinOf, readDraftForSave, useDraftSaveGuard } from './DraftConflictDialog.js'; +// objectstack#36902 — Save takes effect at once; the AI draft's notice is the designers'. +import { isAiDraft, publishDetailSave } from './detailSaveAtOnce.js'; +import { StudioAiDraftNotice } from '../studio-design/StudioAiDraftNotice.js'; +import { publishFailureOf, publishRefusal, type StudioRefusal } from '../studio-design/metadataError.js'; +import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; // objectstack#29148 — the one strip a Studio editor draws for a refused draft read. import { StudioRefusalStrip } from '../studio-design/StudioRefusalStrip.js'; -import type { StudioRefusal } from '../studio-design/metadataError.js'; import { BUNDLE_MEMBER_PARAM, getMetadataResource, @@ -1060,8 +1063,19 @@ function MetadataResourceEditPageImpl({ save: saveDraftVersioned, recordRead: recordDraftRead, forget: forgetDraftVersion, + recordPublished: recordPublishedVersion, + publish: publishPinned, dialog: draftConflictDialog, } = useDraftSaveGuard(client, reloadFromServer); + // objectstack#36902 — the pending draft's per-key provenance (`draftChanges`), + // `null` with no draft or none recorded: an AI-written draft gets the + // designers' notice and its discard (decision 1), a person's the + // "unpublished changes" line with its own Publish and Discard (decision 14). + const [draftChanges, setDraftChanges] = React.useState(null); + // objectstack#36902 — why the item's own publish was refused, in the + // designers' words (`publishRefusal`), the server's text behind Details. + const [publishRefused, setPublishRefused] = React.useState(null); + const [discardingAiDraft, setDiscardingAiDraft] = React.useState(false); // Form edit mode. The form is read-only by default — admins land in a // "view" state and must click Edit to mutate, mirroring the Salesforce / @@ -1163,7 +1177,7 @@ function MetadataResourceEditPageImpl({ : `${type}:${name}:default`; // objectstack#27629 — the verdict belongs to the DRAFT, not to the selection // (the ruling on objectstack#27485, ported here from Studio's Data pillar). - // Expiring it with the selection released Save and the autosave the moment + // Expiring it with the selection released Save the moment // the author cleared or changed it, while the broken text stayed in the // draft. So each selection's last live verdict is kept with the stamp of the // draft slice it judged (`selectionSlicePath`, fingerprinted the way a server @@ -1259,6 +1273,7 @@ function MetadataResourceEditPageImpl({ React.useEffect(() => { setSaveRefusal(null); setInspectorVerdicts({}); + setPublishRefused(null); }, [type, name]); React.useEffect(() => { if (!editing) setSelection(null); @@ -1269,32 +1284,11 @@ function MetadataResourceEditPageImpl({ const draftSnapshotRef = React.useRef | null>(null); // Last successful save timestamp — surfaced as "Saved HH:MM" indicator - // next to the icon-only Save button. + // next to the Save button. objectstack#36902 — there is no auto-save: a + // Save makes the item live, so it is the author's to press (as #36511 did + // for the designers). const [lastSavedAt, setLastSavedAt] = React.useState(null); - // Auto-save toggle, persisted per-browser. Defaults to on for an - // "it just works" experience; users can disable it from the toolbar. - const [autoSaveEnabled, setAutoSaveEnabled] = React.useState(() => { - if (typeof window === 'undefined') return true; - try { - const v = window.localStorage.getItem('metadata-admin:autosave'); - return v === null ? true : v === '1'; - } catch { - return true; - } - }); - React.useEffect(() => { - try { - window.localStorage.setItem('metadata-admin:autosave', autoSaveEnabled ? '1' : '0'); - } catch { - /* ignore */ - } - }, [autoSaveEnabled]); - // Tracks the last draft snapshot we attempted to auto-save, so a - // validation failure does not loop on the same payload — auto-save - // only retries once the user mutates the draft again. - const lastAutoSaveSnapshotRef = React.useRef(null); - // Prefetch object name list once — fuels the `ref:object` widget. // We don't block render on it; the widget shows a "Loading…" state. // @@ -1557,7 +1551,11 @@ function MetadataResourceEditPageImpl({ // objectui#11773 — the next save is pinned to what the draft read // served: its version, or "no draft row" when none was pending. recordDraftRead(type, name, draftPackage, draftRead.pin); + // objectstack#36902 — and the Save's publish is pinned to the published + // row the layers served (objectstack#36601), at the address it writes. + recordPublishedVersion(type, name, draftPackage, publishedPinOf(lay)); setHasDraft(!!draftReal); + setDraftChanges(draftReal ? readDraftChanges(draftResp) : null); setLoading(false); } catch (err: any) { if (!cancelled) { @@ -1580,7 +1578,7 @@ function MetadataResourceEditPageImpl({ return () => { cancelled = true; }; - }, [client, type, name, ownerPackageId, bundleMember, createMode, reloadKey, locale, recordDraftRead]); + }, [client, type, name, ownerPackageId, bundleMember, createMode, reloadKey, locale, recordDraftRead, recordPublishedVersion]); // Related drawer state. `null` = closed. We avoid querystring round- // trips on every keystroke; URL state is best-effort sync via effect @@ -1993,6 +1991,7 @@ function MetadataResourceEditPageImpl({ async function doSave(force: boolean) { setSaving(true); setError(null); + setPublishRefused(null); setIssues([]); if (createMode) { setRevealIssues(true); @@ -2098,57 +2097,115 @@ function MetadataResourceEditPageImpl({ setSaving(false); return; } - // Save lands in the draft buffer — the runtime keeps serving the - // last published version until the operator clicks Publish. The - // backend defaults to publish mode for backward-compatibility, so - // Studio must opt into draft explicitly. - // Bind to the active software package (sys_metadata.package_id) when a - // real package scope is carried in the URL (`?package=`). The backend - // stamps it on create and preserves an existing binding on update, so - // env-local overlays (no `?package=`) are unaffected. + // objectstack#36902 (epic objectstack#36890 decision 1) — a Save takes + // effect at once, as the designers' Save does (objectstack#36511): the + // item's draft (`PUT ?mode=draft`), then that one item's own publish + // (`publishDetailSave`), never the package's batch. The draft binds to + // the active software package (`?package=`) when the URL carries one; + // the publish names the same package and member. const activePackage = readActivePackageBinding(); const saveOptions = { force, mode: 'draft' as const, ...(activePackage ? { packageId: activePackage } : {}), }; + // The draft pending before this save — the AI assistant's, or a + // person's from before Save took effect at once. A refused publish keeps + // it, now carrying these edits; with none, it takes back the one this + // save wrote. + const hadDraft = !createMode && hasDraft; + // objectstack#28680 — whether this save gives the item its first layer. + const firstPublish = createMode || holdsNoLayer(layered); // objectui#11773 — a create, with nothing read, is the first-write pin // (`If-None-Match: *`): the door refuses it where the name already holds // a draft instead of writing over it, and reads it as a create. A save of // the item this editor loaded sends the pin its load or last save held. + let wroteDraft = true; if (createMode) { // objectui#7611 — a type whose edit page writes the live item creates - // it live too (`createLive`), so the page that opens next reads what - // was created and no draft is left behind for a Publish to replay. - const createOptions = - config.createLive && !activePackage ? { force } : saveOptions; - await client.save(type, savedName, itemToSave, { ...createOptions, ifNoneMatch: '*' }); + // it live too (`createLive`): nothing is left in the draft to publish. + const live = !!config.createLive && !activePackage; + await client.save(type, savedName, itemToSave, { ...(live ? { force } : saveOptions), ifNoneMatch: '*' }); + wroteDraft = !live; } else if ((await saveDraftVersioned(type, savedName, itemToSave, saveOptions)) === 'reloaded') { // The author chose the saved version; the load effect replaces the draft. return; } + if (wroteDraft) { + // objectstack#34818 — a flow whose Problems tab lists the draft's + // publish checks: the author has read them (`publishChecksShown.ts`). + const reviewedChecks = type === 'flow' && (draftDiagnostics?.warnings?.length ?? 0) > 0; + if (reviewedChecks) markPublishChecksShown(type, savedName); + let live: Awaited>; + try { + live = await publishDetailSave( + client, + { type, name: savedName, ...(activePackage ? { packageId: activePackage } : {}), ...memberScope }, + hadDraft, + // objectstack#36601 — pinned to the published row the load read; a + // create read nothing, and its draft's first-write pin stands. + createMode ? undefined : publishPinned, + ); + } finally { + if (reviewedChecks) clearPublishChecksShown(type, savedName); + } + // The published row moved and the author chose to reload it. + if (live.kind === 'reloaded') return; + if (live.kind === 'refused') { + // objectstack#36902 item 6 — nothing went live: the reason is shown, + // and the edits stay on the page, unsaved. + if (live.draftDiscarded) { + setHasDraft(false); + setDraftChanges(null); + if (!createMode) recordDraftRead(type, savedName, activePackage, { ifNoneMatch: '*' }); + } + setPublishRefused( + isPublishConflictKeptEditing(live.error) + ? { message: live.error instanceof Error ? live.error.message : String(live.error) } + : publishRefusal(publishFailureOf(type, savedName, live.error), type, itemToSave as Record, locale), + ); + return; + } + } // Refresh layered + draft state after save — scope to the same package // as the initial load (ADR-0048) so a same-name collision re-reads this // package's own row, not another's. const refreshScope = { ...(ownerPackageId ? { packageId: ownerPackageId } : {}), ...memberScope }; - // objectui#11799 — this save went into a draft, which makes no layer. An - // item this page loaded with no layer still has none, and an item it - // just created has never been published (the page then navigates to the - // item, whose load reads it afresh). `/layers` answers 404 for both, so - // it is not asked: the answer already held stands. + // objectui#11799 — a create's page navigates to the item, whose load + // reads it afresh, so `/layers` is not asked here. // objectstack#29793, objectstack#30786 — …except for a type whose buffer - // IS a layer (`editsAuthoredLayers`: the stored `draft` this save just - // wrote, which a caller the server serves that layer to is answered for a - // draft-only name too). - const layerless = !editsAuthoredLayers(type) && (createMode || (savedName === name && holdsNoLayer(layered))); - const [lay, draftResp] = await Promise.all([ + // IS a layer (`editsAuthoredLayers`). + const layerless = !editsAuthoredLayers(type) && createMode; + const [lay, draftRead] = await Promise.all([ layerless ? layered : client.layered(type, savedName, refreshScope), - client.getDraft(type, savedName, refreshScope).catch(() => null), + // objectui#11773 — read at the address the next save writes, so its answer pins that save. + readDraftForSave(client, type, savedName, activePackage, bundleMember), ]); if (!layerless) setLayered(lay); + if (wroteDraft && firstPublish && !activePackage) { + // objectstack#28680 — a package-less page or dashboard made live for + // the first time joins app navigation. Not awaited: each app write + // reports itself (a toast with Undo, or its failure). + void navigationWrites.created(type, savedName, lay?.effective ?? itemToSave); + } + if ('refused' in draftRead) { + setDraftRefused({ + message: t('engine.studio.refusal.draftUnreadable', locale), + detail: formatMetadataError(draftRead.refused), + }); + setLoadFailed(true); + return; + } + const draftResp = draftRead.answer; const draftReal = extractDraftBody(draftResp); setHasDraft(!!draftReal); + setDraftChanges(draftReal ? readDraftChanges(draftResp) : null); setDraftDiagnostics(draftReal ? draftEnvelopeDiagnostics(draftResp) : undefined); + if (!createMode) { + // What remains pins the next save (normally "no draft row") and its publish. + recordDraftRead(type, savedName, activePackage, draftRead.pin); + recordPublishedVersion(type, savedName, activePackage, publishedPinOf(lay)); + } // The served draft is the whole document the save just stored (see the // load effect, objectui#10765): take it as-is. ⛔ Not spread over // `effective` — that is the PUBLISHED layer, and a spread would bring a @@ -2175,7 +2232,6 @@ function MetadataResourceEditPageImpl({ setDraft(fresh); draftSnapshotRef.current = fresh; setLastSavedAt(new Date()); - lastAutoSaveSnapshotRef.current = JSON.stringify(fresh); setDestructiveIssues(null); setPendingItem(null); // The server took this document, so whatever it refused before is @@ -2375,6 +2431,8 @@ function MetadataResourceEditPageImpl({ if (resetSemantic) { const lay = await client.layered(type, name, layeredScope); setLayered(lay); + // objectstack#36902 — the next Save's publish is pinned to the row read. + recordPublishedVersion(type, name, activePackage, publishedPinOf(lay)); // objectstack#29793 — the published item as its author wrote it. const fresh = authoredPublished(type, lay as AuthoredLayers); setDraft(fresh); @@ -2397,11 +2455,14 @@ function MetadataResourceEditPageImpl({ } } - // Promote the pending draft to the active overlay. Mirrors `doSave`'s - // refresh pattern so the editor stays in sync with the new baseline. + // objectstack#36902 (decision 14) — publish a draft that was already pending + // (a person's from before Save took effect at once): that one item, pinned + // like a Save's publish. Mirrors `doSave`'s refresh pattern so the editor + // stays in sync with the new baseline. async function doPublish() { setPublishing(true); setError(null); + setPublishRefused(null); try { // State the SAME package the save step already stated — read from the // same single source, so the two calls of one loop can never disagree. @@ -2420,13 +2481,25 @@ function MetadataResourceEditPageImpl({ const reviewedChecks = type === 'flow' && (draftDiagnostics?.warnings?.length ?? 0) > 0; if (reviewedChecks) markPublishChecksShown(type, name); try { - await client.publish(type, name, { + // objectstack#36601 — pinned to the published row the load read. + const outcome = await publishPinned(client, type, name, { ...(activePackage ? { packageId: activePackage } : {}), ...memberScope, }); + // The published row moved and the author chose to reload it. + if (outcome === 'reloaded') return; + } catch (err) { + // objectstack#36902 item 6 — the refusal's reason, in the designers' words. + setPublishRefused( + isPublishConflictKeptEditing(err) + ? { message: err instanceof Error ? err.message : String(err) } + : publishRefusal(publishFailureOf(type, name, err), type, refusalProbeBody(draft), locale), + ); + return; } finally { if (reviewedChecks) clearPublishChecksShown(type, name); } + emitMetadataRefresh(); // objectui#11773 — the draft is re-read at the address the next save // writes, so its answer pins that save (see the load effect). const [lay, draftRead] = await Promise.all([ @@ -2454,6 +2527,7 @@ function MetadataResourceEditPageImpl({ } const draftReal = extractDraftBody(draftResp); setHasDraft(!!draftReal); + setDraftChanges(draftReal ? readDraftChanges(draftResp) : null); setDraftDiagnostics(draftReal ? draftEnvelopeDiagnostics(draftResp) : undefined); // After a publish the promoted body IS `effective` and the draft row is // normally gone; a draft that does remain is a whole document and is @@ -2479,6 +2553,7 @@ function MetadataResourceEditPageImpl({ // the re-read says what the next save is pinned to (normally "no draft // row"). recordDraftRead(type, name, activePackage, draftRead.pin); + recordPublishedVersion(type, name, activePackage, publishedPinOf(lay)); } catch (err: any) { setError(err?.message ?? String(err)); } finally { @@ -2503,6 +2578,39 @@ function MetadataResourceEditPageImpl({ }); } + // objectstack#36902 (decision 1, the designers' rule of objectstack#36660) — + // drop the AI assistant's draft of this one item, at the package and member + // it was read at (`DELETE /meta/:type/:name?state=draft`), back to the live + // version. Edits not yet saved go with it, so they are asked about first. + async function discardAiDraft() { + if (isDirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return; + setDiscardingAiDraft(true); + setError(null); + setPublishRefused(null); + try { + const activePackage = readActivePackageBinding(); + await client.reset(type, name, { + state: 'draft', + ...(activePackage ? { packageId: activePackage } : {}), + ...memberScope, + }); + setHasDraft(false); + setDraftChanges(null); + // The load installs the live version and pins the next save to it. + setReloadKey((k) => k + 1); + // The ledger behind Changes re-reads, one item fewer. + emitMetadataRefresh(); + } catch (err) { + setError( + tFormat('engine.studio.aiDraft.discardFailed', locale, { + reason: formatMetadataError(err), + }), + ); + } finally { + setDiscardingAiDraft(false); + } + } + async function runDiscardDraft(item: string) { setSaving(true); setError(null); @@ -2523,12 +2631,16 @@ function MetadataResourceEditPageImpl({ // with no layer still has none, and `/layers` would answer 404. const lay = layered && holdsNoLayer(layered) ? layered : await client.layered(type, name, layeredScope); setLayered(lay); + // objectstack#36902 — the next Save's publish is pinned to the row read. + recordPublishedVersion(type, name, activePackage, publishedPinOf(lay)); // objectstack#29793 — the published item as its author wrote it. const fresh = authoredPublished(type, lay as AuthoredLayers); setDraft(fresh); draftSnapshotRef.current = fresh; setHasDraft(false); + setDraftChanges(null); setDraftDiagnostics(undefined); + emitMetadataRefresh(); // objectui#12303 — the discard is said, naming what it discarded, through // the console's shared toast (`sonner`, the one Studio's publish uses). // Only here, after the DELETE and the re-read landed: a refused discard @@ -2604,42 +2716,13 @@ function MetadataResourceEditPageImpl({ }, }); - // Auto-save: debounce edits and persist silently once the user pauses - // for AUTOSAVE_DEBOUNCE_MS. Skipped for create mode (need an explicit - // name first), read-only forms, and while a save is already in flight. - // We track the last attempted snapshot so a validation failure doesn't - // loop on the same payload — the user has to mutate the draft again. - const AUTOSAVE_DEBOUNCE_MS = 1500; - // Keep doSave fresh inside the effect without re-arming the timer on - // every render. + // objectstack#36902 — no auto-save timer: a Save makes the item live, so it + // is sent only by the button, ⌘S and the destructive-change confirmation. + // Keep doSave fresh for the shortcut without re-binding it on every render. const doSaveRef = React.useRef(doSave); React.useEffect(() => { doSaveRef.current = doSave; }); - React.useEffect(() => { - if (!autoSaveEnabled) return; - if (createMode || readOnly || !editing || !isDirty || saving) return; - // Autosave is a save door like any other: gating only the button would let - // the timer publish the malformed definition a second later (objectui#4306). - if (inspectorBlocking > 0) return; - // Second validation term, and the one that survives a selection change. - // The timer is the door the wedge (`9073cf018`) actually came through: it - // re-sent the refused document on every later edit, silently, so the - // designer showed the rename as applied while the server held none of it. - if (refusalBlocking > 0) return; - let snap: string; - try { - snap = JSON.stringify(draft); - } catch { - return; - } - if (snap === lastAutoSaveSnapshotRef.current) return; - const handle = window.setTimeout(() => { - lastAutoSaveSnapshotRef.current = snap; - doSaveRef.current(false); - }, AUTOSAVE_DEBOUNCE_MS); - return () => window.clearTimeout(handle); - }, [draft, isDirty, editing, saving, createMode, readOnly, autoSaveEnabled, inspectorBlocking, refusalBlocking]); // Keyboard shortcut — ⌘S / Ctrl+S triggers save when dirty. React.useEffect(() => { @@ -2648,8 +2731,8 @@ function MetadataResourceEditPageImpl({ if (!canWrite || readOnly) return; if (!editing && !createMode) return; e.preventDefault(); - // Third save door — the shortcut must respect the same gate as the - // button and the autosave timer (objectui#4306). + // Second save door — the shortcut must respect the same gate as the + // button (objectui#4306). if (!saving && (createMode || isDirty) && inspectorBlocking === 0 && refusalBlocking === 0) { doSaveRef.current(false); } @@ -2959,7 +3042,6 @@ function MetadataResourceEditPageImpl({ )} - {canWrite && (editing || createMode) && !createMode && ( - - )} {canWrite && !createMode && editing && !PreviewComponent && ( - )} - {canWrite && !createMode && hasDraft && ( - - )} + {/* objectstack#36902 — no Publish here: Save makes the item live. A + draft that was already pending is published or discarded from its + own line above the editor (decision 14). */} ); // objectstack#36901 (decision 8) — the draft review is a status chip in the // header, not a sheet trigger among the tools: shown while a draft is // pending, it opens the review (ADR-0033 Phase B), as `?review=1` does. + // objectstack#36902 — a pending draft some key of which the AI assistant wrote. + const aiDraft = !createMode && hasDraft && isAiDraft(draftChanges); const draftChangeCount = hasDraft && !createMode ? computeDraftChangeCount(layered?.effective ?? null, draft) : 0; const reviewChip = !createMode && hasDraft ? ( @@ -3114,7 +3145,7 @@ function MetadataResourceEditPageImpl({ // objectstack#36901 (decision 8) — the body the open tab draws. The canvas // (Preview) and the details form edit the ONE draft this page holds, and the - // header's Save, ⌘S and autosave save it whichever tab is open (decision 4): + // header's Save and ⌘S save it whichever tab is open (decision 4): // a tab switch keeps every unsaved edit, so it asks nothing. A create draft // draws the canvas when its type authors there (`CREATE_MODE_CANVAS_TYPES`). const activeTab = itemTab.location.tab; @@ -3170,7 +3201,7 @@ function MetadataResourceEditPageImpl({ : 'p-6 space-y-6 max-w-7xl' } > - {(error || readOnly || hasDraft || isLocked || walledDeciding) && ( + {(error || publishRefused || readOnly || hasDraft || isLocked || walledDeciding) && (
)} - {hasDraft && !createMode && ( -
+ {/* objectstack#36902 item 6 — the item's own publish was refused: + nothing went live, and the reason says why. */} + {publishRefused && ( + + )} + {/* objectstack#36902 (decision 1) — the AI assistant's draft is the + version on screen: Save makes it live too, and its discard + drops that one item's draft, the designers' line. */} + {aiDraft && ( + void discardAiDraft() : undefined} + busy={discardingAiDraft || saving || publishing} + /> + )} + {/* objectstack#36902 (decision 14) — a person's draft from before + Save took effect at once: marked as unpublished changes, and + published or discarded here, this one item. */} + {hasDraft && !createMode && !aiDraft && ( +
- {t('engine.edit.draftPending', locale)} + {t('engine.edit.unpublishedChanges', locale)} {canWrite && ( <> @@ -3245,7 +3299,9 @@ function MetadataResourceEditPageImpl({ size="sm" onClick={doPublish} disabled={saving || publishing || isDirty} + title={isDirty ? t('engine.edit.unpublishedPublishDirty', locale) : undefined} className="h-7 bg-emerald-600 hover:bg-emerald-700 text-emerald-50" + data-testid="resource-draft-publish" > {publishing ? ( @@ -4023,26 +4079,21 @@ function MetadataResourceEditPageImpl({ } /** - * SaveStatusIndicator — small inline label next to the Save icon that - * communicates auto-save state so the icon-only button is not a black - * box. Six states, each stamped on `data-state`: + * SaveStatusIndicator — small inline label next to the Save button. Four + * states, each stamped on `data-state` (objectstack#36902: no auto-save, so + * an unsaved edit waits for Save): * - saving → "Saving…" with spinner * - dirty + held → "Not saved" (destructive): a save door is shut — the * server refused this draft or the inspector holds a - * fault — so neither the timer nor the button will save - * it; the reason rides on the chip's title - * - dirty + on → "Auto-saving…" (subtle, amber) - * - dirty + off → "Unsaved" (amber) - * - clean + ts → "Saved 14:32" (muted) + * fault — so the button will not save it; the reason + * rides on the chip's title + * - dirty → "Unsaved" (amber) + * - clean + ts → "Saved 14:32" (muted): the item is live * - createMode → hidden until first save - * - * `held` outranks the auto-save promise: the auto-save effect returns early on - * the same terms, so "Auto-saving…" there would promise a save that never comes. */ function SaveStatusIndicator({ saving, isDirty, - autoSaveEnabled, held, heldReason, lastSavedAt, @@ -4051,7 +4102,6 @@ function SaveStatusIndicator({ }: { saving: boolean; isDirty: boolean; - autoSaveEnabled: boolean; /** A save door is shut on this draft (server refusal or inspector fault). */ held: boolean; /** Why it is shut — the Save button's own explanation. */ @@ -4095,13 +4145,11 @@ function SaveStatusIndicator({ return ( - {autoSaveEnabled - ? t('engine.edit.autoSavingShortly', locale) - : t('engine.edit.unsaved', locale)} + {t('engine.edit.unsaved', locale)} ); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts new file mode 100644 index 00000000000..3719b8b4ad6 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36902 (epic objectstack#36890 decisions 1 and 14) — the generic + * item page's Save takes effect at once, as the Studio designers' Save does + * (objectstack#36511): the item's draft, then that one item's own publish + * (`POST /meta/:type/:name/publish`), never the package's batch. + * + * Invariants: + * - The publish addresses what the draft save wrote: the same package + * (`?package=`) and, for a bundle, the same member. The designers' helper + * (`studioSaveBar.tsx` `publishSavedItem`) names no member, which is why + * this page carries its own. + * - Pinned (`pinned`, the buffer's `DraftSaveGuard.publish`), the publish + * sends the published version the buffer was loaded at, so a Save over a + * row another editor published since is asked about (reload, overwrite or + * keep editing) instead of replacing it. + * - Refused, the draft the save wrote is taken back when no other draft of + * the item was pending before it (`hadDraft` false): a refused Save leaves + * nothing behind and the edits stay on the page, unsaved. A draft that was + * pending before (the AI assistant's, or a person's from before Save took + * effect at once) is kept: it now carries the page's edits too. + * - A reload after a conflict takes the saved draft back BEFORE the buffer + * is re-read, and that discard is not best-effort: a draft left behind + * would be re-read as the buffer and published by the next Save. + * - Every path tells the ledger (`emitMetadataRefresh`), so Changes and the + * app re-read what went live. + */ + +import type { DraftChange, MetadataClient } from '@object-ui/data-objectstack'; +import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; +import { isAgentDraftSurface } from '../studio-design/StudioDraftMark.js'; +import type { DraftSaveGuard } from './DraftConflictDialog.js'; + +/** The item a Save wrote, at the address its draft save wrote it. */ +export interface DetailPublishTarget { + type: string; + name: string; + /** The folded `?package=` binding; absent when the page holds none. */ + packageId?: string; + /** The bundle member the draft belongs to; absent for the canonical one. */ + member?: string; +} + +/** What {@link publishDetailSave} did. */ +export type DetailPublishOutcome = + /** The item is live. */ + | { kind: 'published' } + /** The published row moved and the author chose to reload: the caller's load re-reads the buffer. */ + | { kind: 'reloaded'; draftDiscarded: boolean } + /** Refused, or the author kept editing after a conflict; `draftDiscarded` says the saved draft was taken back. */ + | { kind: 'refused'; error: unknown; draftDiscarded: boolean }; + +/** Make the draft a Save just wrote live (see the module docblock). */ +export async function publishDetailSave( + client: Pick, + target: DetailPublishTarget, + hadDraft: boolean, + pinned?: DraftSaveGuard['publish'], +): Promise { + const scope = { + ...(target.packageId ? { packageId: target.packageId } : {}), + ...(target.member ? { member: target.member } : {}), + }; + let draftDiscarded = false; + const takeBack = async (): Promise => { + await client.reset(target.type, target.name, { state: 'draft', ...scope }); + draftDiscarded = true; + }; + try { + if (pinned) { + const outcome = await pinned(client, target.type, target.name, scope, hadDraft ? undefined : takeBack); + if (outcome === 'reloaded') { + emitMetadataRefresh(); + return { kind: 'reloaded', draftDiscarded }; + } + } else { + await client.publish(target.type, target.name, scope); + } + } catch (error) { + if (!hadDraft && !draftDiscarded) { + try { + await takeBack(); + } catch (discardError) { + // The draft stays pending, listed under Changes, where it can be discarded. + console.error('[metadata] a refused publish left the saved draft pending:', discardError); + } + } + emitMetadataRefresh(); + return { kind: 'refused', error, draftDiscarded }; + } + emitMetadataRefresh(); + return { kind: 'published' }; +} + +/** + * Whether a pending draft is the AI assistant's: some key of it was last + * written by the copilot or an MCP client (`draftChanges[].by`), the rule the + * designers' notice reads (`StudioDraftMark.tsx`). A draft whose read recorded + * no provenance (`null`) is a person's. + */ +export function isAiDraft(changes: readonly DraftChange[] | null | undefined): boolean { + return (changes ?? []).some((change) => isAgentDraftSurface(change.by)); +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index f245025219e..b58a9005cc0 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1330,6 +1330,8 @@ const STUDIO_EN: Record = { 'engine.edit.discardDraftConfirmBody': 'The published version stays as it is; only the unpublished changes are removed.', 'engine.edit.draftDiscarded': 'Draft discarded: {item}', 'engine.edit.draftPending': 'Pending changes — save lives in a draft. Click Publish to release.', + 'engine.edit.unpublishedChanges': 'This item has unpublished changes. Publish or discard them here.', + 'engine.edit.unpublishedPublishDirty': 'Saving makes these changes live together with your edits.', 'engine.edit.rollback': 'Rollback to this version', 'engine.edit.rollbackConfirm': 'Restore version {version}? This writes the historical body back as the current published overlay.', 'engine.edit.rollbackConfirmTitle': 'Restore {item} to version {version}?', @@ -1753,9 +1755,6 @@ const STUDIO_EN: Record = { 'You have unsaved changes. Leave this page anyway?', 'engine.edit.saving': 'Saving…', 'engine.edit.savedAt': 'Saved {time}', - 'engine.edit.autoSaveOn': 'Auto-save is on — click to disable', - 'engine.edit.autoSaveOff': 'Auto-save is off — click to enable', - 'engine.edit.autoSavingShortly': 'Auto-saving…', 'engine.edit.notSavedHeld': 'Not saved — fix the errors to save', 'engine.edit.destructive': 'Destructive change', 'engine.edit.destructiveHint': diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index f581a24e357..4df9038ff82 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1183,6 +1183,8 @@ const STUDIO_ZH: Record = { 'engine.edit.discardDraftConfirmBody': '已发布的版本保持不变,仅移除未发布的更改。', 'engine.edit.draftDiscarded': '已丢弃 {item} 的待发布草稿', 'engine.edit.draftPending': '存在未发布的草稿 — 保存仅写入草稿,点击"发布"使其生效。', + 'engine.edit.unpublishedChanges': '这一项有未发布的改动,可以在这里发布或放弃。', + 'engine.edit.unpublishedPublishDirty': '保存会让这些改动和本页的修改一起生效。', 'engine.edit.rollback': '回滚到此版本', 'engine.edit.rollbackConfirm': '恢复版本 {version}?该历史内容将被写回作为当前已发布的覆盖层。', 'engine.edit.rollbackConfirmTitle': '将 {item} 恢复到版本 {version}?', @@ -1564,9 +1566,6 @@ const STUDIO_ZH: Record = { 'engine.edit.unsavedLeaveConfirm': '当前存在未保存的修改,确定离开此页面吗?', 'engine.edit.saving': '保存中…', 'engine.edit.savedAt': '已保存 {time}', - 'engine.edit.autoSaveOn': '自动保存已开启,点击关闭', - 'engine.edit.autoSaveOff': '自动保存已关闭,点击开启', - 'engine.edit.autoSavingShortly': '即将自动保存…', 'engine.edit.notSavedHeld': '未保存 — 修正错误后才能保存', 'engine.edit.destructive': '破坏性变更', 'engine.edit.destructiveHint': '该修改会破坏现有引用关系。请检查问题清单后确认强制保存。', From 7766f65fc97da1bd216c277f4001ecf4a0801b22 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:09:12 +0000 Subject: [PATCH 2/9] test(studio): pin the generic detail page's save-at-once model Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- ...ResourceEditPage.saveAtOnce-36902.test.tsx | 521 ++++++++++++++++++ 1 file changed, 521 insertions(+) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx new file mode 100644 index 00000000000..1cfbd8157f2 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx @@ -0,0 +1,521 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36902 (epic objectstack#36890 decisions 1, 12 and 14) — the + * generic item page's Save takes effect at once, as the Studio designers' + * Save does: + * + * 1. Save writes the item's draft and then publishes that one item + * (`POST /meta/:type/:name/publish`), pinned to the published version the + * page loaded; the draft-version pin and the conflict dialog stay; there + * is no auto-save and no second Publish step. + * 2. A create publishes after its first-write save. + * 3. An AI-written draft (`draftChanges[].by` copilot or mcp) is the version + * on screen, with the designers' notice; Save makes it live; its discard + * asks first when the page holds unsaved edits. + * 4. A person's pending draft is marked as unpublished changes, with its own + * Publish and Discard. + * 5. Every departure the shell sees asks while edits are unsaved: ×, ‹ ›, an + * in-app link, a reload or close. Browser Back is not guarded. + * 6. A refused publish says why, and nothing goes live. + * + * The REAL page over a REAL `MetadataClient`, whose transport is an in-memory + * server answering as the framework's `/meta` doors do (draft and published + * versions, `409 METADATA_CONFLICT` with `currentVersion`). Only `sonner`, + * `window.confirm` and the editor's locale hook are replaced. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { Link, MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { z } from 'zod'; +import { ComponentRegistry } from '@object-ui/core'; +import { DocSchema } from '@objectstack/spec/system'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +const toasts = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() })); +vi.mock('sonner', () => ({ toast: toasts })); + +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); + +interface Row { + body: Record; + version: string; + draftChanges?: Array<{ path: string[]; by: string; actor: string; at: string }>; +} + +/** What the server holds, and every write it was sent. */ +const server = { + active: new Map(), + drafts: new Map(), + writes: [] as Array<{ method: string; key: string; search: string; ifMatch: string | null; ifNoneMatch: string | null; status: number }>, + /** The publish door's next refusal, sent once. */ + refusePublish: null as null | { status: number; body: unknown }, + seq: 0, +}; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +const conflict = (key: string, head: string | null) => + json(409, { error: `${key} has been modified since you loaded it (current is ${head}).`, code: 'METADATA_CONFLICT', currentVersion: head }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(String(input), 'http://console.test'); + const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); + if (!meta) return json(200, []); + const seg = meta[1].split('/').map(decodeURIComponent); + if (seg[0] === '_drafts') return json(200, { drafts: [] }); + if (seg.length === 1) return json(200, { items: [{ name: 'alpha' }, { name: 'guide' }, { name: 'zeta' }] }); + const key = `${seg[0]}/${seg[1]}`; + const headers = new Headers(init?.headers); + const ifMatch = headers.get('If-Match'); + const ifNoneMatch = headers.get('If-None-Match'); + const log = (status: number) => + server.writes.push({ method, key, search: url.search, ifMatch, ifNoneMatch, status }); + if (seg.length === 3 && seg[2] === 'layers') { + const row = server.active.get(key); + return row + ? json(200, { + code: null, + overlay: row.body, + overlayScope: 'env', + effective: row.body, + overlayVersion: row.version, + editable: true, + deletable: true, + resettable: false, + lock: 'none', + }) + : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); + } + if (seg.length === 3 && seg[2] === 'references') return json(200, []); + if (seg.length === 3 && seg[2] === 'publish' && method === 'POST') { + if (server.refusePublish) { + const { status, body } = server.refusePublish; + server.refusePublish = null; + log(status); + return json(status, body); + } + const head = server.active.get(key)?.version ?? null; + if ((ifMatch !== null && ifMatch !== head) || (ifNoneMatch !== null && head !== null)) { + log(409); + return conflict(key, head); + } + const draft = server.drafts.get(key); + if (!draft) { + log(404); + return json(404, { error: { code: 'NO_DRAFT', message: 'nothing pending' } }); + } + server.seq += 1; + const version = `pub:v${server.seq}`; + server.active.set(key, { body: draft.body, version }); + server.drafts.delete(key); + log(200); + return json(200, { success: true, version, seq: server.seq, message: `Published ${key}` }); + } + if (method === 'PUT') { + const head = server.drafts.get(key)?.version ?? null; + if ((ifMatch !== null && ifMatch !== head) || (ifNoneMatch !== null && head !== null)) { + log(409); + return conflict(key, head); + } + server.seq += 1; + const version = `draft:v${server.seq}`; + server.drafts.set(key, { body: JSON.parse(String(init?.body ?? '{}')) as Record, version }); + log(200); + return json(200, { success: true, version, seq: server.seq, state: 'draft', message: `Saved ${key}` }); + } + if (method === 'DELETE') { + if (url.searchParams.get('state') === 'draft') server.drafts.delete(key); + else server.active.delete(key); + log(200); + return json(200, { success: true }); + } + if (url.searchParams.get('state') === 'draft') { + const row = server.drafts.get(key); + if (!row) return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); + return json(200, { + type: seg[0], + name: seg[1], + item: row.body, + version: row.version, + ...(row.draftChanges ? { draftChanges: row.draftChanges } : {}), + }); + } + const row = server.active.get(key); + return row ? json(200, { type: seg[0], name: seg[1], item: row.body }) : json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); +} + +const client = vi.hoisted(() => ({ current: null as unknown })); + +vi.mock('./useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + useMetadataClient: () => client.current, + useMetadataTypes: () => ({ + loading: false, + entries: [ + { type: 'doc', label: 'Documentation', domain: 'system', allowEnvironmentOverlay: false, allowRuntimeCreate: true, schema: DOC_JSON_SCHEMA }, + ], + }), + }; +}); + +import { MetadataResourceEditPage } from './ResourceEditPage'; +import { registerDefaultMetadataSchemas } from './default-schemas'; +import { registerBuiltinPreviews } from './previews'; +import { t } from './i18n'; + +const DOC_JSON_SCHEMA = z.toJSONSchema(DocSchema as unknown as z.ZodType) as Record; +client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); + +registerDefaultMetadataSchemas(); +registerBuiltinPreviews(); + +const STUB_NS = 'save-at-once-36902'; +function StubMarkdown({ schema }: { schema: { content?: string } }) { + return
{schema.content}
; +} +beforeAll(() => { + ComponentRegistry.register('markdown', StubMarkdown as never, { namespace: STUB_NS }); +}); +afterAll(() => { + ComponentRegistry.unregister('markdown', STUB_NS); +}); + +const LEAVE_QUESTION = t('engine.edit.unsavedLeaveConfirm', 'en-US'); +const confirmSpy = vi.fn((_message?: string) => false); + +beforeEach(() => { + server.active.clear(); + server.drafts.clear(); + server.writes = []; + server.refusePublish = null; + server.seq = 0; + for (const fn of Object.values(toasts)) fn.mockClear(); + confirmSpy.mockReset(); + confirmSpy.mockReturnValue(false); + Object.defineProperty(window, 'confirm', { configurable: true, writable: true, value: confirmSpy }); + window.history.replaceState(null, '', '/metadata/doc/guide'); +}); +afterEach(() => { + cleanup(); + window.history.replaceState(null, '', '/'); +}); + +async function settle() { + await act(async () => { + for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0)); + }); +} + +function Where() { + return
{useLocation().pathname}
; +} + +const source = () => screen.findByRole('textbox', { name: /Markdown source|Markdown/ }, { timeout: 8000 }); +const saveButton = () => screen.getByTestId('resource-save'); +const publishWrites = () => server.writes.filter((w) => w.key === 'doc/guide' && w.method === 'POST'); + +/** Opens `doc/guide`, published at `pub:v0`, beside a link to another page. */ +async function openGuide(opts: { draft?: Row } = {}) { + server.active.set('doc/guide', { body: { name: 'guide', label: 'Guide', content: '# Live', group: 'reference' }, version: 'pub:v0' }); + if (opts.draft) server.drafts.set('doc/guide', opts.draft); + render( + + Other page + + + + + + } + /> + } /> + } /> + } /> + + , + ); + await source(); + await settle(); +} + +async function editSource(value = '# Live, edited') { + fireEvent.change(await source(), { target: { value } }); + await settle(); +} + +describe('Save takes effect at once (objectstack#36902 item 1)', () => { + it('Save writes the draft, then publishes that one item pinned to the published version it loaded', async () => { + await openGuide(); + await editSource(); + fireEvent.click(saveButton()); + await waitFor(() => expect(publishWrites()).toHaveLength(1), { timeout: 8000 }); + + const [put, publish] = server.writes; + expect(put).toMatchObject({ method: 'PUT', key: 'doc/guide', search: '?mode=draft', ifNoneMatch: '*', status: 200 }); + expect(publish).toMatchObject({ method: 'POST', key: 'doc/guide', ifMatch: 'pub:v0', status: 200 }); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# Live, edited' }); + expect(server.drafts.has('doc/guide')).toBe(false); + // No second step: no draft is left, so nothing offers a Publish. + await waitFor(() => expect(screen.getByTestId('save-status')).toHaveAttribute('data-state', 'saved')); + expect(screen.queryByTestId('resource-unpublished-changes')).toBeNull(); + expect(screen.queryByRole('button', { name: /^Publish$/ })).toBeNull(); + }); + + it('a second Save chains its pins: the draft asserts none again, the publish names the version the first one left', async () => { + await openGuide(); + await editSource('# one'); + fireEvent.click(saveButton()); + await waitFor(() => expect(publishWrites()).toHaveLength(1), { timeout: 8000 }); + await settle(); + await editSource('# two'); + fireEvent.click(saveButton()); + await waitFor(() => expect(publishWrites()).toHaveLength(2), { timeout: 8000 }); + const second = server.writes.slice(2); + expect(second[0]).toMatchObject({ method: 'PUT', ifNoneMatch: '*', status: 200 }); + expect(second[1]).toMatchObject({ method: 'POST', ifMatch: 'pub:v2', status: 200 }); + }); + + it('there is no auto-save: an edit left alone sends nothing, and the switch is gone', async () => { + await openGuide(); + await editSource(); + await act(async () => { + await new Promise((r) => setTimeout(r, 2000)); + }); + expect(server.writes).toEqual([]); + expect(screen.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + expect(screen.queryByTitle(/Auto-save/)).toBeNull(); + }); + + it('the published row moved since the load: the conflict dialog asks, and "keep editing" leaves nothing live or pending', async () => { + await openGuide(); + await editSource(); + // Another editor publishes in between. + server.active.set('doc/guide', { body: { name: 'guide', label: 'Guide', content: '# Theirs' }, version: 'pub:theirs' }); + fireEvent.click(saveButton()); + expect(await screen.findByTestId('draft-conflict-dialog', {}, { timeout: 8000 })).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + await waitFor(() => expect(screen.getByTestId('studio-refusal-message')).toBeInTheDocument()); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# Theirs' }); + // The draft the save wrote was taken back; the edit stays on the page, unsaved. + expect(server.drafts.has('doc/guide')).toBe(false); + expect(await source()).toHaveValue('# Live, edited'); + }); +}); + +describe('a create publishes after its save (objectstack#36902 item 2)', () => { + function renderCreate() { + render( + + + + + + + } + /> + } /> + + , + ); + } + async function fillAndSave() { + const label = await waitFor(() => { + const el = document.getElementById('mdf-label') as HTMLInputElement | null; + expect(el).not.toBeNull(); + return el!; + }, { timeout: 8000 }); + fireEvent.change(label, { target: { value: 'New Guide' } }); + await waitFor(() => expect((document.getElementById('mdf-name') as HTMLInputElement).value).toBe('new_guide')); + fireEvent.change(await source(), { target: { value: '# New' } }); + fireEvent.click(saveButton()); + } + + it('the create lands live: first-write draft, then its publish, then the item opens', async () => { + renderCreate(); + await fillAndSave(); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/new_guide'), { timeout: 8000 }); + expect(server.writes.map((w) => [w.method, w.key, w.ifNoneMatch, w.status])).toEqual([ + ['PUT', 'doc/new_guide', '*', 200], + ['POST', 'doc/new_guide', null, 200], + ]); + expect(server.active.get('doc/new_guide')?.body).toMatchObject({ name: 'new_guide', content: '# New' }); + expect(server.drafts.has('doc/new_guide')).toBe(false); + }); + + it('a refused publish of the create takes its draft back, says why, and stays on the form', async () => { + server.refusePublish = { status: 422, body: { error: 'Publish refused: the referenced object exists only in a draft.', code: 'INVALID_METADATA' } }; + renderCreate(); + await fillAndSave(); + expect(await screen.findByTestId('studio-refusal-message', {}, { timeout: 8000 })).toHaveTextContent(/exists only in a draft/); + expect(server.drafts.has('doc/new_guide')).toBe(false); + expect(server.active.has('doc/new_guide')).toBe(false); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/new'); + }); +}); + +describe('the AI assistant\'s draft (objectstack#36902 item 3, decision 1)', () => { + const aiDraft = (): Row => ({ + body: { name: 'guide', label: 'Guide', content: '# From the AI', group: 'reference' }, + version: 'draft:ai', + draftChanges: [{ path: ['content'], by: 'copilot', actor: 'u1', at: '2026-11-24T10:00:00.000Z' }], + }); + + it('the page shows the AI version with the notice, and a person\'s Save makes it live, the draft pin carried', async () => { + await openGuide({ draft: aiDraft() }); + expect(await source()).toHaveValue('# From the AI'); + expect(screen.getByTestId('studio-ai-draft-notice')).toBeInTheDocument(); + expect(screen.queryByTestId('resource-unpublished-changes')).toBeNull(); + await editSource('# From the AI, reviewed'); + fireEvent.click(saveButton()); + await waitFor(() => expect(publishWrites()).toHaveLength(1), { timeout: 8000 }); + expect(server.writes[0]).toMatchObject({ method: 'PUT', ifMatch: 'draft:ai', status: 200 }); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# From the AI, reviewed' }); + await waitFor(() => expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull()); + }); + + it('a refused Save keeps the AI draft (it now carries the edit): nothing takes it back', async () => { + server.refusePublish = { status: 422, body: { error: 'Publish refused.', code: 'INVALID_METADATA' } }; + await openGuide({ draft: aiDraft() }); + await editSource('# edited'); + fireEvent.click(saveButton()); + await screen.findByTestId('studio-refusal-message', {}, { timeout: 8000 }); + expect(server.writes.some((w) => w.method === 'DELETE')).toBe(false); + expect(server.drafts.get('doc/guide')?.body).toMatchObject({ content: '# edited' }); + }); + + it('discard asks first when the page holds unsaved edits; Cancel keeps both the draft and the edits', async () => { + await openGuide({ draft: aiDraft() }); + await editSource('# unsaved'); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(t('engine.studio.aiDraft.discardConfirmUnsaved', 'en-US')); + await settle(); + expect(server.writes).toEqual([]); + expect(await source()).toHaveValue('# unsaved'); + }); + + it('discard drops that one item\'s draft at its address and goes back to the live version', async () => { + await openGuide({ draft: aiDraft() }); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + // Nothing unsaved, so nothing to ask. + expect(confirmSpy).not.toHaveBeenCalled(); + await waitFor(() => expect(server.drafts.has('doc/guide')).toBe(false), { timeout: 8000 }); + expect(server.writes).toEqual([expect.objectContaining({ method: 'DELETE', search: '?state=draft' })]); + await waitFor(async () => expect(await source()).toHaveValue('# Live'), { timeout: 8000 }); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + }); +}); + +describe('a person\'s pending draft (objectstack#36902 item 4, decision 14)', () => { + const humanDraft = (): Row => ({ + body: { name: 'guide', label: 'Guide', content: '# Mine, unpublished', group: 'reference' }, + version: 'draft:mine', + draftChanges: [{ path: ['content'], by: 'studio', actor: 'u1', at: '2026-11-20T10:00:00.000Z' }], + }); + + it('is marked as unpublished changes, never as the AI\'s, and its own Publish makes it live, pinned', async () => { + await openGuide({ draft: humanDraft() }); + expect(await screen.findByTestId('resource-unpublished-changes')).toBeInTheDocument(); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + fireEvent.click(screen.getByTestId('resource-draft-publish')); + await waitFor(() => expect(publishWrites()).toHaveLength(1), { timeout: 8000 }); + expect(publishWrites()[0]).toMatchObject({ ifMatch: 'pub:v0', status: 200 }); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# Mine, unpublished' }); + await waitFor(() => expect(screen.queryByTestId('resource-unpublished-changes')).toBeNull()); + }); + + it('a draft whose read recorded no provenance is a person\'s too', async () => { + const { draftChanges: _omitted, ...bare } = humanDraft(); + await openGuide({ draft: bare }); + expect(await screen.findByTestId('resource-unpublished-changes')).toBeInTheDocument(); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + }); + + it('its own Discard asks in-app and drops that one draft', async () => { + await openGuide({ draft: humanDraft() }); + fireEvent.click(await screen.findByTestId('resource-draft-discard')); + fireEvent.click(await screen.findByTestId('resource-edit-confirm-action')); + await waitFor(() => expect(server.drafts.has('doc/guide')).toBe(false), { timeout: 8000 }); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# Live' }); + }); +}); + +describe('a refused publish says why (objectstack#36902 item 6)', () => { + it('the refusal reason is shown, nothing goes live, the saved draft is taken back and the edits stay', async () => { + server.refusePublish = { + status: 422, + body: { error: 'doc/guide references object "invoice", which exists only in a draft.', code: 'INVALID_METADATA' }, + }; + await openGuide(); + await editSource(); + fireEvent.click(saveButton()); + expect(await screen.findByTestId('studio-refusal-message', {}, { timeout: 8000 })).toHaveTextContent(/exists only in a draft/); + expect(server.active.get('doc/guide')?.body).toMatchObject({ content: '# Live' }); + expect(server.drafts.has('doc/guide')).toBe(false); + expect(server.writes.map((w) => w.method)).toEqual(['PUT', 'POST', 'DELETE']); + expect(await source()).toHaveValue('# Live, edited'); + expect(screen.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + }); +}); + +describe('the leave guard (objectstack#36902 item 5, decision 12)', () => { + it('× asks while edits are unsaved, and Cancel stays', async () => { + await openGuide(); + await editSource(); + fireEvent.click(screen.getByTestId('studio-detail-close')); + expect(confirmSpy).toHaveBeenCalledWith(LEAVE_QUESTION); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/guide'); + }); + + it('‹ › ask while edits are unsaved; OK opens the neighbour', async () => { + await openGuide(); + await waitFor(() => expect(screen.getByTestId('studio-detail-next')).toBeEnabled(), { timeout: 8000 }); + await editSource(); + fireEvent.click(screen.getByTestId('studio-detail-next')); + expect(confirmSpy).toHaveBeenCalledWith(LEAVE_QUESTION); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/guide'); + confirmSpy.mockReturnValue(true); + fireEvent.click(screen.getByTestId('studio-detail-previous')); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/alpha')); + }); + + it('an in-app link and a reload or close ask too', async () => { + await openGuide(); + await editSource(); + fireEvent.click(screen.getByRole('link', { name: 'Other page' })); + expect(confirmSpy).toHaveBeenCalledWith(LEAVE_QUESTION); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/guide'); + const unload = new Event('beforeunload', { cancelable: true }); + window.dispatchEvent(unload); + expect(unload.defaultPrevented).toBe(true); + }); + + it('browser Back is not guarded (the console is a BrowserRouter), and a saved page asks nothing', async () => { + await openGuide(); + await editSource(); + window.dispatchEvent(new PopStateEvent('popstate')); + expect(confirmSpy).not.toHaveBeenCalled(); + fireEvent.click(saveButton()); + await waitFor(() => expect(publishWrites()).toHaveLength(1), { timeout: 8000 }); + await settle(); + fireEvent.click(screen.getByTestId('studio-detail-close')); + expect(confirmSpy).not.toHaveBeenCalled(); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/metadata\/doc$/)); + }); +}); From d7a3cfb20603571dabb84cd6a56dd066c7c909dd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:13:43 +0000 Subject: [PATCH 3/9] fix(data-objectstack): forward the published version from layered() The client rebuilt the layered answer field by field and dropped overlayVersion, so a Studio Save's pinned publish never had a pin. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- ...ResourceEditPage.saveAtOnce-36902.test.tsx | 6 ++++- ...metadata-client.layeredDraft-29793.test.ts | 26 +++++++++++++++++++ .../data-objectstack/src/metadata-client.ts | 11 ++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx index 1cfbd8157f2..82ed486eb35 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx @@ -71,7 +71,9 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise ({ type: k.split('/')[0], name: k.split('/')[1] })) }); + } if (seg.length === 1) return json(200, { items: [{ name: 'alpha' }, { name: 'guide' }, { name: 'zeta' }] }); const key = `${seg[0]}/${seg[1]}`; const headers = new Headers(init?.headers); @@ -87,6 +89,8 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + it('the conforming fixture still parses with the version served', () => { + expect(GetMetaItemLayeredResponseSchema.safeParse({ ...CONFORMING, overlayVersion: 'v7' }).success).toBe(true); + }); + + for (const [branch, body] of [['conforming', CONFORMING], ['degraded', DEGRADED]] as const) { + it(`${branch}: a served version arrives as served, and a served null as null`, async () => { + expect((await clientAnswering({ ...body, overlayVersion: 'v7' }).layered('object', 'ticket')).overlayVersion).toBe('v7'); + const none = await clientAnswering({ ...body, overlayVersion: null }).layered('object', 'ticket'); + expect('overlayVersion' in none).toBe(true); + expect(none.overlayVersion).toBeNull(); + }); + + it(`${branch}: a version the server did not serve stays absent`, async () => { + const layered = await clientAnswering(body).layered('object', 'ticket'); + expect('overlayVersion' in layered).toBe(false); + }); + } +}); diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index aef18606cba..b31429901ee 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -611,6 +611,14 @@ export interface MetadataLayered { * key is forwarded only when the server sent it. */ draft?: T | null; + /** + * objectstack#36601 — the published row's version (spec + * `GetMetaItemLayeredResponseSchema.overlayVersion`): the token a pinned + * publish sends as `If-Match`, `null` when no published row is stored at the + * read's address. ABSENT when the server served none (a server from before + * the field): a caller then pins nothing. Forwarded only when served. + */ + overlayVersion?: string | null; /** * Load-time validation result for `effective` (server-computed via * the same Zod registry used at save time). Undefined for types @@ -1821,6 +1829,8 @@ export class MetadataClient { effective: (envelope.effective ?? null) as T | null, // objectstack#29793 — the draft layer, forwarded only when served. ...('draft' in body ? { draft: (body.draft ?? null) as T | null } : {}), + // objectstack#36601 — the published version a pinned publish sends, forwarded only when served. + ...(envelope.overlayVersion !== undefined ? { overlayVersion: envelope.overlayVersion } : {}), ...(body._diagnostics ? { _diagnostics: body._diagnostics as MetadataDiagnostics } : {}), lock: envelope.lock, ...(envelope.lockReason !== undefined ? { lockReason: envelope.lockReason } : {}), @@ -1854,6 +1864,7 @@ export class MetadataClient { overlayScope: body.overlayScope ?? null, effective: body.effective ?? null, ...('draft' in body ? { draft: (body.draft ?? null) as T | null } : {}), + ...(body.overlayVersion !== undefined ? { overlayVersion: body.overlayVersion as string | null } : {}), ...(body._diagnostics ? { _diagnostics: body._diagnostics as MetadataDiagnostics } : {}), ...(body.lock !== undefined ? { lock: body.lock as MetadataLayered['lock'] } : {}), ...(body.lockReason !== undefined ? { lockReason: body.lockReason as string } : {}), From 2252df7cc39a57517617fa815d1a852cc54c03e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:15:32 +0000 Subject: [PATCH 4/9] test(studio): live e2e for save-at-once and the leave guard; changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- .changeset/36902-detail-save-at-once.md | 22 ++++ .../live/studio-detail-save-at-once.spec.ts | 100 ++++++++++++++++++ ui/e2e/live/studio-editor.spec.ts | 20 ++-- 3 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 .changeset/36902-detail-save-at-once.md create mode 100644 ui/e2e/live/studio-detail-save-at-once.spec.ts diff --git a/.changeset/36902-detail-save-at-once.md b/.changeset/36902-detail-save-at-once.md new file mode 100644 index 00000000000..194bbcf06b5 --- /dev/null +++ b/.changeset/36902-detail-save-at-once.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/data-objectstack': patch +--- + +feat(studio): the generic item page's Save takes effect at once; an AI draft gets the designers' notice and discard + +Clause-②: no +Metadata-protocol: none + +Studio's generic item page saves the way the designers do. Save writes the item's draft and then publishes that one item (`POST /meta/:type/:name/publish`, at the same package and bundle member), so the change is live at once and there is no second Publish step. The draft save keeps its version pin and conflict dialog, and the publish is now pinned to the published version the page loaded: when another editor published the item in between, the same dialog asks to reload, overwrite or keep editing. A create publishes right after its first save. The auto-save switch is gone, and edits wait for Save, ⌘S or the destructive-change confirmation. + +A refused publish shows its reason above the editor in the designers' words, with the server's text under Details. Nothing goes live, the draft the Save wrote is taken back, and the edits stay on the page, unsaved. + +A pending draft written by the AI assistant (the copilot or an MCP client) is the version on screen, under the designers' line: saving makes it live too, and "Discard AI changes" drops that one item's draft, asking first when the page holds unsaved edits. A pending draft a person wrote before this change is marked "This item has unpublished changes", with its own Publish and Discard for that item. The header's Publish and discard buttons are gone. + +Leaving the page with unsaved edits still asks first through ×, ‹ ›, the side menu, in-app links, reload and close. The browser's Back is not intercepted. + +`@object-ui/data-objectstack`: `MetadataClient.layered()` now forwards the served `overlayVersion` (new optional `MetadataLayered.overlayVersion`). The client used to rebuild its answer field by field and drop it, so a Studio Save's publish was never pinned on a server that serves it. + +Locale keys `engine.edit.unpublishedChanges` and `engine.edit.unpublishedPublishDirty` are new, and `engine.edit.autoSaveOn`, `engine.edit.autoSaveOff` and `engine.edit.autoSavingShortly` are removed (en, zh). The per-browser `metadata-admin:autosave` setting is no longer read. No metadata changes; nothing to migrate. diff --git a/ui/e2e/live/studio-detail-save-at-once.spec.ts b/ui/e2e/live/studio-detail-save-at-once.spec.ts new file mode 100644 index 00000000000..52a74f31a0a --- /dev/null +++ b/ui/e2e/live/studio-detail-save-at-once.spec.ts @@ -0,0 +1,100 @@ +import { test, expect, type APIRequestContext, type Dialog } from '@playwright/test'; + +/** + * Live e2e for the generic Studio item page's save model (objectstack#36902, + * epic objectstack#36890 decisions 1 and 12): Save makes the item live at once + * (its draft, then that one item's publish), with no auto-save and no second + * Publish step, and leaving with unsaved edits asks first through × and ‹ › + * while the browser's Back is not intercepted. + * + * The item under edit is a page the test authors in the environment (a copy of + * the showcase's `showcase_project_workspace`), removed again at the end, as + * `studio-editor.spec.ts` does. + */ +const API = process.env.LIVE_API_URL || 'http://localhost:3000'; +const SHIPPED_PAGE = 'showcase_project_workspace'; + +async function authorEditablePage(request: APIRequestContext): Promise<{ name: string; firstRegionBlocks: number }> { + const res = await request.get(`${API}/api/v1/meta/page/${SHIPPED_PAGE}`); + expect(res.ok(), await res.text()).toBeTruthy(); + const shipped = (await res.json()).item as Record; + const body = Object.fromEntries(Object.entries(shipped).filter(([k]) => !k.startsWith('_'))); + const firstRegionBlocks = ((body.regions as { components?: unknown[] }[])[0].components ?? []).length; + const name = `e2e_save_at_once_${Date.now()}`; + const put = await request.put(`${API}/api/v1/meta/page/${name}`, { + data: { ...body, name, label: `E2E Save At Once ${name.slice(-6)}` }, + }); + expect(put.ok(), await put.text()).toBeTruthy(); + return { name, firstRegionBlocks }; +} + +test('Save makes the edit live at once, and an unsaved edit is guarded on × but not on Back', async ({ page, request }) => { + const { name, firstRegionBlocks } = await authorEditablePage(request); + const writes: string[] = []; + page.on('request', (r) => { + if (r.url().includes(`/api/v1/meta/page/${name}`) && ['PUT', 'POST'].includes(r.method())) { + writes.push(`${r.method()} ${new URL(r.url()).pathname}`); + } + }); + try { + await page.goto('/studio/~all/metadata/page'); + await page.goto(`/studio/~all/metadata/page/${name}`); + await expect(page.getByTestId('metadata-edit-page')).toBeVisible(); + + await test.step('an edit stays on the page: no auto-save sends it', async () => { + await page.getByRole('button', { name: /Add block/i }).first().click(); + await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click(); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + await page.waitForTimeout(2500); + expect(writes).toEqual([]); + }); + + await test.step('× asks before dropping the edit; Cancel stays', async () => { + const asked: string[] = []; + const dismiss = (d: Dialog) => { + asked.push(d.type()); + void d.dismiss(); + }; + page.on('dialog', dismiss); + await page.getByTestId('studio-detail-close').click(); + await expect.poll(() => asked).toEqual(['confirm']); + page.off('dialog', dismiss); + await expect(page).toHaveURL(new RegExp(`/metadata/page/${name}`)); + }); + + await test.step('Save writes the draft, then publishes the one item; nothing is left to publish', async () => { + const published = page.waitForResponse( + (r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`), + ); + await page.getByTestId('resource-save').click(); + const publish = await published; + expect(publish.ok(), await publish.text()).toBeTruthy(); + expect(writes).toEqual([`PUT /api/v1/meta/page/${name}`, `POST /api/v1/meta/page/${name}/publish`]); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'saved'); + await expect(page.getByTestId('resource-unpublished-changes')).toHaveCount(0); + const live = await request.get(`${API}/api/v1/meta/page/${name}`, { headers: { 'Cache-Control': 'no-cache' } }); + const blocks = (await live.json()).item.regions[0].components as unknown[]; + expect(blocks).toHaveLength(firstRegionBlocks + 1); + const draft = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`); + expect(draft.status()).toBe(404); + }); + + await test.step('browser Back is not intercepted, even with an unsaved edit', async () => { + await page.getByRole('button', { name: /Add block/i }).first().click(); + await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click(); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + const asked: string[] = []; + const accept = (d: Dialog) => { + asked.push(d.type()); + void d.accept(); + }; + page.on('dialog', accept); + await page.goBack(); + await expect(page).toHaveURL(/\/metadata\/page(\?|$)/); + page.off('dialog', accept); + expect(asked).toEqual([]); + }); + } finally { + await request.delete(`${API}/api/v1/meta/page/${name}`); + } +}); diff --git a/ui/e2e/live/studio-editor.spec.ts b/ui/e2e/live/studio-editor.spec.ts index 8d4df2a4a74..832afdeed62 100644 --- a/ui/e2e/live/studio-editor.spec.ts +++ b/ui/e2e/live/studio-editor.spec.ts @@ -86,16 +86,18 @@ test('Add block opens a block-type picker with configurable block kinds, and the await expect(dialog.getByRole('button', { name: /Section/i })).toBeVisible(); await expect(dialog.getByRole('button', { name: /Record details/i })).toBeVisible(); - // The save round trip, not only the canvas: picking a kind autosaves a - // draft, and the draft read back through /meta holds the new block at the - // end of the first region. - const saved = page.waitForResponse( - (r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/page/${name}?mode=draft`), - ); + // The save round trip, not only the canvas: picking a kind is an unsaved + // edit, and Save makes it live at once (objectstack#36902): the item's + // draft, then that one item's publish. The page read back through /meta + // holds the new block at the end of the first region. await dialog.getByRole('button', { name: /Card/i }).first().click(); - const save = await saved; - expect(save.ok(), await save.text()).toBeTruthy(); - const stored = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`); + const published = page.waitForResponse( + (r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`), + ); + await page.getByTestId('resource-save').click(); + const publish = await published; + expect(publish.ok(), await publish.text()).toBeTruthy(); + const stored = await request.get(`${API}/api/v1/meta/page/${name}`); expect(stored.ok(), await stored.text()).toBeTruthy(); const blocks = (await stored.json()).item.regions[0].components as { type?: string }[]; expect(blocks).toHaveLength(firstRegionBlocks + 1); From d3fbcf67df2633c75a6c82ac1c77b62e83978e4a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:25:47 +0000 Subject: [PATCH 5/9] test(studio): serverRefusalGate presses Save instead of waiting out auto-save Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- ...esourceEditPage.serverRefusalGate.test.tsx | 44 +++++++++++++++++-- .../views/metadata-admin/ResourceEditPage.tsx | 10 ++--- 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.serverRefusalGate.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.serverRefusalGate.test.tsx index fb4a7583625..61ec028151b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.serverRefusalGate.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.serverRefusalGate.test.tsx @@ -140,6 +140,10 @@ const mockClient = { get: vi.fn(async () => null), saveDraft: vi.fn(async () => ({})), save: vi.fn(async () => ({})), + // objectstack#36902 — a Save publishes the item it wrote, and a refused + // publish takes that draft back. + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), }; vi.mock('./useMetadata', async (importOriginal) => { @@ -240,6 +244,19 @@ const saveSays = () => { const refusalHoldsSave = () => saveSays().includes('The server refused this draft'); +/** + * objectstack#36902 — there is no auto-save: the author presses Save once the + * edit has reached the draft (the chip reads it as unsaved, or held). A Save + * withheld by the gate is a disabled button, and pressing it sends nothing. + */ +async function pressSave() { + await waitFor( + () => expect(screen.getByTestId('save-status').getAttribute('data-state')).toMatch(/^(unsaved|held)$/), + { timeout: 6000 }, + ); + fireEvent.click(saveButton()); +} + /** * Open the editor and select `which`, returning that block's CEL textarea. * @@ -278,7 +295,7 @@ function openEditor() { ); } -/** Auto-save debounces 1500ms; wait past it so a fire has room to happen. */ +/** Long enough for a save the button sent to have landed. */ const AUTOSAVE_WINDOW_MS = 2600; const pastAutoSaveWindow = () => new Promise((r) => setTimeout(r, AUTOSAVE_WINDOW_MS)); @@ -290,6 +307,7 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# openEditor(); const box = await selectAndOpenCel('bystander'); fireEvent.change(box, { target: { value: 'record.amount > 11' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); }, 20000); @@ -304,6 +322,7 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# openEditor(); const offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } }); + await pressSave(); // The server refuses that draft. Anchor on the button actually going // disabled, so everything after is taken at a moment the gate provably ran. @@ -315,6 +334,7 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# // refused element is untouched, so the block must still stand. const bystanderBox = await selectAndOpenCel('bystander'); fireEvent.change(bystanderBox, { target: { value: 'record.amount > 12' } }); + await pressSave(); await waitFor( () => expect(bystanderBox).toHaveValue('record.amount > 12'), @@ -332,11 +352,13 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# openEditor(); const offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); await waitFor(() => expect(saveButton()).toBeDisabled(), { timeout: 6000 }); const bystanderBox = await selectAndOpenCel('bystander'); fireEvent.change(bystanderBox, { target: { value: 'record.amount > 13' } }); + await pressSave(); await pastAutoSaveWindow(); // Still ONE. Before this fix the timer fired again here, carrying the same @@ -353,12 +375,14 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# openEditor(); let offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); await waitFor(() => expect(saveButton()).toBeDisabled(), { timeout: 6000 }); // Touch the refused element itself — the block is keyed to that slice. offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 22' } }); + await pressSave(); await waitFor(() => expect(saveButton()).toBeEnabled(), { timeout: 6000 }); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(2), { timeout: 6000 }); @@ -373,6 +397,7 @@ describe('MetadataResourceEditPage — a draft the SERVER refused blocks Save (# openEditor(); const box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); // The error is still surfaced; only the BLOCK is withheld. @@ -391,6 +416,7 @@ describe('MetadataResourceEditPage — the advisory half is untouched (#8057 / # openEditor(); const box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); // The server TOOK it: the draft is clean again, and the only thing holding @@ -404,6 +430,7 @@ describe('MetadataResourceEditPage — the advisory half is untouched (#8057 / # // ("Save is always blocked") reddens on this second call. const other = await selectAndOpenCel('bystander'); fireEvent.change(other, { target: { value: 'record.amount > 14' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(2), { timeout: 8000 }); expect(refusalHoldsSave()).toBe(false); }, 25000); @@ -417,16 +444,19 @@ describe('MetadataResourceEditPage — the advisory half is untouched (#8057 / # openEditor(); let box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(saveButton()).toBeDisabled(), { timeout: 6000 }); box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 22' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(2), { timeout: 6000 }); await waitFor(() => expect(refusalHoldsSave()).toBe(false), { timeout: 6000 }); // A later unrelated edit is not held against the settled refusal. const other = await selectAndOpenCel('bystander'); fireEvent.change(other, { target: { value: 'record.amount > 15' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(3), { timeout: 8000 }); }, 25000); }); @@ -457,6 +487,7 @@ describe('MetadataResourceEditPage — a refusal is read off the parsed error on openEditor(); const box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); await waitFor(() => expect(saveButton()).toBeDisabled(), { timeout: 6000 }); @@ -489,6 +520,7 @@ describe('MetadataResourceEditPage — a refusal is read off the parsed error on openEditor(); const box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); expect(await screen.findByText('Destructive change detected', {}, { timeout: 6000 })).toBeInTheDocument(); @@ -508,6 +540,7 @@ describe('MetadataResourceEditPage — a refusal is read off the parsed error on openEditor(); const box = await selectAndOpenCel('offender'); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); expect(await screen.findByText(message)).toBeInTheDocument(); @@ -531,12 +564,13 @@ describe('MetadataResourceEditPage — a refusal is read off the parsed error on describe('MetadataResourceEditPage — the save-status chip while a refusal holds auto-save (#29901)', () => { const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null; - it('CONTROL: an ordinary dirty edit reads the auto-save state, then saves', async () => { + it('CONTROL: an ordinary dirty edit reads the unsaved state, then saves', async () => { openEditor(); const box = await selectAndOpenCel('bystander'); fireEvent.change(box, { target: { value: 'record.amount > 11' } }); - await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 6000 }); + await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 6000 }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); await waitFor(() => expect(chipState()).toBe('saved'), { timeout: 6000 }); }, 20000); @@ -547,6 +581,7 @@ describe('MetadataResourceEditPage — the save-status chip while a refusal hold openEditor(); const offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 }); await waitFor(() => expect(chipState()).toBe('held'), { timeout: 6000 }); @@ -562,6 +597,7 @@ describe('MetadataResourceEditPage — the save-status chip while a refusal hold expect(chipState()).toBe('held'); const bystanderBox = await selectAndOpenCel('bystander'); fireEvent.change(bystanderBox, { target: { value: 'record.amount > 12' } }); + await pressSave(); await pastAutoSaveWindow(); expect(chipState()).toBe('held'); expect(mockClient.save).toHaveBeenCalledTimes(1); @@ -573,12 +609,14 @@ describe('MetadataResourceEditPage — the save-status chip while a refusal hold openEditor(); let offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 21' } }); + await pressSave(); await waitFor(() => expect(chipState()).toBe('held'), { timeout: 6000 }); // Editing the slice the server named releases the hold; the next save is // accepted. offenderBox = await selectAndOpenCel('offender'); fireEvent.change(offenderBox, { target: { value: 'record.amount > 22' } }); + await pressSave(); await waitFor(() => expect(chipState()).not.toBe('held'), { timeout: 6000 }); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(2), { timeout: 6000 }); await waitFor(() => expect(chipState()).toBe('saved'), { timeout: 6000 }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index e917a4a7fb0..337e4d67a10 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -2299,7 +2299,7 @@ function MetadataResourceEditPageImpl({ } setIssues(mapped); // Hold the refusal against the draft slices the server named, so the - // next auto-save cannot re-send the same refused document behind an + // next Save cannot re-send the same refused document behind an // unrelated edit (`9073cf018`). Paths that do not localise are // DROPPED rather than kept as a wildcard: a refusal we cannot tie to a // slice must gate nothing at all. @@ -2669,7 +2669,7 @@ function MetadataResourceEditPageImpl({ }, [draft, createMode]); // The write gates — hoisted above the early `loading` return so the - // auto-save / keyboard / blocker effects below can read them. The item + // keyboard / blocker effects below can read them. The item // half (`itemWritable`: the type tier and the served `editable`) and the // caller half (`canWrite`) are decided once, next to the designer auto-on // effect above. @@ -2912,6 +2912,7 @@ function MetadataResourceEditPageImpl({ // Cancel reverts the draft to the last saved snapshot, so the document the // server refused no longer exists to be refused. setSaveRefusal(null); + setPublishRefused(null); setEditing(false); } @@ -3042,9 +3043,8 @@ function MetadataResourceEditPageImpl({ 0 || refusalBlocking > 0} heldReason={saveTitle} lastSavedAt={lastSavedAt} From 230196c94ef0c17cb5d6505a6e8d6230118c589f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:33:15 +0000 Subject: [PATCH 6/9] test(studio): existing detail-page suites press Save and read the single-item publish Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufziBCAytAzzCu3iPBFR --- ...itPage.authoredObjectBuffer-29793.test.tsx | 30 +++++---- ...sourceEditPage.bundleMember-26649.test.tsx | 4 +- .../ResourceEditPage.celGate.test.tsx | 14 ++--- ...itPage.choiceWithoutOptions-11253.test.tsx | 32 ++++++---- ...ditPage.createFirstWritePin-11773.test.tsx | 17 ++++-- ...ditPage.draftPublishVerdict-26707.test.tsx | 4 +- ...rceEditPage.draftUnreadable-29148.test.tsx | 16 ++--- ...itPage.draftVersionConflict-11773.test.tsx | 56 ++++++++++------- ...ourceEditPage.layersUnsaved-11799.test.tsx | 33 ++++++---- ...eEditPage.pageRequiresStamp-11357.test.tsx | 9 ++- ...tPage.picklistServedOptions-10202.test.tsx | 14 +++-- ...rceEditPage.publishPackageBinding.test.tsx | 26 +++----- ...itPage.servedDraftTakenAsIs-10765.test.tsx | 61 ++++++++++--------- ...esourceEditPage.serverRefusalGate.test.tsx | 2 +- 14 files changed, 185 insertions(+), 133 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx index 1027982f25a..4d9b4f4aa4f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx @@ -183,6 +183,12 @@ function renderZh() { ); } +/** Save is explicit (objectstack#36902): wait for the unsaved edit, then press Save. */ +async function pressSave() { + await waitFor(() => expect(screen.getByTestId('save-status').getAttribute('data-state')).toBe('unsaved'), { timeout: 8000 }); + fireEvent.click(screen.getByTestId('resource-save')); +} + const editorDraft = (): Row => JSON.parse(screen.getByTestId('editor-draft').textContent ?? '{}') as Row; function expectAuthored(doc: Row, severityLabel: string) { @@ -196,7 +202,7 @@ function expectAuthored(doc: Row, severityLabel: string) { } describe('MetadataResourceEditPage in a zh-CN console — an object buffer is the authored document (objectstack#29793)', () => { - it('a pending draft: the buffer is the stored draft, one edit PUTs it in source labels with no injected column, and the publish refresh stays authored', async () => { + it('a pending draft: the buffer is the stored draft, one Save PUTs it in source labels with no injected column and publishes it, and the refresh stays authored', async () => { srv.draft = wire({ ...AUTHORED, description: 'draft only' }); renderZh(); @@ -204,20 +210,14 @@ describe('MetadataResourceEditPage in a zh-CN console — an object buffer is th expect(editorDraft()).toStrictEqual(wire({ ...AUTHORED, description: 'draft only' })); fireEvent.click(screen.getByRole('button', { name: 'relabel severity' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); const { body, opts } = srv.saves.at(-1)!; expect(opts).toMatchObject({ mode: 'draft' }); expectAuthored(body, 'Level'); expect(body.description).toBe('draft only'); - // The refresh after the save installs the stored draft again, not the served one. - await waitFor(() => expect((editorDraft().fields as Record).severity.label).toBe('Level'), { timeout: 8000 }); - expectAuthored(editorDraft(), 'Level'); - - // Publish: the refresh installs the promoted body as authored (`overlay`). - const publish = await screen.findAllByRole('button', { name: new RegExp(`^${t('engine.edit.publish', 'zh-CN')}$`) }, { timeout: 8000 }); - await waitFor(() => expect(publish[0]).toBeEnabled(), { timeout: 8000 }); - fireEvent.click(publish[0]!); + // The Save publishes the item, and the refresh installs the promoted body as authored (`overlay`). await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 }); await waitFor(() => expect(srv.draft).toBeNull(), { timeout: 8000 }); await act(async () => { @@ -233,6 +233,7 @@ describe('MetadataResourceEditPage in a zh-CN console — an object buffer is th expect(editorDraft()).toStrictEqual(wire(AUTHORED)); fireEvent.click(screen.getByRole('button', { name: 'relabel severity' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); expectAuthored(srv.saves.at(-1)!.body, 'Level'); }); @@ -401,17 +402,19 @@ describe.each(TRANSLATED_TYPES)( if (realTypePreview) registerMetadataPreview(spec.type, realTypePreview); }); - it('no pending draft: two edits in a row each PUT source text, the second after the save refresh re-read the draft', async () => { + it('no pending draft: two Saves in a row each PUT source text, the second after the save refresh re-read the published item', async () => { renderTypeZh(spec); await waitFor(() => expect(editorDraft().name).toBe(spec.name), { timeout: 8000 }); expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBe(1), { timeout: 8000 }); expect(srv.saves[0]!.opts).toMatchObject({ mode: 'draft' }); expect(spec.sourceText(srv.saves[0]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); - // The save refresh: the served draft is now the zh-CN one, the layers' the stored one. + // The Save published the draft; the refresh re-reads the stored row, in source text. + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 }); await waitFor(() => expect(mockClient.getDraft.mock.calls.length).toBeGreaterThan(1), { timeout: 8000 }); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); @@ -419,9 +422,11 @@ describe.each(TRANSLATED_TYPES)( expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBe(2), { timeout: 8000 }); expect(spec.sourceText(srv.saves[1]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); - expect(spec.sourceText(srv.draft!)).toStrictEqual(SOURCE_TEXT[spec.type]); + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(2), { timeout: 8000 }); + expect(spec.sourceText(srv.overlay!)).toStrictEqual(SOURCE_TEXT[spec.type]); }); it('a pending draft: the buffer is the stored draft, and one edit PUTs it in source text', async () => { @@ -431,6 +436,7 @@ describe.each(TRANSLATED_TYPES)( expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); expect(spec.sourceText(srv.saves.at(-1)!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx index 1e8e3c01270..4b9319f95e1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx @@ -193,7 +193,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 }); await settle(); - fireEvent.click(screen.getByTitle('Publish')); + fireEvent.click(screen.getByTestId('resource-draft-publish')); await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull()); await settle(); @@ -208,7 +208,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 }); await settle(); - fireEvent.click(screen.getAllByTitle('Discard draft')[0]!); + fireEvent.click(screen.getByTestId('resource-draft-discard')); await confirmDialog(); await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull()); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx index 678ed543aaa..4f6c82cf734 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx @@ -165,17 +165,17 @@ describe('MetadataResourceEditPage — Save is gated on the block inspector’s }); }); -describe('MetadataResourceEditPage — the save-status chip while the inspector holds auto-save (#29901)', () => { - // `inspectorBlocking` returns the auto-save effect early exactly as a server - // refusal does, so the chip must not promise an auto-save then either. +describe('MetadataResourceEditPage — the save-status chip while the inspector holds Save (#29901)', () => { + // `inspectorBlocking` holds Save exactly as a server refusal does, so the + // chip must not read as a plain unsaved edit then either. const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null; - it('reads the held state on a dangling operator, and the auto-save state once it parses', async () => { + it('reads the held state on a dangling operator, and the unsaved state once it parses', async () => { const box = await openBlockCel(); - // CONTROL first: a good predicate dirties the draft and reads auto-save. + // CONTROL first: a good predicate dirties the draft and reads unsaved. fireEvent.change(box, { target: { value: 'record.amount > 20' } }); - await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 }); + await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 }); fireEvent.change(box, { target: { value: 'record.amount >' } }); await waitFor(() => expect(chipState()).toBe('held'), { timeout: 4000 }); @@ -185,6 +185,6 @@ describe('MetadataResourceEditPage — the save-status chip while the inspector ); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); - await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 }); + await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 }); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx index 9c8e1a8665e..e8c5d9a2cc0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx @@ -15,8 +15,8 @@ * canvas and field inspector. The client is a real `MetadataClient`, whose * `save` is the door that runs the object write guard; only its transport and * the mount's reads are doubles. So the claim is read off the WIRE: no PUT - * carries a choice field without options, the held autosave says why and names - * the field, and one option lets the next autosave go (the control). + * carries a choice field without options, the held Save says why and names + * the field, and one option lets the next Save go (the control). */ import '@testing-library/jest-dom/vitest'; @@ -46,6 +46,13 @@ const OBJECT_ENTRY = { const puts: Array<{ url: string; body: Record }> = []; const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + // The Save's own publish and a refused publish's take-back (objectstack#36902). + if (init?.method === 'POST' || init?.method === 'DELETE') { + return new Response(JSON.stringify({ success: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + } if (init?.method === 'PUT') { puts.push({ url, body: JSON.parse(String(init.body)) as Record }); return new Response(JSON.stringify({ success: true }), { @@ -125,10 +132,11 @@ function choiceWithoutOptions(): WireField[] { ); } -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { +/** Press Save (a held Save is a disabled button, so the press sends nothing), and let any write leave. */ +async function pressSaveAndSettle(): Promise { + fireEvent.click(screen.getByTestId('resource-save')); await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); + await new Promise((r) => setTimeout(r, 300)); }); } @@ -137,7 +145,7 @@ describe('metadata-admin object editor — a new choice field is not sent withou ['select', 'Picklist', 'status'], ['radio', 'Radio', 'radio'], ] as const) { - it(`add a \`${type}\` from the palette, wait out the autosave: no request carries it without options`, async () => { + it(`add a \`${type}\` from the palette, press Save: no request carries it without options`, async () => { render( @@ -145,21 +153,23 @@ describe('metadata-admin object editor — a new choice field is not sent withou ); fireEvent.click(await screen.findByRole('button', { name: 'Add field' }, { timeout: 8000 })); fireEvent.click(await screen.findByRole('button', { name: paletteLabel })); - await outlastDebounce(); + await pressSaveAndSettle(); // Held: the seeded `options: []` never reached the wire. expect(choiceWithoutOptions()).toEqual([]); - const banner = await screen.findByText(new RegExp(`\`${seededName}\``)); - expect(banner).toHaveTextContent(/no options/); + const named = await screen.findAllByText(new RegExp(`\`${seededName}\``)); + expect(named.some((el) => /no options/.test(el.textContent ?? ''))).toBe(true); - // CONTROL: one option lets the next autosave go, and the banner clears. + // CONTROL: one option lets the next Save go, and the banner clears. fireEvent.change(await screen.findByPlaceholderText('value'), { target: { value: 'open' } }); + await waitFor(() => expect(screen.getByTestId('resource-save')).toBeEnabled(), { timeout: 4000 }); + fireEvent.click(screen.getByTestId('resource-save')); await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 4000 }); const sent = wireFields(puts[puts.length - 1].body).find((f) => f.name === seededName); expect(sent?.type).toBe(type); expect(sent?.options).toEqual([expect.objectContaining({ value: 'open' })]); expect(choiceWithoutOptions()).toEqual([]); - await waitFor(() => expect(screen.queryByText(new RegExp(`\`${seededName}\``))).toBeNull()); + await waitFor(() => expect(screen.queryAllByText(new RegExp(`\`${seededName}\``))).toHaveLength(0)); }); } }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx index fa9a6cd0783..4fd0ef537ec 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx @@ -30,6 +30,8 @@ import { MetadataClient } from '@object-ui/data-objectstack'; const server = { drafts: new Map; version: string }>(), + /** What a publish made live (objectstack#36902: a create's Save publishes it). */ + active: new Map>(), puts: [] as Array<{ name: string; ifMatch: string | null; ifNoneMatch: string | null; status: number }>, seq: 0, }; @@ -48,6 +50,13 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise ({ type: k.split('/')[0], name: k.split('/')[1] })) }); } if (seg.length === 1) return json(200, { items: [] }); + if (seg.length === 3 && seg[2] === 'publish' && method === 'POST') { + const row = server.drafts.get(key); + if (!row) return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); + server.active.set(key, row.body); + server.drafts.delete(key); + return json(200, { success: true, version: `sha256:${key}`, message: 'published' }); + } if (seg.length === 3) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); if (method === 'PUT') { const headers = new Headers(init?.headers); @@ -115,13 +124,12 @@ afterAll(() => { beforeEach(() => { server.drafts.clear(); + server.active.clear(); server.puts = []; server.seq = 0; - window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { cleanup(); - window.localStorage.removeItem('metadata-admin:autosave'); }); function Where() { @@ -161,11 +169,12 @@ async function createNewGuide() { } describe('MetadataResourceEditPage — a create sends If-None-Match: * (objectui#11773)', () => { - it('the create is sent with the first-write pin and no If-Match, and lands', async () => { + it('the create is sent with the first-write pin and no If-Match, and lands live', async () => { await createNewGuide(); await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/new_guide'), { timeout: 8000 }); expect(server.puts).toEqual([{ name: 'new_guide', ifMatch: null, ifNoneMatch: '*', status: 200 }]); - expect(server.drafts.get('doc/new_guide')?.body).toMatchObject({ name: 'new_guide', content: '# New' }); + expect(server.active.get('doc/new_guide')).toMatchObject({ name: 'new_guide', content: '# New' }); + expect(server.drafts.has('doc/new_guide')).toBe(false); }); it('a create over a name that already holds a draft is refused, and that draft is not written over', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx index d2eea563f23..075c009a34d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx @@ -175,13 +175,15 @@ describe('MetadataResourceEditPage — a pending draft is judged by its own serv ); }); - it('the verdict follows the draft: the refresh after an autosave of a fixed draft clears it', async () => { + it('the verdict follows the draft: the refresh after a Save of a fixed draft clears it', async () => { server.active.set('page/home', PAGE); server.drafts.set('page/home', { ...PAGE, label: 'broken' }); renderEditor(); await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).toContain(REFUSAL.message), { timeout: 8000 }); fireEvent.click(screen.getByRole('button', { name: 'fix the draft' })); + await waitFor(() => expect(screen.getByTestId('resource-save')).toBeEnabled(), { timeout: 8000 }); + fireEvent.click(screen.getByTestId('resource-save')); await waitFor(() => expect(server.saves).toBe(1), { timeout: 8000 }); await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).not.toContain(REFUSAL.message), { timeout: 8000 }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx index d6d0b5140b2..c37b2cc61d6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx @@ -97,7 +97,7 @@ vi.mock('./useMetadata', async (importOriginal) => { import { MetadataResourceEditPage } from './ResourceEditPage'; import { registerMetadataPreview, getMetadataPreview } from './preview-registry'; -/** Canvas stand-in: its only job is to dirty the buffer, which arms the real autosave. */ +/** Canvas stand-in: its only job is to dirty the buffer, which arms the real Save. */ function StubPageCanvas({ onPatch }: { onPatch?: (patch: Record) => void }) { return (