From af9b5c973aa095824e3db897f07f82d3ecf72647 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:51:52 +0000 Subject: [PATCH 1/5] fix(studio): pin the publish of the extension, hook, action and flow Saves (WIP) Claude-Session: https://claude.ai/code/session_011y7As6kDA9BVrMsBR9rmrJ Co-authored-by: Claude --- .../metadata-admin/DraftConflictDialog.tsx | 75 ++++++++-- .../studio-design/StudioDesignSurface.tsx | 136 ++++++++++++++---- .../views/studio-design/objectHooksBuffer.ts | 69 +++++++-- .../views/studio-design/pairObjectActions.ts | 49 ++++++- .../src/views/studio-design/studioSaveBar.tsx | 66 ++++++++- 5 files changed, 343 insertions(+), 52 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx index ff94bf10157..ef1d509493c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx @@ -93,6 +93,15 @@ * draft the Save just wrote is taken back before the buffer is re-read), * overwrite after the confirmation (re-sent pinned to the refusal's * `currentVersion`), or keep editing (nothing goes live). + * 9. objectstack#36726 — a reload whose `beforeReload` leaves a draft pending + * (`'kept'`: one that was there before the Save, a copilot's, which the + * Save wrote into and never discards) re-reads THAT draft, now carrying + * the page's edits. Its publish stays pinned to the version the conflict + * was raised on until the author re-confirms: the next Save is refused and + * asked again, and only an overwrite, a publish that lands, or a load that + * reads no pending draft (the buffer is then the live row) takes the + * fresh read's pin. A reload over a discarded draft re-reads the live row + * and is pinned to it at once, as before. */ import * as React from 'react'; @@ -112,6 +121,14 @@ import { GetMetaItemLayeredResponseSchema, GetMetaItemResponseSchema, MetadataCo import { errorCodeIs } from '@object-ui/types'; import { t, tFormat, translateMetadataType, useMetadataLocale } from './i18n.js'; +/** + * objectstack#36726 — what a publish conflict's `beforeReload` left at the + * item: `'discarded'`, the draft the Save wrote was taken back, so the reload + * re-reads the live row; `'kept'`, a draft pending before the Save stays (it + * carries the page's edits), so the reload re-reads that draft (rule 9). + */ +export type BeforeReloadOutcome = 'discarded' | 'kept'; + /** What a guarded save ended in, when it did not throw. */ export type DraftSaveOutcome = 'saved' | 'reloaded'; @@ -306,6 +323,13 @@ export class DraftVersionGuard { private readonly held = new Map(); /** objectstack#36601 — the published layer's pin per item, for the Save's publish (rules 6–8). */ private readonly published = new Map(); + /** + * objectstack#36726 — rule 9: per item, the published pin a conflict was + * raised on, held over a reload that re-read a pending draft until the + * author re-confirms; `fresh` is what the reload's load recorded meanwhile + * (absent until it has), taken once the item is confirmed. + */ + private readonly unconfirmed = new Map(); private tail: Promise | null = null; /** Bumped by a reload: a save queued before it carries the replaced buffer. */ private epoch = 0; @@ -324,15 +348,29 @@ export class DraftVersionGuard { /** The published pin held, for the item `publish` would address (tests read it). */ publishedFor(type: string, name: string, packageId?: string | null): DraftPin | null { - return this.published.get(itemKey(type, name, packageId)) ?? null; + const key = itemKey(type, name, packageId); + return this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; } /** The buffer was installed with no draft read behind it: nothing describes it. */ forget = (): void => { this.held.clear(); this.published.clear(); + this.unconfirmed.clear(); }; + /** + * objectstack#36726 — rule 9 ends for the item: its publish takes the pin + * the last load recorded, if one has since the reload. + */ + private confirm(key: string): void { + const entry = this.unconfirmed.get(key); + if (!entry) return; + this.unconfirmed.delete(key); + if (entry.fresh) this.published.set(key, entry.fresh); + else if (entry.fresh === null) this.published.delete(key); + } + /** * objectstack#36601 — the buffer was installed from a load whose `/layers` * read, at the address the buffer's publish writes, served `pin` @@ -340,30 +378,40 @@ export class DraftVersionGuard { */ recordPublished = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { const key = itemKey(type, name, packageId); + // objectstack#36726 — a reload that re-read a pending draft is not the + // author's answer to the conflict: the pin it was raised on stays (rule 9). + const entry = this.unconfirmed.get(key); + if (entry) { + entry.fresh = pin; + return; + } if (pin) this.published.set(key, pin); else this.published.delete(key); }; /** * objectstack#36601 — the Save's publish of the draft it just wrote, pinned - * to the published version this buffer holds (rules 6–8 above). Resolves + * to the published version this buffer holds (rules 6–9 above). Resolves * `'published'`, or `'reloaded'` when the author chose to reload after a * conflict (`beforeReload` has run, then the caller's reload); throws the * client's error otherwise, and the guard's "not saved" error when the - * author kept editing. + * author kept editing. `beforeReload` answers what it left at the item + * ({@link BeforeReloadOutcome}); one that answers nothing is `'discarded'`. */ publish = async ( client: Pick, type: string, name: string, options: { packageId?: string; member?: string } = {}, - beforeReload?: () => Promise, + beforeReload?: () => Promise, ): Promise<'published' | 'reloaded'> => { const key = itemKey(type, name, options.packageId); - let pin = this.published.get(key) ?? null; + let pin = this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null; for (;;) { try { const receipt = await client.publish(type, name, { ...options, ...(pin ?? {}) }); + // The publish the author's buffer was built for landed: rule 9 is over for it. + this.unconfirmed.delete(key); const version = receiptVersion(receipt); if (version) this.published.set(key, { ifMatch: version }); else this.published.delete(key); @@ -376,10 +424,14 @@ export class DraftVersionGuard { // A `beforeReload` that throws (its draft could not be taken back) // stops the reload here: nothing is re-read and the pins stay, so // the next Save is asked about again (contract review S2). - await beforeReload?.(); + const left = await beforeReload?.(); this.held.clear(); this.published.clear(); this.epoch += 1; + // objectstack#36726 — the reload re-reads the pending draft it kept, + // which carries the page's edits: never pinned to the fresh read's + // version, so its next Save is refused and asked again (rule 9). + if (left === 'kept' && pin) this.unconfirmed.set(key, { pin }); this.deps.reload(); return 'reloaded'; } @@ -389,7 +441,10 @@ export class DraftVersionGuard { throw kept; } // As for a draft: the re-send is pinned to the version the refusal - // names, so a publish landing in between is asked about again. + // names, so a publish landing in between is asked about again. The + // author has seen the live row move and chose this buffer over it: + // that is the re-confirmation rule 9 waits for. + this.unconfirmed.delete(key); pin = pinOfConflict(err); if (pin) this.published.set(key, pin); else this.published.delete(key); @@ -403,7 +458,11 @@ export class DraftVersionGuard { * {@link readDraftForSave} returned. `null` pins nothing, as `forget()`. */ recordRead = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => { - this.pin(itemKey(type, name, packageId), pin); + const key = itemKey(type, name, packageId); + this.pin(key, pin); + // objectstack#36726 — no draft is pending at the address: the buffer is + // the live row, which the load's published read describes (rule 9 ends). + if (pin && 'ifNoneMatch' in pin) this.confirm(key); }; /** diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index 63f39f857c6..37b513c55e3 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -324,6 +324,9 @@ import { emitMetadataRefresh, subscribeMetadataRefresh } from '../../assistant/a import { STUDIO_CHANGES_PARAM, STUDIO_CHANGES_REVIEW } from './studioChangesLink.js'; import { publishSavedItem, + publishCreated, + publishedPinOfLayers, + readPublishedPin, STUDIO_SAVE_TOAST_ID, StudioSaveControls, StudioSaveProvider, @@ -5713,6 +5716,8 @@ export function DataPillar({ const [extHasDraft, setExtHasDraft] = React.useState(false); const [extReloadNonce, setExtReloadNonce] = React.useState(0); const extLoadedRef = React.useRef(null); + // objectstack#36726 — the pair the open extension buffer was read at (`null`: none was listed). + const extReadAtRef = React.useRef<{ name: string; pair: string | null } | null>(null); const extOpen = extendsBase && ext !== null && ext.for === current?.name ? ext : null; // Adding a field asks the ensure door for the pair once per base: its // answer names every write, ⛔ never a `.custom` spelled here. @@ -6037,6 +6042,9 @@ export function DataPillar({ const { save: saveExtDraft, recordRead: recordExtRead, + // objectstack#36726 — and the pair's published extension row, for the Save's publish. + recordPublished: recordExtPublished, + publish: publishExt, dialog: extConflictDialog, } = useDraftSaveGuard(client, reloadExt); // The pair a READ names is the surface's (`StudioBaseCustomization.pairId`), @@ -6401,6 +6409,13 @@ export function DataPillar({ let draft: ObjectExtensionBody | null = null; let published: ObjectExtensionBody | null = null; if (pair) { + // objectstack#36726 — the published extension's version at the pair, + // the address the Save's publish writes, read BEFORE the rows below + // (the server's own order for `/layers`): a publish landing between + // the reads leaves the pin older than the buffer, so the next Save + // is asked about, never published over it. + const publishedAt = await readPublishedPin(client, OBJECT_EXTENSION_TYPE, name, pair); + if (cancelled) return; const [draftRead, publishedRow] = await Promise.all([ readDraftForSave>(client, OBJECT_EXTENSION_TYPE, name, pair), client.get>(OBJECT_EXTENSION_TYPE, name, { packageId: pair }), @@ -6420,8 +6435,10 @@ export function DataPillar({ draft = objectExtensionBodyOf(extractDraftBody(draftRead.answer), name); published = objectExtensionBodyOf(publishedRow, name); recordExtRead(OBJECT_EXTENSION_TYPE, name, pair, draftRead.pin); + recordExtPublished(OBJECT_EXTENSION_TYPE, name, pair, publishedAt); } if (refreshOnly) refreshInstalledRef.current = true; + extReadAtRef.current = { name, pair }; setExt({ for: name, body: draft ?? published ?? { extend: name }, published: new Set(extensionFieldNames(published)) }); setExtHasDraft(draft !== null); } catch (e) { @@ -6435,7 +6452,7 @@ export function DataPillar({ // A load cancelled before it settled takes its claim back (see the object load above). if (!settled) extLoadedRef.current = null; }; - }, [client, current, extendsBase, publishNonce, extReloadNonce, objRefreshNonce, recordExtRead]); + }, [client, current, extendsBase, publishNonce, extReloadNonce, objRefreshNonce, recordExtRead, recordExtPublished]); // objectstack#32610 — a field the pulse's re-read no longer has (a discard // took it away) is not left selected; one it still has stays open. @@ -6873,6 +6890,14 @@ export function DataPillar({ const hadDraft = extHasDraft; try { const pair = await extPairFor(customization); + // objectstack#36726 — a buffer read before any pair was listed read no + // row there: its publish asserts none, so an extension another writer + // published at the pair meanwhile is asked about, never replaced. + const readAt = extReadAtRef.current; + if (readAt?.name === name && readAt.pair !== pair) { + recordExtPublished(OBJECT_EXTENSION_TYPE, name, pair, { ifNoneMatch: '*' }); + extReadAtRef.current = { name, pair }; + } const outcome = await saveExtDraft(OBJECT_EXTENSION_TYPE, name, extensionBodyForSave(body), { mode: 'draft', packageId: pair, @@ -6881,18 +6906,29 @@ export function DataPillar({ if (outcome === 'reloaded') return { kind: 'declined' }; setExtHasDraft(true); setSaving('publish'); - const live = await publishSavedItem(client, { type: OBJECT_EXTENSION_TYPE, name, packageId: pair }, hadDraft); + // objectstack#36726 — pinned to the published extension row this buffer was loaded at. + const live = await publishSavedItem( + client, + { type: OBJECT_EXTENSION_TYPE, name, packageId: pair }, + hadDraft, + publishExt, + ); + // The published row moved and the author chose to reload: the load replaces the buffer. + if (!live.ok && 'reloaded' in live) return { kind: 'declined' }; if (!live.ok) { if (live.draftDiscarded) { setExtHasDraft(false); recordExtRead(OBJECT_EXTENSION_TYPE, name, pair, { ifNoneMatch: '*' }); } - const refusal = publishRefusal( - publishFailureOf(OBJECT_EXTENSION_TYPE, name, live.error), - OBJECT_EXTENSION_TYPE, - extensionBodyForSave(body), - locale, - ); + // The published row moved and the author kept editing: read as the draft conflict's "not saved". + const refusal = isPublishConflictKeptEditing(live.error) + ? plainRefusal(live.error) + : publishRefusal( + publishFailureOf(OBJECT_EXTENSION_TYPE, name, live.error), + OBJECT_EXTENSION_TYPE, + extensionBodyForSave(body), + locale, + ); setError(refusal); return { kind: 'refused', reason: refusal.message }; } @@ -6907,7 +6943,7 @@ export function DataPillar({ } finally { setSaving(false); } - }, [extOpen, customization, extPairFor, saveExtDraft, recordExtRead, client, extHasDraft, locale]); + }, [extOpen, customization, extPairFor, saveExtDraft, recordExtRead, recordExtPublished, publishExt, client, extHasDraft, locale]); // An edit of the folded object's fields, written into the extension: an // extension field whole, a base field's whitelisted change as its patch. const onExtFieldsPatch = React.useCallback( @@ -8595,6 +8631,9 @@ export function AutomationsPillar({ const { save: saveFlowDraft, recordRead: recordFlowRead, + // objectstack#36726 — and the published flow the buffer was loaded at, for the Save's publish. + recordPublished: recordFlowPublished, + publish: publishFlow, dialog: flowConflictDialog, } = useDraftSaveGuard(client, reloadFlowDraft); const [selection, setSelection] = React.useState(null); @@ -8910,9 +8949,16 @@ export function AutomationsPillar({ }); // objectstack#36511 — and published at once, switched off as it was // born: no draft is left for a package publish, and the switch arms it. - const live = await publishSavedItem(client, { type: 'flow', name, packageId: target ?? railPackageId }, false); + // objectstack#36726 — pinned `If-None-Match: *`: a flow another writer + // published under the name since the check above is refused, not replaced. + const live = await publishSavedItem( + client, + { type: 'flow', name, packageId: target ?? railPackageId }, + false, + publishCreated, + ); if (!live.ok) { - setError(plainRefusal(live.error)); + if ('error' in live) setError(plainRefusal(live.error)); return; } const item: Surface = target === null ? { type: 'flow', name, label } : { type: 'flow', name, label, addedIn: target }; @@ -8957,6 +9003,21 @@ export function AutomationsPillar({ // read-only base's flow: its pair, when one is listed. const pair = flowCustomizing && !current.addedIn ? (customizationRef.current?.pairId ?? null) : null; const readAt = pair ?? draftPackageId; + // objectstack#36726 — the published flow's layers at the address the + // Save's publish writes, read FIRST (the server's order for the + // version and the body): a publish landing between this and the reads + // below leaves the pin older than the buffer, so the next Save is + // asked about, never published over it. At the drafts' own package it + // is also the baseline read below. + const baselineScope = draftPackageId ? { packageId: draftPackageId } : {}; + const layAtReadAt = await client + .layered>('flow', current.name, readAt ? { packageId: readAt } : {}) + .then( + (lay) => ({ ok: true as const, lay }), + (err: unknown) => ({ ok: false as const, err }), + ); + if (cancelled) return; + const publishedAt = layAtReadAt.ok ? publishedPinOfLayers(layAtReadAt.lay) : null; const draftRead = await readDraftForSave>(client, 'flow', current.name, readAt); if (cancelled) return; // objectstack#29148 — a flow draft the server refused to read is no @@ -8977,13 +9038,16 @@ export function AutomationsPillar({ // ADR-0048 — at the package the flow saves write, its owner here; with // none, the read names none, and a name two packages hold is refused // with the server's own sentence, shown as the load's error. - const layRaw = draftBody - ? null - : await client.layered>( - 'flow', - current.name, - draftPackageId ? { packageId: draftPackageId } : {}, - ); + let layRaw: unknown = null; + if (!draftBody) { + if (readAt === draftPackageId) { + // The read above, at this same address: its refusal is the load's error, as it always was. + if (!layAtReadAt.ok) throw layAtReadAt.err; + layRaw = layAtReadAt.lay; + } else { + layRaw = await client.layered>('flow', current.name, baselineScope); + } + } if (cancelled) return; const lay = layRaw as { effective?: Record; code?: Record } | null; const baseline = (lay?.effective ?? lay?.code ?? {}) as Record; @@ -9001,6 +9065,8 @@ export function AutomationsPillar({ ); // objectui#11773 — the next save is pinned to what the draft read served. recordFlowRead('flow', current.name, readAt, draftRead.pin); + // objectstack#36726 — …and its publish to the published flow the layers served there. + recordFlowPublished('flow', current.name, readAt, publishedAt); flowReadAtRef.current = { key: `flow:${current.name}`, at: readAt }; setHasDraft(!!draftBody); setFlowDraftChanges(draftBody ? readDraftChanges(draftRead.answer) : null); @@ -9020,7 +9086,7 @@ export function AutomationsPillar({ // `loading` it raised, as in InterfacesPillar's draft load. if (!settled) setLoading(false); }; - }, [client, current, draftPackageId, publishNonce, flowReloadNonce, recordFlowRead, flowCustomizing]); + }, [client, current, draftPackageId, publishNonce, flowReloadNonce, recordFlowRead, recordFlowPublished, flowCustomizing]); // objectui#5813 — local dirty flag: auto-save arms only after a real edit. const [autoDirty, setAutoDirty] = React.useState(false); @@ -9077,6 +9143,9 @@ export function AutomationsPillar({ const key = `flow:${current.name}`; if (!(flowReadAtRef.current?.key === key && flowReadAtRef.current.at === pair)) { recordFlowRead('flow', current.name, pair, { ifNoneMatch: '*' }); + // objectstack#36726 — and to hold no live row of it: one published + // there meanwhile is asked about, never replaced. + recordFlowPublished('flow', current.name, pair, { ifNoneMatch: '*' }); flowReadAtRef.current = { key, at: pair }; } entering = !flowInPairRef.current; @@ -9092,17 +9161,24 @@ export function AutomationsPillar({ // The badge reads the declaration the server now serves. if (entering) setServedNonce((n) => n + 1); setSaving('publish'); + // objectstack#36726 — pinned to the published flow this buffer was loaded at. const live = await publishSavedItem( client, { type: 'flow', name: current.name, packageId: target.packageId ?? null }, hadDraft, + publishFlow, ); + // The published flow moved and the author chose to reload: the load replaces the buffer. + if (!live.ok && 'reloaded' in live) return { kind: 'declined' }; if (!live.ok) { setHasDraft(!live.draftDiscarded); if (live.draftDiscarded) recordFlowRead('flow', current.name, target.packageId, { ifNoneMatch: '*' }); // objectstack#26858 — what the pending draft now says, or the live flow's verdict. rereadFlowVerdict(current.name, target.packageId); - const refusal = publishRefusal(publishFailureOf('flow', current.name, live.error), 'flow', target.body, locale); + // The published flow moved and the author kept editing: read as the draft conflict's "not saved". + const refusal = isPublishConflictKeptEditing(live.error) + ? flowSaveRefusal(live.error, target.body, locale) + : publishRefusal(publishFailureOf('flow', current.name, live.error), 'flow', target.body, locale); setError(refusal); return { kind: 'refused', reason: refusal.message }; } @@ -9126,7 +9202,7 @@ export function AutomationsPillar({ } finally { setSaving(false); } - }, [saveFlowDraft, client, current, draft, hasDraft, draftPackageId, locale, rereadFlowVerdict, readOnly, pairForFlow, recordFlowRead]); + }, [saveFlowDraft, publishFlow, client, current, draft, hasDraft, draftPackageId, locale, rereadFlowVerdict, readOnly, pairForFlow, recordFlowRead, recordFlowPublished]); // objectui#11786 — an edit that leaves a step's required input out (a step // just added, before it is filled in) is held, not sent: the server would // refuse the flow with a 422 naming that input. The step's inspector hints the @@ -9237,12 +9313,24 @@ export function AutomationsPillar({ // objectui#11773 — a reload replaced the buffer the flip was taken on. if ((await saveFlowDraft('flow', flowName, stored, { mode: 'draft', packageId: draftPackageId, surface: 'studio' })) === 'reloaded') return; setSaving('publish'); - const live = await publishSavedItem(client, { type: 'flow', name: flowName, packageId: draftPackageId ?? null }, hadDraft); + // objectstack#36726 — pinned to the published flow this buffer was loaded at, as the Save is. + const live = await publishSavedItem( + client, + { type: 'flow', name: flowName, packageId: draftPackageId ?? null }, + hadDraft, + publishFlow, + ); + // The author chose to reload: the load replaces the buffer, the switch with it. + if (!live.ok && 'reloaded' in live) return; if (!live.ok) { setHasDraft(!live.draftDiscarded); if (live.draftDiscarded) recordFlowRead('flow', flowName, draftPackageId, { ifNoneMatch: '*' }); rollBack(); - setError(publishRefusal(publishFailureOf('flow', flowName, live.error), 'flow', stored, locale)); + setError( + isPublishConflictKeptEditing(live.error) + ? flowSaveRefusal(live.error, stored, locale) + : publishRefusal(publishFailureOf('flow', flowName, live.error), 'flow', stored, locale), + ); return; } setHasDraft(false); @@ -9257,7 +9345,7 @@ export function AutomationsPillar({ } finally { setSaving(false); } - }, [saveFlowDraft, client, current, draft, draftFor, hasDraft, draftPackageId, locale, readOnly, recordFlowRead, rereadFlowVerdict]); + }, [saveFlowDraft, publishFlow, client, current, draft, draftFor, hasDraft, draftPackageId, locale, readOnly, recordFlowRead, rereadFlowVerdict]); // The rail's "+" — and the empty block's button, which runs this same // handler (objectui#12514). objectui#11553 — no "New" in the package-less diff --git a/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts b/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts index c414ddcc06e..db3ba9e8b7c 100644 --- a/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts +++ b/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts @@ -23,12 +23,19 @@ * expression check reports an error, hold the Save with a named clause. * - Each save is pinned to the draft version the list read served * (objectui#11773); a new hook's first write asserts no draft row. + * - objectstack#36726 — and each Save's publish to the published hook the + * load read (`/layers`' `overlayVersion`, at the package the publish + * writes): a hook another editor published since is refused and asked + * about (reload, overwrite, keep editing), never replaced in silence. A + * published hook pinned so is buffered from that same answer, so the pin + * always describes the body it publishes. A new hook's publish asserts no + * published row. */ import * as React from 'react'; -import { extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack'; +import { authoredPublished, extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack'; import { useMetadataClient } from '../metadata-admin/useMetadata.js'; -import { readDraftForSave, useDraftSaveGuard, type DraftPin } from '../metadata-admin/DraftConflictDialog.js'; +import { publishedPinOf, readDraftForSave, useDraftSaveGuard, type DraftPin } from '../metadata-admin/DraftConflictDialog.js'; import type { HookTargetScope } from '../metadata-admin/inspectors/HookDefaultInspector.js'; import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; import { loadPackageSurfaces } from './packageSurfaces.js'; @@ -141,10 +148,15 @@ export function useObjectHooksBuffer({ const [saving, setSaving] = React.useState(false); const [nonce, setNonce] = React.useState(0); const reloadHooks = React.useCallback(() => setNonce((n) => n + 1), []); - const { save: saveHookDraft, recordRead: recordHookRead, forget: forgetHookVersion, dialog } = useDraftSaveGuard( - client, - reloadHooks, - ); + const { + save: saveHookDraft, + recordRead: recordHookRead, + forget: forgetHookVersion, + // objectstack#36726 — the published hook each buffer was loaded at, for the Save's publish. + recordPublished: recordHookPublished, + publish: publishHook, + dialog, + } = useDraftSaveGuard(client, reloadHooks); React.useEffect(() => { forgetHookVersion(); }, [publishNonce, forgetHookVersion]); @@ -265,14 +277,41 @@ export function useObjectHooksBuffer({ if (read.answer !== null) pending.add(n); } }); + // objectstack#36726 — each listed hook's layers at the package its + // publish writes: the published version its Save's publish is pinned + // to. A published hook with no pending draft is buffered from that same + // answer, so the pin describes the body; an answer that pins nothing + // (a server that serves no version, a read that failed) leaves the + // listed body and an unpinned publish, as before. + const listedNames = [...byName.keys()]; + const layers = await Promise.all( + listedNames.map((n) => + Promise.resolve() + .then(() => client.layered>('hook', n, { packageId })) + .catch(() => null), + ), + ); + if (cancelled) return; + const publishedPins = new Map(); + listedNames.forEach((n, i) => { + const pin = publishedPinOf(layers[i]); + publishedPins.set(n, pin); + if (!pin || pending.has(n) || refused.has(n)) return; + const body = authoredPublished('hook', layers[i]) as HookItem; + if (body.name !== undefined && targetsObject(body, objectName)) byName.set(n, body); + // The layers say the hook no longer fires here: its publish is not this buffer's to pin. + else publishedPins.set(n, null); + }); setListed([...byName.values()]); setRefusedHooks(refused); setDrafted(pending); - // A hook whose buffer holds an unsent edit keeps the pin that edit was built on. + // A hook whose buffer holds an unsent edit keeps the pins that edit was built on. const open = bufferRef.current; for (const [n, pin] of pins) { if (publishNonceRef.current !== publishAtStart) break; - if (!(open.dirty && open.hook === n)) recordHookRead('hook', n, packageId, pin); + if (open.dirty && open.hook === n) continue; + recordHookRead('hook', n, packageId, pin); + recordHookPublished('hook', n, packageId, publishedPins.get(n) ?? null); } } catch (e) { if (!cancelled) setError(formatMetadataError(e)); @@ -283,7 +322,7 @@ export function useObjectHooksBuffer({ return () => { cancelled = true; }; - }, [client, packageId, objectName, nonce, recordHookRead, live]); + }, [client, packageId, objectName, nonce, recordHookRead, recordHookPublished, live]); // Load the selected hook into the buffer: on a selection change and when the // list changes, except over an unsent edit of that same hook. @@ -362,7 +401,15 @@ export function useObjectHooksBuffer({ setEdited(false); return { kind: 'declined' }; } - const outcome = await publishSavedItem(client, { type: 'hook', name, packageId }, hadDraft); + // objectstack#36726 — a new hook's publish asserts no published row of its name. + if (isNew) recordHookPublished('hook', name, packageId, { ifNoneMatch: '*' }); + const outcome = await publishSavedItem(client, { type: 'hook', name, packageId }, hadDraft, publishHook); + // The published hook moved and the author chose to reload: the list re-read installs it. + if (!outcome.ok && 'reloaded' in outcome) { + if (isNew) setCreated(null); + setEdited(false); + return { kind: 'declined' }; + } if (!outcome.ok) { if (outcome.draftDiscarded) { recordHookRead('hook', name, packageId, { ifNoneMatch: '*' }); @@ -403,7 +450,7 @@ export function useObjectHooksBuffer({ } finally { setSaving(false); } - }, [client, draft, draftFor, created, drafted, packageId, objectName, saveHookDraft, recordHookRead]); + }, [client, draft, draftFor, created, drafted, packageId, objectName, saveHookDraft, recordHookRead, recordHookPublished, publishHook]); const cancel = React.useCallback(() => { setError(null); diff --git a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts index cb0feb8cddc..58f0a758991 100644 --- a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts +++ b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts @@ -42,6 +42,11 @@ * draft, else the published action. A row whose stored copy is not served * (`unserved`) stays listed and is not edited: ⛔ never buffered from the * served copy. + * + * objectstack#36726 — that same layered answer's `overlayVersion` pins each + * row's publish: a row another editor published since is refused and asked + * about (reload, overwrite, keep editing), never replaced in silence. A new + * row's publish asserts no published row of its name. */ import * as React from 'react'; @@ -49,7 +54,12 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { authoredBuffer, extractDraftBody, formatMetadataError, type AuthoredLayers } from '@object-ui/data-objectstack'; import { useMetadataClient } from '../metadata-admin/useMetadata.js'; import { t as tStudio, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; -import { readDraftForSave, useDraftSaveGuard, type DraftPin } from '../metadata-admin/DraftConflictDialog.js'; +import { + publishedPinOf, + readDraftForSave, + useDraftSaveGuard, + type DraftPin, +} from '../metadata-admin/DraftConflictDialog.js'; import { publishSavedItem, useStudioSaveEntry, type StudioSaveResult } from './studioSaveBar.js'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import type { RailCustomizations } from './StudioRailCustomizations.js'; @@ -164,7 +174,15 @@ export function usePairObjectActions( const [blocking, setBlocking] = React.useState>>({}); const [nonce, setNonce] = React.useState(0); const reload = React.useCallback(() => setNonce((n) => n + 1), []); - const { save: saveGuarded, recordRead, forget, dialog } = useDraftSaveGuard(client, reload); + const { + save: saveGuarded, + recordRead, + forget, + // objectstack#36726 — the published action each row was loaded at, for the Save's publish. + recordPublished, + publish: publishGuarded, + dialog, + } = useDraftSaveGuard(client, reload); React.useEffect(() => { forget(); }, [publishNonce, forget]); @@ -275,7 +293,11 @@ export function usePairObjectActions( return { for: objectName, pair: readAt, list: [...merged, ...added] }; }); for (const [name, pin] of pins) { - if (!open.edited.has(name)) recordRead('action', name, readAt, pin); + if (open.edited.has(name)) continue; + recordRead('action', name, readAt, pin); + // objectstack#36726 — the row's publish, to the published action the same layers served. + const at = listed.indexOf(name); + recordPublished('action', name, readAt, at < 0 ? null : publishedPinOf(layers[at])); } setError(null); } catch (e) { @@ -285,7 +307,7 @@ export function usePairObjectActions( return () => { cancelled = true; }; - }, [client, active, pairId, objectName, publishNonce, nonce, recordRead]); + }, [client, active, pairId, objectName, publishNonce, nonce, recordRead, recordPublished]); const all = active && rows !== null && rows.for === objectName && (rows.pair === pairId || rows.pair === null) ? rows.list : NO_ROWS; const list = React.useMemo(() => (removed.size === 0 ? all : all.filter((r) => !removed.has(r.name))), [all, removed]); @@ -401,10 +423,25 @@ export function usePairObjectActions( setEdited(new Set()); continue; } - const outcome = await publishSavedItem(client, { type: 'action', name, packageId: pair }, row.draft); + // objectstack#36726 — a new row's publish asserts no published action of its name. + if (isNew) recordPublished('action', name, pair, { ifNoneMatch: '*' }); + const outcome = await publishSavedItem(client, { type: 'action', name, packageId: pair }, row.draft, publishGuarded); + // The published action moved and the author chose to reload: the pair's read installs it. + if (!outcome.ok && 'reloaded' in outcome) { + setEdited(new Set()); + if (isNew) { + setCreated((prev) => { + const next = new Set(prev); + next.delete(name); + return next; + }); + } + continue; + } if (!outcome.ok) { if (outcome.draftDiscarded) recordRead('action', name, pair, { ifNoneMatch: '*' }); else setRows((prev) => (prev === null ? prev : { ...prev, list: prev.list.map((r) => (r.name === name ? { ...r, draft: true } : r)) })); + // Kept editing reads as the draft conflict's own "not saved" line, as for a draft that moved. refusals.push(`${String(row.body.label ?? name)}: ${formatMetadataError(outcome.error)}`); continue; } @@ -445,7 +482,7 @@ export function usePairObjectActions( return { kind: 'refused', reason }; } return { kind: 'saved' }; - }, [client, created, edited, removed, pairForWrite, saveGuarded, recordRead, reload]); + }, [client, created, edited, removed, pairForWrite, saveGuarded, publishGuarded, recordRead, recordPublished, reload]); const cancel = React.useCallback(() => { setError(null); diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index 16e9b6db172..ae5d95e8474 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -43,7 +43,12 @@ import type { MetadataClient } from '@object-ui/data-objectstack'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { t, tFormat } from '../metadata-admin/i18n.js'; import { LINT_DEBOUNCE_MS } from '../metadata-admin/celLintDebounce.js'; -import type { DraftSaveGuard } from '../metadata-admin/DraftConflictDialog.js'; +import { + publishedPinOf, + type BeforeReloadOutcome, + type DraftPin, + type DraftSaveGuard, +} from '../metadata-admin/DraftConflictDialog.js'; /** Past the editors' expression check of the last keystroke, and its report. */ const VERDICT_SETTLE_MS = LINT_DEBOUNCE_MS + 50; @@ -270,6 +275,55 @@ export type PublishSavedOutcome = */ export type PinnedPublish = DraftSaveGuard['publish']; +/** + * objectstack#36726 — a load's `/layers` read at the address its Save's + * publish writes, for the published pin alone ({@link publishedPinOf}). Read + * it BEFORE the reads the buffer is installed from, as the server reads the + * version before the body: a publish landing in between leaves the pin older + * than the buffer, and the Save is asked about instead of publishing over it. + * + * No layer at all at the address (the door's 404, which the client answers as + * the empty view) is no published row there: `If-None-Match: *`, so a row + * another writer publishes first is refused, never replaced. A read that + * fails says nothing about the row and pins nothing; so does a served answer + * without `overlayVersion` (a server from before it was served). + */ +export async function readPublishedPin( + client: Pick, + type: string, + name: string, + packageId: string | null | undefined, +): Promise { + let layered: unknown; + try { + layered = await client.layered(type, name, packageId ? { packageId } : {}); + } catch { + return null; + } + return publishedPinOfLayers(layered); +} + +/** {@link readPublishedPin}'s reading of an answer the caller already holds. */ +export function publishedPinOfLayers(layered: unknown): DraftPin | null { + const pin = publishedPinOf(layered); + if (pin) return pin; + const l = (layered ?? {}) as { code?: unknown; overlay?: unknown; effective?: unknown; draft?: unknown }; + const absent = l.code == null && l.overlay == null && l.effective == null && l.draft == null; + return absent ? { ifNoneMatch: '*' } : null; +} + +/** + * objectstack#36726 — the publish of an item a create has just written, pinned + * `If-None-Match: *`: no live row was there when the create checked, so a row + * another writer published under the name since is refused `409` instead of + * replaced. For a create with no loaded buffer to reload (a new flow), the + * refusal is the create's own: no dialog is asked. + */ +export const publishCreated: PinnedPublish = async (client, type, name, options = {}) => { + await client.publish(type, name, { ...options, ifNoneMatch: '*' }); + return 'published'; +}; + /** * Make the draft a Save just wrote live: that one item's publish, at the * package the draft was written to (`?package=`), never the package's batch. @@ -284,6 +338,8 @@ export type PinnedPublish = DraftSaveGuard['publish']; * published version the buffer was loaded at, so a Save over a row another * editor published since is refused and asked about (reload or overwrite) * instead of replacing it. Omitted, the publish is unpinned, as before. + * objectstack#36726 — every Studio editor that saves this way passes it; a + * create passes {@link publishCreated} where no buffer is loaded behind it. */ export async function publishSavedItem( client: Pick, @@ -320,10 +376,14 @@ export async function publishSavedItem( // publish the losing copy without a prompt. Its failure throws instead: the // guard does not reload, keeps the published pin the conflict was raised // on, and the Save reads as refused, edits on the page. - const discardBeforeReload = async (): Promise => { - if (hadDraft) return; + // objectstack#36726 — a draft pending before the Save is kept, never + // discarded: the guard is told so, and the reload that re-reads it stays + // pinned to the published version the conflict was raised on. + const discardBeforeReload = async (): Promise => { + if (hadDraft) return 'kept'; await client.reset(item.type, item.name, { state: 'draft', ...scope }); draftDiscarded = true; + return 'discarded'; }; try { if (pinned) { From 6a88328ad4918ae2e8dda61e774b46196d388e60 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:14:12 +0000 Subject: [PATCH 2/5] test(studio): race pins for the extension, hook, action and flow Saves' publish (WIP) Claude-Session: https://claude.ai/code/session_011y7As6kDA9BVrMsBR9rmrJ Co-authored-by: Claude --- .../DraftConflictDialog.test.tsx | 92 +++++ ...mationsPillar.publishPinned-36726.test.tsx | 347 ++++++++++++++++ ...llar.extensionPublishPinned-36726.test.tsx | 356 ++++++++++++++++ ...ar.pairActionsPublishPinned-36726.test.tsx | 379 ++++++++++++++++++ ...ectHooksPanel.publishPinned-36726.test.tsx | 324 +++++++++++++++ ...urface.draftVersionConflict-11773.test.tsx | 55 +++ .../views/studio-design/pairObjectActions.ts | 6 +- 7 files changed, 1558 insertions(+), 1 deletion(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/AutomationsPillar.publishPinned-36726.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/DataPillar.extensionPublishPinned-36726.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx index d6b6c299e24..a91331de548 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx @@ -626,3 +626,95 @@ describe('DraftVersionGuard — the Save\'s publish is pinned to the published r expect(unpinned.state.sent).toEqual([[null, null]]); }); }); + +describe('DraftVersionGuard — a reload that keeps a pending draft keeps the publish pinned until the author re-confirms (objectstack#36726)', () => { + const NAME = 'acme_task'; + + /** A publish door over one live row, the refusal parsed by the real client. */ + function liveDoor(live: string) { + const state = { live, sent: [] as Array }; + const fetchImpl = (async (_input: RequestInfo | URL, init?: RequestInit) => { + const ifMatch = new Headers(init?.headers).get('If-Match'); + state.sent.push(ifMatch); + if (ifMatch !== null && ifMatch !== state.live) { + return json(409, { error: 'The published row moved.', code: 'METADATA_CONFLICT', currentVersion: state.live }); + } + state.live = v(200 + state.sent.length); + return json(200, { success: true, version: state.live, seq: 1 }); + }) as typeof fetch; + return { state, client: new MetadataClient({ baseUrl: 'http://localhost:3000', fetch: fetchImpl }) }; + } + + function guardAnswering(...answers: DraftConflictChoice[]) { + const queue = [...answers]; + const ask = vi.fn(async () => queue.shift() ?? 'cancel'); + const guard = new DraftVersionGuard({ + client: () => measuredDoor().client, + ask, + reload: vi.fn(), + notSaved: (c) => new Error(`not saved: ${c.type}/${c.name}`), + }); + return { guard, ask }; + } + + /** The conflict, answered "reload", then the reload's load: its draft read and its fresh `/layers` read. */ + async function reloadOverPendingDraft( + left: 'kept' | 'discarded', + order: 'read-first' | 'layers-first' = 'read-first', + ...later: DraftConflictChoice[] + ) { + const door = liveDoor(v(2)); + const { guard, ask } = guardAnswering('reload', ...later); + guard.recordPublished('object', NAME, PKG, { ifMatch: v(1) }); + expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG }, async () => left)).toBe('reloaded'); + const draftPin = left === 'kept' ? { ifMatch: v(9) } : ({ ifNoneMatch: '*' } as const); + if (order === 'read-first') guard.recordRead('object', NAME, PKG, draftPin); + guard.recordPublished('object', NAME, PKG, { ifMatch: v(2) }); + if (order === 'layers-first') guard.recordRead('object', NAME, PKG, draftPin); + return { door, guard, ask }; + } + + it('kept: the fresh read does not replace the pin the conflict was raised on, and the next publish is asked again', async () => { + const { door, guard, ask } = await reloadOverPendingDraft('kept'); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) }); + await expect(guard.publish(door.client, 'object', NAME, { packageId: PKG })).rejects.toThrow(/not saved/); + expect(ask).toHaveBeenCalledTimes(2); + expect(door.state.sent).toEqual([v(1), v(1)]); + expect(door.state.live).toBe(v(2)); + }); + + it('discarded: the reload re-read the live row, and is pinned to it at once', async () => { + const { door, guard } = await reloadOverPendingDraft('discarded'); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(2) }); + expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG })).toBe('published'); + expect(door.state.sent).toEqual([v(1), v(2)]); + }); + + it('kept, then the author overwrites: re-sent pinned to the refusal\'s currentVersion, and the receipt pins the next', async () => { + const { door, guard } = await reloadOverPendingDraft('kept', 'read-first', 'overwrite'); + expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG })).toBe('published'); + expect(door.state.sent).toEqual([v(1), v(1), v(2)]); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: door.state.live }); + }); + + it('a load that reads no pending draft ends it: the fresh pin is taken, whichever read is recorded first', async () => { + for (const order of ['read-first', 'layers-first'] as const) { + const { guard } = await reloadOverPendingDraft('kept', order); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) }); + guard.recordRead('object', NAME, PKG, { ifNoneMatch: '*' }); + // Recorded before the release: taken now. Recorded after: taken as usual. + guard.recordPublished('object', NAME, PKG, { ifMatch: v(2) }); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(2) }); + } + }); + + it('`forget` ends it too, and the pin it held for another item survives a reload of this one', async () => { + const { guard } = await reloadOverPendingDraft('kept', 'read-first', 'reload'); + const other = liveDoor(v(5)); + guard.recordPublished('object', 'acme_other', PKG, { ifMatch: v(4) }); + expect(await guard.publish(other.client, 'object', 'acme_other', { packageId: PKG }, async () => 'discarded')).toBe('reloaded'); + expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) }); + guard.forget(); + expect(guard.publishedFor('object', NAME, PKG)).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.publishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.publishPinned-36726.test.tsx new file mode 100644 index 00000000000..413a9c19c7f --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.publishPinned-36726.test.tsx @@ -0,0 +1,347 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36726 — a flow's Save, its switch and its creation publish over + * the published flow they were built on, never over one another writer + * published since. + * + * A Save is the flow's draft and then that one flow's publish + * (objectstack#36511), so it leaves no draft: two editors that opened the same + * published flow both pass the draft door, and before this card the later + * publish replaced the earlier one in silence. The flow's load now reads its + * layers at the address the publish writes BEFORE the draft, and pins the + * publish to the `overlayVersion` they serve; the later Save is refused + * `409 METADATA_CONFLICT` and the author is asked. A new flow's publish asserts + * no published flow of its name. + * + * The other writer is the double's own move of the live row; the refusal is + * parsed by the REAL `MetadataClient`. The REAL `AutomationsPillar`, with the + * REAL registered `FlowPreview` and `FlowInspector`. Also pinned: the reload + * residual of the card's scope addition. + */ + +import '@testing-library/jest-dom/vitest'; +// Paid at collection, not inside a clocked case (check:test-source-alias): +// the source under test loads `@objectstack/lint` lazily. +import '@objectstack/lint'; +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Module scope as well as in the `vi.mock` factory below: the cold transform is paid +// during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). +import '@object-ui/components'; +import { render, screen, fireEvent, cleanup, waitFor, within, act } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataClient, type MetadataError } from '@object-ui/data-objectstack'; + +const PKG = 'com.acme.app'; +const LIVE = 'hmac-sha256:live0'; +const PENDING = 'hmac-sha256:pending'; + +const FLOW = { + name: 'notify_owner', + label: 'Notify owner', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}; + +const server = vi.hoisted(() => ({ + active: new Map>(), + activeVersions: new Map(), + drafts: new Map; version: string }>(), + servesPublishedVersion: true, + saves: [] as Array<{ name: string; body: Record; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + publishes: [] as Array<{ name: string; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + seq: 0, +})); + +async function conflictRefusal(name: string, head: string | null): Promise { + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async () => + new Response( + JSON.stringify({ + error: `flow/${name} has been modified since you loaded it. The version token sent is not the current version (current is ${head}).`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }), + { status: 409, headers: { 'content-type': 'application/json' } }, + )) as unknown as typeof fetch, + }); + return client.publish('flow', name).then( + () => { + throw new Error('the stub door accepted the publish'); + }, + (e: unknown) => e as MetadataError, + ); +} + +const mockClient = vi.hoisted(() => { + const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + return { + list: vi.fn(async () => [...server.active.values()].map((row) => ({ name: row.name, label: row.label ?? row.name }))), + listResponse: vi.fn(async () => ({ items: [...server.active.values()].map((row) => ({ name: row.name })) })), + listDrafts: vi.fn(async () => [...server.drafts.keys()].map((name) => ({ type: 'flow', name }))), + listTypes: vi.fn(async () => ({ entries: [] })), + get: vi.fn(async () => null), + references: vi.fn(async () => []), + layered: vi.fn(async (_type: string, name: string) => { + const live = server.active.get(name) ?? null; + const draft = server.drafts.get(name)?.body ?? null; + const version = server.servesPublishedVersion ? { overlayVersion: live ? (server.activeVersions.get(name) ?? null) : null } : {}; + return { code: null, overlay: live && copy(live), overlayScope: live ? 'env' : null, effective: live && copy(live), draft: draft && copy(draft), ...version, editable: true, deletable: true, resettable: false, lock: 'none' }; + }), + // No draft is `null`, as the real client resolves the read's 404. + getDraft: vi.fn(async (type: string, name: string) => { + const row = server.drafts.get(name); + return row ? { type, name, item: copy(row.body), version: row.version } : null; + }), + save: vi.fn(async (_type: string, name: string, item: unknown, options?: { ifMatch?: string; ifNoneMatch?: string }) => { + const body = copy(item) as Record; + server.saves.push({ name, body, ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const head = server.drafts.get(name)?.version ?? null; + if (options?.ifMatch !== undefined && options.ifMatch !== head) throw await conflictRefusal(name, head); + if (options?.ifNoneMatch !== undefined && head !== null) throw await conflictRefusal(name, head); + server.seq += 1; + const version = `hmac-sha256:v${server.seq}`; + server.drafts.set(name, { body, version }); + return { success: true, version, state: 'draft' }; + }), + publish: vi.fn(async (_type: string, name: string, options?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + server.publishes.push({ name, ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const live = server.active.has(name) ? (server.activeVersions.get(name) ?? null) : null; + if (options?.ifMatch !== undefined && options.ifMatch !== live) throw await conflictRefusal(name, live); + if (options?.ifNoneMatch !== undefined && live !== null) throw await conflictRefusal(name, live); + const draft = server.drafts.get(name); + server.seq += 1; + const version = `hmac-sha256:live${server.seq}`; + if (draft) { + server.active.set(name, draft.body); + server.activeVersions.set(name, version); + } + server.drafts.delete(name); + return { success: true, version }; + }), + reset: vi.fn(async (_type: string, name: string, options?: { state?: string }) => { + if (options?.state === 'draft') server.drafts.delete(name); + return {}; + }), + }; +}); + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); + +import { AutomationsPillar } from './StudioDesignSurface'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; +import { registerMetadataPreview } from '../metadata-admin/preview-registry'; +import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; +import { FlowPreview } from '../metadata-admin/previews/FlowPreview'; +import { FlowInspector } from '../metadata-admin/inspectors/FlowInspector'; +import { t } from '../metadata-admin/i18n'; + +const dataSource = createEmptyDataSource(); +registerMetadataPreview('flow', FlowPreview); +registerMetadataInspector('flow', FlowInspector); + +const en = (key: string) => t(key, 'en'); +const WAIT = { timeout: 8000 }; +const fetchSpy = vi.fn(async (_input: RequestInfo | URL) => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })); + +beforeEach(() => { + server.active.clear(); + server.activeVersions.clear(); + server.drafts.clear(); + server.servesPublishedVersion = true; + server.saves.length = 0; + server.publishes.length = 0; + server.seq = 0; + for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); + window.confirm = vi.fn(() => true) as unknown as typeof window.confirm; + // The `/automation/_status` probe, the action catalog and the run history read go through the global `fetch`. + vi.stubGlobal('fetch', fetchSpy); + server.active.set(FLOW.name, JSON.parse(JSON.stringify(FLOW))); + server.activeVersions.set(FLOW.name, LIVE); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function mount(): void { + render( + + + + + , + ); +} + +async function openFlow(): Promise { + mount(); + await screen.findByTestId('auto-tab-canvas', undefined, WAIT); + await waitFor(() => expect(screen.getByText('Status:').nextElementSibling).toHaveTextContent(en('engine.studio.auto.enabled')), WAIT); +} + +async function editStartLabel(value: string): Promise { + fireEvent.click(document.querySelector('[data-node-id="start"] [role="button"]') as HTMLElement); + const box = await within(screen.getByTestId('auto-config-aside')).findByLabelText('Label', undefined, WAIT); + fireEvent.change(box, { target: { value } }); + fireEvent.blur(box); + await screen.findByTestId('studio-save', undefined, WAIT); +} + +async function save(): Promise { + const before = server.saves.length; + await pressStudioSave({ settle: false }); + await waitFor(() => expect(server.saves.length).toBe(before + 1), WAIT); +} + +async function saveAndLand(): Promise { + const before = server.publishes.length; + await save(); + await waitFor(() => expect(server.publishes.length).toBe(before + 1), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); +} + +const live = () => server.active.get(FLOW.name)!; +const liveNodeLabel = (id: string) => (live().nodes as Array<{ id: string; label?: string }>).find((n) => n.id === id)?.label; + +function anotherWriterPublishes(patch: Record): string { + server.seq += 1; + const version = `hmac-sha256:other${server.seq}`; + server.active.set(FLOW.name, { ...live(), ...patch }); + server.activeVersions.set(FLOW.name, version); + return version; +} + +async function racePublished(): Promise { + await openFlow(); + await editStartLabel('Kick-off'); + const theirs = anotherWriterPublishes({ description: 'Theirs' }); + await save(); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + return theirs; +} + +describe('Flows — two Saves over one published flow are not last-writer-wins (objectstack#36726)', () => { + it('the later Save is refused at its publish, worded as a live change; keep editing leaves the edit unsaved', async () => { + await racePublished(); + expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([[undefined, '*']]); + expect(server.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[LIVE, undefined]]); + expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('This changed since you opened it'); + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + expect((await screen.findAllByText(/Not saved:/, undefined, WAIT)).length).toBeGreaterThan(0); + expect(live().description).toBe('Theirs'); + expect(liveNodeLabel('start')).toBe('Start'); + expect(server.drafts.size).toBe(0); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }, 30_000); + + it('"reload" re-reads the other writer\'s flow, and the next Save is pinned to it', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); + await editStartLabel('Begin'); + await saveAndLand(); + expect(server.publishes[server.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + expect(live().description).toBe('Theirs'); + expect(liveNodeLabel('start')).toBe('Begin'); + }, 30_000); + + it('"overwrite" asks again, then re-publishes pinned to the refusal\'s currentVersion', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + await act(async () => { + fireEvent.click(await screen.findByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(liveNodeLabel('start')).toBe('Kick-off'), WAIT); + expect(server.publishes[server.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + }, 30_000); + + it('one editor: each Save\'s publish is pinned to the version the last one left', async () => { + await openFlow(); + await editStartLabel('Kick-off'); + await saveAndLand(); + const first = server.activeVersions.get(FLOW.name)!; + await editStartLabel('Begin'); + await saveAndLand(); + expect(server.publishes.map((p) => p.ifMatch)).toEqual([LIVE, first]); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }, 30_000); + + it('the switch\'s publish is pinned too: a flip over a flow another writer published is asked about', async () => { + await openFlow(); + anotherWriterPublishes({ description: 'Theirs' }); + fireEvent.click(screen.getByRole('switch')); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + expect(server.publishes.map((p) => p.ifMatch)).toEqual([LIVE]); + expect(live().status).toBe('active'); + }, 30_000); + + it('a new flow\'s publish asserts no published flow of its name', async () => { + mount(); + await screen.findByTestId(`auto-rail-row-${FLOW.name}`, undefined, WAIT); + fireEvent.click(screen.getByTitle(en('engine.studio.auto.newTitle'))); + const dialog = await screen.findByRole('dialog'); + fireEvent.click(within(dialog).getByTestId('create-flow-preset-manual')); + fireEvent.change(dialog.querySelectorAll('input')[0], { target: { value: 'Escalate' } }); + fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createLive') })); + await waitFor(() => expect(server.publishes).toHaveLength(1), WAIT); + expect(server.publishes[0]).toEqual({ name: 'escalate', ifMatch: undefined, ifNoneMatch: '*' }); + await waitFor(() => expect(server.active.has('escalate')).toBe(true), WAIT); + }, 40_000); + + it('control: a server that serves no `overlayVersion` gets an unpinned publish, as before', async () => { + server.servesPublishedVersion = false; + await openFlow(); + await editStartLabel('Kick-off'); + anotherWriterPublishes({ description: 'Theirs' }); + await saveAndLand(); + expect(server.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[undefined, undefined]]); + }, 30_000); +}); + +describe('Flows — a reload over a pending draft does not pin its publish to the fresh read (objectstack#36726)', () => { + it('a pending draft, a live change by another writer, a refused publish, Reload: the next Save is asked again', async () => { + server.drafts.set(FLOW.name, { body: JSON.parse(JSON.stringify(FLOW)), version: PENDING }); + await openFlow(); + await editStartLabel('Kick-off'); + anotherWriterPublishes({ description: 'Theirs' }); + await save(); + expect(server.saves[server.saves.length - 1]!.ifMatch).toBe(PENDING); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + // The draft pending before the Save is kept, carrying the page's edit, and re-read. + expect(JSON.stringify(server.drafts.get(FLOW.name)?.body.nodes)).toContain('Kick-off'); + await waitFor(() => expect(document.querySelector('[data-node-id="start"]')).toHaveTextContent('Kick-off'), WAIT); + + await editStartLabel('Begin'); + const publishesBefore = server.publishes.length; + await save(); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + expect(server.publishes.slice(publishesBefore).map((p) => p.ifMatch)).toEqual([LIVE]); + expect(live().description).toBe('Theirs'); + expect(liveNodeLabel('start')).toBe('Start'); + }, 30_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.extensionPublishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.extensionPublishPinned-36726.test.tsx new file mode 100644 index 00000000000..b1e7d6ce4cb --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.extensionPublishPinned-36726.test.tsx @@ -0,0 +1,356 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36726 — the extension a read-only base's pair holds of one of + * its objects (objectstack#28575) is published over the published extension + * row its buffer was loaded at, never over one another writer published since. + * + * The extension's Save writes its draft at the pair, then publishes that one + * extension there (objectstack#36511), so it leaves no draft: two editors that + * opened the same published extension both pass the draft door, and before + * this card the later publish replaced the earlier one in silence. The load + * now reads the extension's layers at the pair BEFORE its rows and pins the + * publish to their `overlayVersion` (`If-None-Match: *` where the pair holds + * no extension), so the later Save is refused `409 METADATA_CONFLICT` and the + * author is asked. + * + * The other writer is the double's own move of the live row; the refusal is + * parsed by the REAL `MetadataClient`. Also pinned: the reload residual of + * the card's scope addition. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// Module scope as well as in the `vi.mock` factory below: the cold transform is paid +// during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). +import '@object-ui/components'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataClient, type MetadataError } from '@object-ui/data-objectstack'; + +const BASE = 'com.example.hotcrm'; +const PAIR = 'com.example.hotcrm.custom'; +const OBJECT = 'crm_account'; +const EXT = 'object_extension'; +const LIVE = 'hmac-sha256:live0'; +const PENDING = 'hmac-sha256:pending'; + +type Row = Record; + +const srv = vi.hoisted(() => ({ + /** The pair's published extension row of the object, `null` when it has none. */ + publishedExt: null as Record | null, + publishedVersion: null as string | null, + /** The pair's pending extension draft. */ + draftExt: null as { body: Record; version: string } | null, + servesPublishedVersion: true, + saves: [] as Array<{ body: Record; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + publishes: [] as Array<{ ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + seq: 0, +})); + +async function conflictRefusal(head: string | null): Promise { + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async () => + new Response( + JSON.stringify({ + error: `object_extension/${OBJECT} has been modified since you loaded it. The version token sent is not the current version (current is ${head}).`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }), + { status: 409, headers: { 'content-type': 'application/json' } }, + )) as unknown as typeof fetch, + }); + return client.publish(EXT, OBJECT).then( + () => { + throw new Error('the stub door accepted the publish'); + }, + (e: unknown) => e as MetadataError, + ); +} + +const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const baseFields = () => ({ + name: { type: 'text', label: 'Account Name', required: true }, + industry: { type: 'text', label: 'Industry' }, +}); +/** The base as served, the pair's published extension merged in. */ +const served = (): Row => ({ + name: OBJECT, + label: 'Account', + fields: { ...baseFields(), ...((srv.publishedExt?.fields ?? {}) as Row) }, +}); + +const extFields = (row: Row | null | undefined) => Object.keys((row?.fields ?? {}) as Row); + +const mockClient = { + list: vi.fn(async (_type: string, opts?: { packageId?: string }) => + opts?.packageId === PAIR ? [] : [{ name: OBJECT, label: 'Account' }], + ), + listDrafts: vi.fn(async (opts?: { packageId?: string; type?: string }) => + srv.draftExt && opts?.packageId === PAIR && (!opts.type || opts.type === EXT) ? [{ type: EXT, name: OBJECT }] : [], + ), + layered: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => { + if (type === EXT && name === OBJECT && opts?.packageId === PAIR) { + const live = srv.publishedExt; + const draft = srv.draftExt?.body ?? null; + // The door's 404, answered by the client as the empty view. + if (!live && !draft) return { code: null, overlay: null, overlayScope: null, effective: null }; + const version = srv.servesPublishedVersion ? { overlayVersion: live ? srv.publishedVersion : null } : {}; + return { code: null, overlay: live && copy(live), effective: live && copy(live), draft: draft && copy(draft), ...version }; + } + return { effective: served(), code: served() }; + }), + getDraft: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => + type === EXT && name === OBJECT && opts?.packageId === PAIR && srv.draftExt + ? { type, name, item: copy(srv.draftExt.body), version: srv.draftExt.version } + : null, + ), + get: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => + type === EXT && name === OBJECT && opts?.packageId === PAIR && srv.publishedExt ? { ...copy(srv.publishedExt), _packageId: PAIR } : null, + ), + publish: vi.fn(async (type: string, _name: string, options?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + if (type !== EXT) return {}; + srv.publishes.push({ ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const live = srv.publishedExt ? srv.publishedVersion : null; + if (options?.ifMatch !== undefined && options.ifMatch !== live) throw await conflictRefusal(live); + if (options?.ifNoneMatch !== undefined && live !== null) throw await conflictRefusal(live); + srv.seq += 1; + if (srv.draftExt) { + srv.publishedExt = srv.draftExt.body; + srv.publishedVersion = `hmac-sha256:live${srv.seq}`; + } + srv.draftExt = null; + return { success: true, version: srv.publishedVersion }; + }), + reset: vi.fn(async (type: string, _name: string, opts?: { state?: string }) => { + if (type === EXT && opts?.state === 'draft') srv.draftExt = null; + return {}; + }), + save: vi.fn(async (type: string, _name: string, item: unknown, opts?: { ifMatch?: string; ifNoneMatch?: string }) => { + if (type !== EXT) return { ok: true, version: 'v-other', state: 'draft' }; + const body = copy(item) as Row; + srv.saves.push({ body, ifMatch: opts?.ifMatch, ifNoneMatch: opts?.ifNoneMatch }); + const head = srv.draftExt?.version ?? null; + if (opts?.ifMatch !== undefined && opts.ifMatch !== head) throw await conflictRefusal(head); + if (opts?.ifNoneMatch !== undefined && head !== null) throw await conflictRefusal(head); + srv.seq += 1; + srv.draftExt = { body, version: `hmac-sha256:v${srv.seq}` }; + return { success: true, version: srv.draftExt.version, state: 'draft' }; + }), +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); + +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); + +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => ({}) }; +}); + +vi.mock('@object-ui/plugin-view', async (importOriginal) => { + const mod = await importOriginal>(); + return { ...mod, ObjectView: () =>
}; +}); + +// The console's preview and authoring code loads `@objectstack/lint` lazily; +// warmed here so its first load is paid at import, not inside a test's clock. +import '@objectstack/lint'; +import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; +import { t } from '../metadata-admin/i18n'; +import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; +import { ObjectFieldInspector } from '../metadata-admin/inspectors/ObjectFieldInspector'; + +registerMetadataInspector('object', ObjectFieldInspector); + +const FORM = t('engine.studio.data.tab.form', 'en'); +const WAIT = { timeout: 8000 }; +const ensure = vi.fn(async (): Promise => PAIR); + +function customization(): StudioBaseCustomization { + return { + base: BASE, + baseLabel: 'HotCRM', + basedOn: '4.0.0', + walled: false, + pairId: PAIR, + ensure, + ensurePackage: vi.fn() as unknown as StudioBaseCustomization['ensurePackage'], + marks: { status: 'off' }, + }; +} + +beforeEach(() => { + for (const m of ['hasPointerCapture', 'setPointerCapture', 'releasePointerCapture'] as const) { + if (!(m in Element.prototype)) { + (Element.prototype as unknown as Record)[m] = m === 'hasPointerCapture' ? () => false : () => {}; + } + } + if (!('scrollIntoView' in Element.prototype)) { + (Element.prototype as unknown as Record).scrollIntoView = () => {}; + } + srv.publishedExt = { extend: OBJECT, fields: { region__c: { type: 'text', label: 'Region' } } }; + srv.publishedVersion = LIVE; + srv.draftExt = null; + srv.servesPublishedVersion = true; + srv.saves.length = 0; + srv.publishes.length = 0; + srv.seq = 0; + ensure.mockImplementation(async () => PAIR); +}); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +async function openOnForm(): Promise { + render( + + + + + , + ); + await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), WAIT); + await userEvent.click(screen.getAllByRole('button', { name: FORM })[0]); + await screen.findByRole('button', { name: 'Layout', pressed: true }); +} + +/** Add an extension field from the Form toolbar: nothing is sent. */ +async function addField(label: string): Promise { + await userEvent.click(await screen.findByTestId('data-form-add-extension-field')); + const popover = await screen.findByTestId('add-field-popover'); + await userEvent.type(within(popover).getByTestId('add-field-label-input'), label); + await userEvent.click(within(popover).getByTestId('add-field-create')); +} + +async function save(): Promise { + const before = srv.saves.length; + await pressStudioSave({ settle: false }); + await waitFor(() => expect(srv.saves.length).toBe(before + 1), WAIT); +} + +async function saveAndLand(): Promise { + const before = srv.publishes.length; + await save(); + await waitFor(() => expect(srv.publishes.length).toBe(before + 1), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); +} + +/** Another writer publishes the pair's extension: its row and its version move. */ +function anotherWriterPublishes(field: string): string { + srv.seq += 1; + srv.publishedExt = { ...srv.publishedExt!, fields: { ...(srv.publishedExt!.fields as Row), [field]: { type: 'text', label: field } } }; + srv.publishedVersion = `hmac-sha256:other${srv.seq}`; + return srv.publishedVersion; +} + +async function racePublished(): Promise { + await openOnForm(); + await addField('Tier'); + const theirs = anotherWriterPublishes('score__c'); + await save(); + expect(srv.saves[srv.saves.length - 1]).toMatchObject({ ifMatch: undefined, ifNoneMatch: '*' }); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + return theirs; +} + +describe('Extension — two Saves over one published extension are not last-writer-wins (objectstack#36726)', () => { + it('the later Save is refused at its publish, worded as a live change; keep editing leaves the edit unsaved', async () => { + await racePublished(); + expect(srv.publishes).toEqual([{ ifMatch: LIVE, ifNoneMatch: undefined }]); + expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('This changed since you opened it'); + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + expect((await screen.findAllByText(/Not saved:/, undefined, WAIT)).length).toBeGreaterThan(0); + expect(extFields(srv.publishedExt)).toEqual(['region__c', 'score__c']); + expect(srv.draftExt).toBeNull(); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }, 30_000); + + it('"reload" re-reads the other writer\'s extension, and the next Save is pinned to it', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); + await addField('Tier'); + await saveAndLand(); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + // Built on the other writer's extension: its field is kept. + expect(extFields(srv.publishedExt)).toEqual(['region__c', 'score__c', 'tier__c']); + }, 30_000); + + it('"overwrite" asks again, then re-publishes pinned to the refusal\'s currentVersion', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + await act(async () => { + fireEvent.click(await screen.findByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(extFields(srv.publishedExt)).toEqual(['region__c', 'tier__c']), WAIT); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + }, 30_000); + + it('one editor: each Save\'s publish is pinned to the version the last one left', async () => { + await openOnForm(); + await addField('Tier'); + await saveAndLand(); + const first = srv.publishedVersion; + await addField('Score'); + await saveAndLand(); + expect(srv.publishes.map((p) => p.ifMatch)).toEqual([LIVE, first]); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }, 30_000); + + it('a pair that holds no extension of the object: the first publish asserts none', async () => { + srv.publishedExt = null; + srv.publishedVersion = null; + await openOnForm(); + await addField('Tier'); + await saveAndLand(); + expect(srv.publishes).toEqual([{ ifMatch: undefined, ifNoneMatch: '*' }]); + }, 30_000); + + it('control: a server that serves no `overlayVersion` gets an unpinned publish, as before', async () => { + srv.servesPublishedVersion = false; + await openOnForm(); + await addField('Tier'); + anotherWriterPublishes('score__c'); + await saveAndLand(); + expect(srv.publishes).toEqual([{ ifMatch: undefined, ifNoneMatch: undefined }]); + }, 30_000); +}); + +describe('Extension — a reload over a pending draft does not pin its publish to the fresh read (objectstack#36726)', () => { + it('a pending draft, a live change by another writer, a refused publish, Reload: the next Save is asked again', async () => { + srv.draftExt = { body: copy(srv.publishedExt!), version: PENDING }; + await openOnForm(); + await addField('Tier'); + anotherWriterPublishes('score__c'); + await save(); + expect(srv.saves[srv.saves.length - 1]!.ifMatch).toBe(PENDING); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + // The draft pending before the Save is kept, carrying the page's edit, and re-read. + expect(extFields(srv.draftExt?.body)).toEqual(['region__c', 'tier__c']); + + await addField('Rank'); + const publishesBefore = srv.publishes.length; + await save(); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + expect(srv.publishes.slice(publishesBefore).map((p) => p.ifMatch)).toEqual([LIVE]); + expect(extFields(srv.publishedExt)).toEqual(['region__c', 'score__c']); + }, 30_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx new file mode 100644 index 00000000000..aada32703be --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx @@ -0,0 +1,379 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36726 — an action a read-only base's pair adds to one of its + * objects (objectstack#30088) is published over the published action its row + * was loaded at, never over one another writer published since. + * + * A Save writes the row's draft at the pair, then publishes that one action + * there (objectstack#36511), so it leaves no draft: two editors that opened + * the same published action both pass the draft door, and before this card + * the later publish replaced the earlier one in silence. The pair's layered + * read, which the row's buffer already comes from (objectstack#35054), serves + * `overlayVersion`; the row's publish is pinned to it, so the later Save is + * refused `409 METADATA_CONFLICT` and the author is asked. + * + * The other writer is the double's own move of the live row; the door's + * refusal is parsed by the REAL `MetadataClient`. Also pinned: a new row's + * publish asserts no published action of its name, and the reload residual + * of the card's scope addition (a draft pending before the Save is kept, and + * the reload that re-reads it does not pin its publish to the fresh read). + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// Module scope as well as in the `vi.mock` factory below: the cold transform is paid +// during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). +import '@object-ui/components'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataClient, type MetadataError } from '@object-ui/data-objectstack'; + +const BASE = 'com.example.crm'; +const PAIR = 'com.example.crm.custom'; +const OBJECT = 'crm_lead'; + +/** The vendor's action, served on the object. */ +const VENDOR = { + name: 'crm_lead_convert', + label: 'Convert', + objectName: OBJECT, + locations: ['record_header'], + type: 'script', + body: { language: 'expression', source: 'true' }, +}; + +/** The action the pair holds on the object, published. */ +const KEPT = { + name: 'crm_lead_action_7', + label: 'Qualify', + objectName: OBJECT, + locations: ['record_more'], + operation: 'update', + patch: { status: 'qualified' }, +}; + +const LIVE = 'hmac-sha256:live0'; +const PENDING = 'hmac-sha256:pending'; + +const srv = vi.hoisted(() => ({ + active: new Map>(), + activeVersions: new Map(), + drafts: new Map; version: string }>(), + servesPublishedVersion: true, + saves: [] as Array<{ name: string; body: Record; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + publishes: [] as Array<{ name: string; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + seq: 0, +})); + +async function conflictRefusal(name: string, head: string | null): Promise { + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async () => + new Response( + JSON.stringify({ + error: `action/${name} has been modified since you loaded it. The version token sent is not the current version (current is ${head}).`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }), + { status: 409, headers: { 'content-type': 'application/json' } }, + )) as unknown as typeof fetch, + }); + return client.publish('action', name).then( + () => { + throw new Error('the stub door accepted the publish'); + }, + (e: unknown) => e as MetadataError, + ); +} + +const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const servedObject = () => ({ + name: OBJECT, + label: 'Lead', + fields: { name: { type: 'text', label: 'Name' } }, + actions: [VENDOR, ...[...srv.active.values()].map((a) => ({ ...a, _packageId: PAIR }))], +}); + +const mockClient = { + list: vi.fn(async (type: string, opts?: { packageId?: string }) => { + if (type === 'action') return opts?.packageId === PAIR ? [...srv.active.values()].map((a) => ({ ...copy(a), _packageId: PAIR })) : []; + if (type === 'object') return opts?.packageId === PAIR ? [] : [{ name: OBJECT, label: 'Lead' }]; + return []; + }), + listDrafts: vi.fn(async (opts?: { packageId?: string; type?: string }) => + opts?.type === 'action' && opts.packageId === PAIR ? [...srv.drafts.keys()].map((name) => ({ type: 'action', name })) : [], + ), + layered: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => { + if (type === 'action' && opts?.packageId === PAIR) { + const live = srv.active.get(name) ?? null; + const draft = srv.drafts.get(name)?.body ?? null; + const version = srv.servesPublishedVersion ? { overlayVersion: live ? (srv.activeVersions.get(name) ?? null) : null } : {}; + return { code: null, overlay: live && copy(live), effective: live && copy(live), draft: draft && copy(draft), ...version }; + } + return { effective: servedObject(), code: servedObject() }; + }), + getDraft: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => { + const row = type === 'action' && opts?.packageId === PAIR ? srv.drafts.get(name) : undefined; + return row ? { type, name, item: { ...copy(row.body), _packageId: PAIR }, version: row.version } : null; + }), + get: vi.fn(async () => null), + save: vi.fn(async (type: string, name: string, item: unknown, opts?: { packageId?: string; ifMatch?: string; ifNoneMatch?: string }) => { + if (type !== 'action' || opts?.packageId !== PAIR) return { ok: true, version: 'v-other', state: 'draft' }; + const body = copy(item) as Record; + srv.saves.push({ name, body, ifMatch: opts.ifMatch, ifNoneMatch: opts.ifNoneMatch }); + const head = srv.drafts.get(name)?.version ?? null; + if (opts.ifMatch !== undefined && opts.ifMatch !== head) throw await conflictRefusal(name, head); + if (opts.ifNoneMatch !== undefined && head !== null) throw await conflictRefusal(name, head); + srv.seq += 1; + const version = `hmac-sha256:v${srv.seq}`; + srv.drafts.set(name, { body, version }); + return { success: true, version, state: 'draft' }; + }), + publish: vi.fn(async (_type: string, name: string, options?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + srv.publishes.push({ name, ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const live = srv.active.has(name) ? (srv.activeVersions.get(name) ?? null) : null; + if (options?.ifMatch !== undefined && options.ifMatch !== live) throw await conflictRefusal(name, live); + if (options?.ifNoneMatch !== undefined && live !== null) throw await conflictRefusal(name, live); + const draft = srv.drafts.get(name); + srv.seq += 1; + const version = `hmac-sha256:live${srv.seq}`; + if (draft) { + srv.active.set(name, draft.body); + srv.activeVersions.set(name, version); + } + srv.drafts.delete(name); + return { success: true, version }; + }), + reset: vi.fn(async (type: string, name: string, opts?: { packageId?: string; state?: string }) => { + if (type === 'action' && opts?.packageId === PAIR && opts.state === 'draft') srv.drafts.delete(name); + return { ok: true }; + }), + withPreviewDrafts() { + return this; + }, +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); + +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); + +// The Advanced views live in a Radix DropdownMenu; rendered as passthroughs, +// as in DataPillar.pairActions-30088.test.tsx. +type PassthroughProps = { children?: React.ReactNode; onSelect?: () => void }; +vi.mock('@object-ui/components', async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + DropdownMenu: (p: PassthroughProps) =>
{p.children}
, + DropdownMenuTrigger: (p: PassthroughProps) =>
{p.children}
, + DropdownMenuContent: (p: PassthroughProps) =>
{p.children}
, + DropdownMenuItem: (p: PassthroughProps) => ( + + ), + DropdownMenuRadioGroup: (p: PassthroughProps) =>
{p.children}
, + DropdownMenuRadioItem: (p: PassthroughProps) => ( + + ), + }; +}); + +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +// The pillar reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; +import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +import { t } from '../metadata-admin/i18n'; + +const dataSource = createEmptyDataSource(); +registerBuiltinInspectors(); + +const L = (key: string) => t(key, 'en'); +const ensure = vi.fn(async (): Promise => PAIR); +const WAIT = { timeout: 8000 }; + +function customization(): StudioBaseCustomization { + return { + base: BASE, + baseLabel: 'CRM', + basedOn: '4.0.0', + walled: false, + pairId: PAIR, + ensure, + ensurePackage: vi.fn() as unknown as StudioBaseCustomization['ensurePackage'], + marks: { status: 'off' }, + }; +} + +beforeEach(() => { + srv.active.clear(); + srv.activeVersions.clear(); + srv.drafts.clear(); + srv.servesPublishedVersion = true; + srv.saves.length = 0; + srv.publishes.length = 0; + srv.seq = 0; + srv.active.set(KEPT.name, copy(KEPT)); + srv.activeVersions.set(KEPT.name, LIVE); + ensure.mockImplementation(async () => PAIR); +}); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +const list = () => screen.getByTestId('actions-list'); +const live = () => srv.active.get(KEPT.name)!; + +async function mountOnActions(): Promise { + render( + + + + + , + ); + fireEvent.click((await screen.findAllByRole('button', { name: L('engine.studio.data.tab.actions') }, WAIT))[0]); + await within(await screen.findByTestId('actions-list', undefined, WAIT)).findByText('Convert', undefined, WAIT); +} + +/** Open the row by its label and rename it: nothing is sent. */ +async function relabel(from: string, to: string): Promise { + fireEvent.click(await within(list()).findByText(from, undefined, WAIT)); + fireEvent.change(screen.getByRole('textbox', { name: L('engine.inspector.action.label') }), { target: { value: to } }); +} + +async function save(): Promise { + const before = srv.saves.length; + await pressStudioSave({ settle: false }); + await waitFor(() => expect(srv.saves.length).toBe(before + 1), WAIT); +} + +async function saveAndLand(): Promise { + const before = srv.publishes.length; + await save(); + await waitFor(() => expect(srv.publishes.length).toBe(before + 1), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); +} + +function anotherWriterPublishes(patch: Record): string { + srv.seq += 1; + const version = `hmac-sha256:other${srv.seq}`; + srv.active.set(KEPT.name, { ...live(), ...patch }); + srv.activeVersions.set(KEPT.name, version); + return version; +} + +async function racePublished(): Promise { + await mountOnActions(); + await relabel('Qualify', 'Mark qualified'); + const theirs = anotherWriterPublishes({ patch: { status: 'hot' } }); + await save(); + expect(srv.saves[srv.saves.length - 1]).toMatchObject({ ifMatch: undefined, ifNoneMatch: '*' }); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + return theirs; +} + +describe('Pair actions — two Saves over one published action are not last-writer-wins (objectstack#36726)', () => { + it('the later Save is refused at its publish, worded as a live change; keep editing leaves the edit unsaved', async () => { + await racePublished(); + expect(srv.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[LIVE, undefined]]); + expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('This changed since you opened it'); + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + expect((await screen.findAllByText(/Not saved:/, undefined, WAIT)).length).toBeGreaterThan(0); + expect(live()).toMatchObject({ label: 'Qualify', patch: { status: 'hot' } }); + expect(srv.drafts.size).toBe(0); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }, 30_000); + + it('"reload" re-reads the other writer\'s action, and the next Save is pinned to it', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); + await relabel('Qualify', 'Qualify lead'); + await saveAndLand(); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + // Built on the other writer's action. + expect(live()).toMatchObject({ label: 'Qualify lead', patch: { status: 'hot' } }); + }, 30_000); + + it('"overwrite" asks again, then re-publishes pinned to the refusal\'s currentVersion', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + await act(async () => { + fireEvent.click(await screen.findByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(live().label).toBe('Mark qualified'), WAIT); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + }, 30_000); + + it('one editor: each Save\'s publish is pinned to the version the last one left', async () => { + await mountOnActions(); + await relabel('Qualify', 'Mark qualified'); + await saveAndLand(); + const first = srv.activeVersions.get(KEPT.name)!; + await relabel('Mark qualified', 'Qualify lead'); + await saveAndLand(); + expect(srv.publishes.map((p) => p.ifMatch)).toEqual([LIVE, first]); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }, 30_000); + + it('a new row\'s publish asserts no published action of its name', async () => { + await mountOnActions(); + fireEvent.click(screen.getByRole('button', { name: L('engine.studio.new') })); + fireEvent.click(await screen.findByTestId('action-preset-change_choice')); + await save(); + await waitFor(() => expect(srv.publishes).toHaveLength(1), WAIT); + expect(srv.publishes[0]).toMatchObject({ ifMatch: undefined, ifNoneMatch: '*' }); + }, 30_000); + + it('control: a server that serves no `overlayVersion` gets an unpinned publish, as before', async () => { + srv.servesPublishedVersion = false; + await mountOnActions(); + await relabel('Qualify', 'Mark qualified'); + anotherWriterPublishes({ patch: { status: 'hot' } }); + await saveAndLand(); + expect(srv.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[undefined, undefined]]); + }, 30_000); +}); + +describe('Pair actions — a reload over a pending draft does not pin its publish to the fresh read (objectstack#36726)', () => { + it('a pending draft, a live change by another writer, a refused publish, Reload: the next Save is asked again', async () => { + srv.drafts.set(KEPT.name, { body: copy(KEPT), version: PENDING }); + await mountOnActions(); + await relabel('Qualify', 'Mark qualified'); + anotherWriterPublishes({ patch: { status: 'hot' } }); + await save(); + expect(srv.saves[srv.saves.length - 1]!.ifMatch).toBe(PENDING); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + // The draft pending before the Save is kept, carrying the page's edit, and re-read. + expect(srv.drafts.get(KEPT.name)?.body.label).toBe('Mark qualified'); + + await relabel('Mark qualified', 'Qualify lead'); + const publishesBefore = srv.publishes.length; + await save(); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + expect(srv.publishes.slice(publishesBefore).map((p) => p.ifMatch)).toEqual([LIVE]); + expect(live()).toMatchObject({ label: 'Qualify', patch: { status: 'hot' } }); + }, 30_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx new file mode 100644 index 00000000000..c0924d4215d --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx @@ -0,0 +1,324 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36726 — a hook's Save publishes over the published hook it was + * loaded at, never over one another writer published since. + * + * A Studio Save is the hook's draft and then that one hook's publish + * (objectstack#36511), so it leaves no draft behind: two editors that opened + * the same published hook each assert "no draft" and both pass the draft door. + * Before this card the hook's publish was unpinned, and the later Save + * replaced the earlier one's live hook without a word. Now the list load + * reads each listed hook's layers at the package the publish writes and pins + * the publish to its `overlayVersion` (`If-Match`), so the later Save is + * refused `409 METADATA_CONFLICT` and the author is asked: reload, overwrite, + * or keep editing. + * + * The other writer is the server double's own move of the live row (a Save + * from another tab, a rollback): the panel cannot tell them apart, and one + * panel keeps the queries unambiguous. The door's refusal is parsed by the + * REAL `MetadataClient`, so the error the buffer catches is production's. + * + * And the reload residual (the scope addition on the card): a hook with a + * draft pending before the Save (a copilot's) keeps that draft through a + * refused publish and a reload, so the reload re-reads it carrying the + * page's edit. Its next Save is asked again, never published over the row + * that moved. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react'; +import { MetadataClient, type MetadataError } from '@object-ui/data-objectstack'; + +const PKG = 'com.example.showcase'; +const GUARD = { name: 'guard_hook', label: 'Guard', object: 'invoice', events: ['beforeInsert'], handler: 'guard_fn' }; +/** The live row's version the panel opens at. */ +const LIVE = 'hmac-sha256:live0'; +/** A draft pending before the Save (a copilot's). */ +const PENDING = 'hmac-sha256:pending'; + +interface Sent { + name: string; + body: Record; + ifMatch: string | undefined; + ifNoneMatch: string | undefined; +} + +const srv = vi.hoisted(() => ({ + active: new Map>(), + activeVersions: new Map(), + drafts: new Map; version: string }>(), + // A server from before `overlayVersion` was served serves none (the control). + servesPublishedVersion: true, + saves: [] as Array<{ name: string; body: Record; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + publishes: [] as Array<{ name: string; ifMatch: string | undefined; ifNoneMatch: string | undefined }>, + seq: 0, +})); + +/** The 409 the door answers, run through the real client's error parser. */ +async function conflictRefusal(name: string, head: string | null): Promise { + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async () => + new Response( + JSON.stringify({ + error: `hook/${name} has been modified since you loaded it. The version token sent is not the current version (current is ${head}).`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }), + { status: 409, headers: { 'content-type': 'application/json' } }, + )) as unknown as typeof fetch, + }); + return client.publish('hook', name).then( + () => { + throw new Error('the stub door accepted the publish'); + }, + (e: unknown) => e as MetadataError, + ); +} + +const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const mockClient = { + list: vi.fn(async () => [...srv.active.values()].map(copy)), + listDrafts: vi.fn(async () => [...srv.drafts.keys()].map((name) => ({ type: 'hook', name }))), + getDraft: vi.fn(async (_type: string, name: string) => { + const row = srv.drafts.get(name); + return row ? { type: 'hook', name, item: copy(row.body), version: row.version } : null; + }), + get: vi.fn(async () => null), + layered: vi.fn(async (_type: string, name: string) => { + const live = srv.active.get(name) ?? null; + const draft = srv.drafts.get(name)?.body ?? null; + const version = srv.servesPublishedVersion ? { overlayVersion: live ? (srv.activeVersions.get(name) ?? null) : null } : {}; + return { code: null, overlay: live && copy(live), effective: live && copy(live), draft: draft && copy(draft), ...version }; + }), + withPreviewDrafts() { + return this; + }, + save: vi.fn( + async (_type: string, name: string, item: Record, options?: { ifMatch?: string; ifNoneMatch?: string }) => { + const body = copy(item); + srv.saves.push({ name, body, ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const head = srv.drafts.get(name)?.version ?? null; + if (options?.ifMatch !== undefined && options.ifMatch !== head) throw await conflictRefusal(name, head); + if (options?.ifNoneMatch !== undefined && head !== null) throw await conflictRefusal(name, head); + srv.seq += 1; + const version = `hmac-sha256:v${srv.seq}`; + srv.drafts.set(name, { body, version }); + return { success: true, version, seq: srv.seq, state: 'draft' }; + }, + ), + // The Save's own publish, pinned on the live row: the draft goes live and none is left. + publish: vi.fn(async (_type: string, name: string, options?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + srv.publishes.push({ name, ifMatch: options?.ifMatch, ifNoneMatch: options?.ifNoneMatch }); + const live = srv.active.has(name) ? (srv.activeVersions.get(name) ?? null) : null; + if (options?.ifMatch !== undefined && options.ifMatch !== live) throw await conflictRefusal(name, live); + if (options?.ifNoneMatch !== undefined && live !== null) throw await conflictRefusal(name, live); + const draft = srv.drafts.get(name); + srv.seq += 1; + const version = `hmac-sha256:live${srv.seq}`; + if (draft) { + srv.active.set(name, draft.body); + srv.activeVersions.set(name, version); + } + srv.drafts.delete(name); + return { success: true, version }; + }), + // The draft discard a refused Save sends (`?state=draft`). + reset: vi.fn(async (_type: string, name: string, options?: { state?: string }) => { + if (options?.state === 'draft') srv.drafts.delete(name); + return { success: true }; + }), +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient }; +}); + +import { HooksPanelHost } from './__tests__/hooksPanelHost'; +import { pressStudioSave } from './__tests__/studioSaveHarness'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +// The source reaches a dynamic `import('@objectstack/lint')`: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; + +registerBuiltinInspectors(); + +beforeEach(() => { + srv.active.clear(); + srv.activeVersions.clear(); + srv.drafts.clear(); + srv.servesPublishedVersion = true; + srv.saves.length = 0; + srv.publishes.length = 0; + srv.seq = 0; + for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear?: () => void }).mockClear?.(); + srv.active.set(GUARD.name, copy(GUARD)); + srv.activeVersions.set(GUARD.name, LIVE); + __setCelFormulaLoader(() => + Promise.resolve({ + validateExpression: () => ({ ok: true, errors: [], warnings: [] }), + introspectScope: () => ({ fields: ['status'], roots: ['record'], functions: ['has'] }), + inferExpressionType: () => 'boolean' as const, + }), + ); +}); +afterEach(() => { + cleanup(); + __setCelFormulaLoader(undefined); +}); + +const WAIT = { timeout: 4000 }; + +function openPanel() { + render(); +} + +/** Open the hook by its label and type a condition into its Expression tab: nothing is sent. */ +async function edit(label: string, condition: string): Promise { + fireEvent.click(await screen.findByText(label, undefined, WAIT)); + fireEvent.click(await screen.findByText('Expression')); + const box = screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; + fireEvent.change(box, { target: { value: condition } }); +} + +/** Press Save and wait for its draft write; a Save refused at its publish stops on the dialog. */ +async function save(): Promise { + const before = srv.saves.length; + await pressStudioSave({ settle: false }); + await waitFor(() => expect(srv.saves.length).toBe(before + 1), WAIT); + return srv.saves[srv.saves.length - 1]!; +} + +async function saveAndLand(): Promise { + await save(); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull(), WAIT); +} + +/** Another writer publishes the hook (another tab's Save, a rollback): the live row and its version move. */ +function anotherWriterPublishes(patch: Record): string { + srv.seq += 1; + const version = `hmac-sha256:other${srv.seq}`; + srv.active.set(GUARD.name, { ...srv.active.get(GUARD.name)!, ...patch }); + srv.activeVersions.set(GUARD.name, version); + return version; +} + +const live = () => srv.active.get(GUARD.name)!; + +/** The race: the panel opened at LIVE, another writer published, then this panel's Save. */ +async function racePublished(): Promise { + openPanel(); + await edit('Guard', "record.status == 'open'"); + const theirs = anotherWriterPublishes({ label: 'Guard (B)' }); + const sent = await save(); + // Its draft passes: no draft was pending, and none is. + expect([sent.ifMatch, sent.ifNoneMatch]).toEqual([undefined, '*']); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + return theirs; +} + +describe('Hooks — two Saves over one published hook are not last-writer-wins (objectstack#36726)', () => { + it('the later Save is refused at its publish, worded as a live change; keep editing leaves the edit unsaved', async () => { + await racePublished(); + expect(srv.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[LIVE, undefined]]); + expect(live().label).toBe('Guard (B)'); + expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('This changed since you opened it'); + expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('guard_hook'); + + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + // Nothing went live, the draft the Save wrote is taken back, and the edit stays, unsaved. + expect(await screen.findByText(/^Not saved:/, undefined, WAIT)).toBeInTheDocument(); + expect(live().label).toBe('Guard (B)'); + expect(live().condition).toBeUndefined(); + expect(srv.drafts.size).toBe(0); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }); + + it('"reload" re-reads the other writer\'s hook, and the next Save is pinned to it', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + expect(srv.drafts.size).toBe(0); + + await edit('Guard (B)', "record.status == 'void'"); + await saveAndLand(); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs, ifNoneMatch: undefined }); + // Built on the other writer's hook: its label is kept. + expect(live()).toMatchObject({ label: 'Guard (B)', condition: "record.status == 'void'" }); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }); + + it('"overwrite" asks again, then re-publishes pinned to the refusal\'s currentVersion', async () => { + const theirs = await racePublished(); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + const before = srv.publishes.length; + expect(await screen.findByTestId('draft-conflict-overwrite-confirm')).toBeInTheDocument(); + expect(srv.publishes.length).toBe(before); + await act(async () => { + fireEvent.click(screen.getByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(live().condition).toBe("record.status == 'open'"), WAIT); + expect(srv.publishes[srv.publishes.length - 1]).toMatchObject({ ifMatch: theirs }); + }); + + it('one editor: each Save\'s publish is pinned to the version the last one left, so it never conflicts with itself', async () => { + openPanel(); + await edit('Guard', "record.status == 'open'"); + await saveAndLand(); + const first = srv.activeVersions.get(GUARD.name)!; + await edit('Guard', "record.status == 'void'"); + await saveAndLand(); + expect(srv.publishes.map((p) => p.ifMatch)).toEqual([LIVE, first]); + expect(live().condition).toBe("record.status == 'void'"); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }); + + it('a new hook\'s publish asserts no published row of its name', async () => { + openPanel(); + await screen.findByText('Guard', undefined, WAIT); + fireEvent.click(screen.getByRole('button', { name: /New/ })); + await save(); + await waitFor(() => expect(srv.publishes).toHaveLength(1), WAIT); + expect(srv.publishes[0]).toMatchObject({ ifMatch: undefined, ifNoneMatch: '*' }); + }); + + it('control: a server that serves no `overlayVersion` gets an unpinned publish, as before', async () => { + srv.servesPublishedVersion = false; + openPanel(); + await edit('Guard', "record.status == 'open'"); + anotherWriterPublishes({ label: 'Guard (B)' }); + await saveAndLand(); + expect(srv.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[undefined, undefined]]); + }); +}); + +describe('Hooks — a reload over a pending draft does not pin its publish to the fresh read (objectstack#36726)', () => { + it('a pending draft, a live change by another writer, a refused publish, Reload: the next Save is asked again', async () => { + srv.drafts.set(GUARD.name, { body: copy(GUARD), version: PENDING }); + openPanel(); + await edit('Guard', "record.status == 'open'"); + // Another writer moves the live row without touching the pending draft. + anotherWriterPublishes({ label: 'Guard (B)' }); + const sent = await save(); + expect(sent.ifMatch).toBe(PENDING); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); + // The draft pending before the Save is kept (it carries the page's edit), and re-read. + expect(srv.drafts.get(GUARD.name)?.body.condition).toBe("record.status == 'open'"); + + await edit('Guard', "record.status == 'void'"); + const publishesBefore = srv.publishes.length; + await save(); + await screen.findByTestId('draft-conflict-dialog', undefined, WAIT); + // Pinned to the version the conflict was raised on, never the fresh read's: asked again. + expect(srv.publishes.slice(publishesBefore).map((p) => p.ifMatch)).toEqual([LIVE]); + expect(live()).toMatchObject({ label: 'Guard (B)' }); + expect(live().condition).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx index 15a3eb33500..7823ed2d82c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx @@ -544,3 +544,58 @@ describe('Data pillar — two Saves over one published object are not last-write expect(server.publishes.map((p) => [p.ifMatch, p.ifNoneMatch])).toEqual([[undefined, undefined]]); }); }); + +describe('Data pillar — a reload over a pending draft does not pin its publish to the fresh read (objectstack#36726)', () => { + const LIVE = 'hmac-sha256:live0'; + const MOVED = 'hmac-sha256:moved'; + + /** + * The residual the draft pin cannot stop: a draft is pending before the + * Save (a copilot's), and another writer moves the live row without + * touching it (a direct active save, a rollback). The Save writes into the + * pending draft, its publish is refused, and the author reloads: the draft, + * which the Save never discards, is re-read carrying the page's edit. + */ + async function reloadOverPendingDraft(): Promise { + server.servesPublishedVersion = true; + server.activeVersions.set(`object/${OBJECT.name}`, LIVE); + servePendingDraft(); + const a = openEditor(); + await loaded(a, '2 fields'); + server.active.set(`object/${OBJECT.name}`, { ...JSON.parse(JSON.stringify(OBJECT)), label: 'Task (moved)' }); + server.activeVersions.set(`object/${OBJECT.name}`, MOVED); + await addFieldFromGrid(a); + await saveIn(a); + await screen.findByTestId('draft-conflict-dialog', undefined, { timeout: 8000 }); + expect(server.saves[server.saves.length - 1]!.ifMatch).toBe(PENDING); + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), { timeout: 8000 }); + await loaded(a, '3 fields'); + expect(server.drafts.size).toBe(1); + return a; + } + + it('the next Save is asked again, pinned to the version the conflict was raised on', async () => { + const a = await reloadOverPendingDraft(); + const publishesBefore = server.publishes.length; + await addFieldFromGrid(a, SECOND); + await saveIn(a); + await screen.findByTestId('draft-conflict-dialog', undefined, { timeout: 8000 }); + expect(server.publishes.slice(publishesBefore).map((p) => p.ifMatch)).toEqual([LIVE]); + expect(server.active.get(`object/${OBJECT.name}`)!.label).toBe('Task (moved)'); + expect(liveFields()).toEqual(['title', 'status']); + }); + + it('asked again, "overwrite" is the re-confirmation: it publishes over the moved row, pinned to it', async () => { + const a = await reloadOverPendingDraft(); + await addFieldFromGrid(a, SECOND); + await saveIn(a); + await screen.findByTestId('draft-conflict-dialog', undefined, { timeout: 8000 }); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + await act(async () => { + fireEvent.click(await screen.findByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(liveFields()).toEqual(['title', 'status', 'new_field', 'second_field']), { timeout: 8000 }); + expect(server.publishes[server.publishes.length - 1]!.ifMatch).toBe(MOVED); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts index 58f0a758991..33942a0554a 100644 --- a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts +++ b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts @@ -383,6 +383,8 @@ export function usePairObjectActions( setSaving(true); setError(null); const refusals: string[] = []; + // The author chose to reload over a conflict: nothing of that row was saved. + let reloaded = false; try { let pair: string; try { @@ -420,6 +422,7 @@ export function usePairObjectActions( } else if ( (await saveGuarded('action', name, row.body, { mode: 'draft', packageId: pair, surface: 'studio' })) === 'reloaded' ) { + reloaded = true; setEdited(new Set()); continue; } @@ -428,6 +431,7 @@ export function usePairObjectActions( const outcome = await publishSavedItem(client, { type: 'action', name, packageId: pair }, row.draft, publishGuarded); // The published action moved and the author chose to reload: the pair's read installs it. if (!outcome.ok && 'reloaded' in outcome) { + reloaded = true; setEdited(new Set()); if (isNew) { setCreated((prev) => { @@ -481,7 +485,7 @@ export function usePairObjectActions( setError(reason); return { kind: 'refused', reason }; } - return { kind: 'saved' }; + return reloaded ? { kind: 'declined' } : { kind: 'saved' }; }, [client, created, edited, removed, pairForWrite, saveGuarded, publishGuarded, recordRead, recordPublished, reload]); const cancel = React.useCallback(() => { From 3fb6020228a523ac1182d7691847d7ae29bf26b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:26:37 +0000 Subject: [PATCH 3/5] test(studio): steady the hook and action race pins (WIP) Claude-Session: https://claude.ai/code/session_011y7As6kDA9BVrMsBR9rmrJ Co-authored-by: Claude --- ...llar.pairActionsPublishPinned-36726.test.tsx | 17 ++++++++++++++++- ...bjectHooksPanel.publishPinned-36726.test.tsx | 3 ++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx index aada32703be..1f853ce3b2f 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx @@ -199,6 +199,8 @@ import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarnes import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { t } from '../metadata-admin/i18n'; +import { indexCustomizations } from './customizationMarks'; +import type { PackageCustomizationsState } from './CustomizationMark'; const dataSource = createEmptyDataSource(); registerBuiltinInspectors(); @@ -207,6 +209,19 @@ const L = (key: string) => t(key, 'en'); const ensure = vi.fn(async (): Promise => PAIR); const WAIT = { timeout: 8000 }; +/** The base's customization read: the pair overrides nothing. */ +function marksRead(): PackageCustomizationsState { + const read = { + packageId: BASE, + overrides: [], + extensions: [], + switchedOff: [], + contributions: [], + counts: { overrides: 0, extensions: 0, switchedOff: 0 }, + } as never; + return { status: 'read', read, index: indexCustomizations(BASE, read)!, baseName: 'CRM', contributorNames: new Map() }; +} + function customization(): StudioBaseCustomization { return { base: BASE, @@ -216,7 +231,7 @@ function customization(): StudioBaseCustomization { pairId: PAIR, ensure, ensurePackage: vi.fn() as unknown as StudioBaseCustomization['ensurePackage'], - marks: { status: 'off' }, + marks: marksRead(), }; } diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx index c0924d4215d..e32e39b04a6 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx @@ -179,7 +179,8 @@ function openPanel() { /** Open the hook by its label and type a condition into its Expression tab: nothing is sent. */ async function edit(label: string, condition: string): Promise { - fireEvent.click(await screen.findByText(label, undefined, WAIT)); + // The rail's row: the open hook's label shows in its inspector too. + fireEvent.click((await screen.findAllByText(label, undefined, WAIT))[0]!); fireEvent.click(await screen.findByText('Expression')); const box = screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; fireEvent.change(box, { target: { value: condition } }); From e1949c71cc2c898be0f8e02b362c1754679dfcf0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:42:22 +0000 Subject: [PATCH 4/5] test(studio): new-row and repeat-edit pins on the hook and action harnesses; fixtures expect the create's If-None-Match Claude-Session: https://claude.ai/code/session_011y7As6kDA9BVrMsBR9rmrJ Co-authored-by: Claude --- .changeset/36726-studio-pinned-publish.md | 16 ++++++++++++++++ .../AutomationsPillar.saveCancel-36511.test.tsx | 3 ++- .../DataPillar.pairActions-30088.test.tsx | 5 +++-- ...illar.pairActionsPublishPinned-36726.test.tsx | 6 +++++- ...ObjectHooksPanel.publishPinned-36726.test.tsx | 10 ++++++++-- ...ioDesignSurface.expectedMisses-11799.test.tsx | 7 +++++-- 6 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 .changeset/36726-studio-pinned-publish.md diff --git a/.changeset/36726-studio-pinned-publish.md b/.changeset/36726-studio-pinned-publish.md new file mode 100644 index 00000000000..008194f244e --- /dev/null +++ b/.changeset/36726-studio-pinned-publish.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(studio): the object extension, hook, action and flow Saves no longer publish over another admin's live change + +Clause-②: no +Metadata-protocol: none + +Studio's top-bar Save writes an item's draft and then publishes that one item. The object page pinned that publish to the published row it was loaded at, but the other editors that save this way did not: two admins who opened the same object extension, hook, pair action or flow each passed the draft check, and the later Save replaced the earlier one's live change without a word. + +Each of those editors now reads the published version at the address its publish writes (the `/layers` read's `overlayVersion`) where its buffer is loaded, and its Save's publish sends it as `If-Match` (`If-None-Match: *` where nothing is published there yet). When another writer published since, the Save opens the same dialog the object page shows for a live change: reload re-reads the live item, overwrite (after a confirmation) publishes over the version the refusal names, and keep editing leaves the edits on the page, unsaved. The flow's on/off switch is pinned the same way. Creating a new hook, pair action or flow publishes with `If-None-Match: *`, so a same-named item another writer published first is refused instead of replaced. No dialog wording or locale key changes. + +A reload over a draft that was pending before the Save (a copilot's) now keeps the publish pinned to the version the conflict was raised on: the reload re-reads that draft, which carries the page's edits, and the next Save is asked again instead of publishing it over the row that moved. An overwrite, a publish that lands, or a load that finds no pending draft ends that hold. This applies to the object page too. + +A server that serves no `overlayVersion` gets an unpinned publish, as before. Nothing to migrate. diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx index 5cad7d7f672..11740bb08e0 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx @@ -248,7 +248,8 @@ describe('Flows — Save and Cancel in the top bar, live at once (objectstack#36 await waitFor(() => expect(server.log).toEqual(['save flow/escalate', 'publish flow/escalate']), { timeout: 8000 }); expect((mockClient.save.mock.calls[0] as unknown[])[3]).toMatchObject({ mode: 'draft', packageId: PKG, ifNoneMatch: '*' }); - expect(mockClient.publish).toHaveBeenCalledWith('flow', 'escalate', { packageId: PKG }); + // objectstack#36726 — asserting no published flow of its name. + expect(mockClient.publish).toHaveBeenCalledWith('flow', 'escalate', { packageId: PKG, ifNoneMatch: '*' }); expect(server.active.get('flow/escalate')?.status, 'born off').toBe('obsolete'); expect(server.drafts.has('flow/escalate'), 'no draft is left').toBe(false); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx index 1da2bc468ed..350438d9a8e 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx @@ -281,8 +281,9 @@ describe('Studio adds an action to an installed app’s object, in its customiza expect(name).not.toBe(VENDOR.name); expect(body).toMatchObject({ name, objectName: OBJECT, operation: 'update', locations: ['record_header'] }); expect(opts).toMatchObject({ mode: 'draft', packageId: PAIR, ifNoneMatch: '*' }); - // Then that one action is published at the pair: live at once. - expect(mockClient.publish).toHaveBeenCalledWith('action', name, { packageId: PAIR }); + // Then that one action is published at the pair: live at once, asserting + // no published action of its name (objectstack#36726). + expect(mockClient.publish).toHaveBeenCalledWith('action', name, { packageId: PAIR, ifNoneMatch: '*' }); expect(mockClient.save.mock.invocationCallOrder[0]).toBeLessThan(mockClient.publish.mock.invocationCallOrder[0]); expect(ensure).toHaveBeenCalledTimes(1); expect(saves().filter(([type]) => type === 'object')).toHaveLength(0); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx index 1f853ce3b2f..917a6da98ae 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsPublishPinned-36726.test.tsx @@ -93,7 +93,11 @@ const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; const servedObject = () => ({ name: OBJECT, label: 'Lead', - fields: { name: { type: 'text', label: 'Name' } }, + fields: { + name: { type: 'text', label: 'Name' }, + // The "Change a picklist field" preset a new row is made from needs one. + status: { type: 'select', label: 'Status', options: [{ label: 'New', value: 'new' }, { label: 'Hot', value: 'hot' }] }, + }, actions: [VENDOR, ...[...srv.active.values()].map((a) => ({ ...a, _packageId: PAIR }))], }); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx index e32e39b04a6..48cdecca93a 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.publishPinned-36726.test.tsx @@ -181,8 +181,14 @@ function openPanel() { async function edit(label: string, condition: string): Promise { // The rail's row: the open hook's label shows in its inspector too. fireEvent.click((await screen.findAllByText(label, undefined, WAIT))[0]!); - fireEvent.click(await screen.findByText('Expression')); - const box = screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; + // A hook whose condition is already an expression opens on that mode: no "Expression" choice to press. + const box = await waitFor(() => { + const mode = screen.queryByText('Expression'); + if (mode) fireEvent.click(mode); + const found = screen.queryAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA'); + if (!found) throw new Error('the condition box is not drawn yet'); + return found as HTMLTextAreaElement; + }, WAIT); fireEvent.change(box, { target: { value: condition } }); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.expectedMisses-11799.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.expectedMisses-11799.test.tsx index cf9af11c881..d2c3b175050 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.expectedMisses-11799.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.expectedMisses-11799.test.tsx @@ -268,7 +268,10 @@ describe('Interfaces pillar — an app found only in the drafts ledger (objectui }); describe('Automations pillar — opening flows asks no 404 question (objectui#11799)', () => { - it('a saved flow with no draft reads its baseline and no draft; an unsaved flow reads its draft and no baseline', async () => { + // objectstack#36726 — an unsaved flow's layers are read too, for the Save's + // publish pin; an item with only a draft has layers (objectstack#30859), so + // the read is answered, never a miss. + it('a saved flow with no draft reads its baseline and no draft; an unsaved flow reads its draft and its layers, no miss', async () => { put(server.active, 'flow', 'p_flow', flow('p_flow')); put(server.drafts, 'flow', 'fresh_flow', flow('fresh_flow')); render( @@ -283,7 +286,7 @@ describe('Automations pillar — opening flows asks no 404 question (objectui#11 fireEvent.click((await screen.findAllByText('fresh_flow'))[0]); await waitFor(() => expect(asked('flow', 'fresh_flow', '?state=draft')).toBe(1)); await settle(); - expect(asked('flow', 'fresh_flow', '/layers')).toBe(0); + expect(asked('flow', 'fresh_flow', '/layers')).toBe(1); expect(misses()).toEqual([]); }); }); From 0b5e8f27001eda6584b0d41a74215eabffa088f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 06:11:21 +0000 Subject: [PATCH 5/5] test(studio): the customize-flow fixture expects the pair publish's If-None-Match Claude-Session: https://claude.ai/code/session_011y7As6kDA9BVrMsBR9rmrJ Co-authored-by: Claude --- .../AutomationsPillar.customizeFlow-28570.test.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx index 13f7d47d68d..5b621145b48 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx @@ -352,8 +352,10 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' expect(srv.saves, 'nothing is written before Save (objectstack#36511)').toEqual([]); await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); - // Then that one flow is published at the pair: the override is live. - await waitFor(() => expect(srv.publishes).toEqual([{ name: FLOW_NAME, opts: { packageId: PAIR } }])); + // Then that one flow is published at the pair: the override is live. Read + // at the base, the Save takes the pair to hold no live flow of the name, + // and its publish asserts so (objectstack#36726). + await waitFor(() => expect(srv.publishes).toEqual([{ name: FLOW_NAME, opts: { packageId: PAIR, ifNoneMatch: '*' } }])); expect(srv.ensure).toEqual([201]); const [saved] = srv.saves; expect(saved!.name).toBe(FLOW_NAME);