diff --git a/.changeset/36648-studio-edit-after-save-kept.md b/.changeset/36648-studio-edit-after-save-kept.md new file mode 100644 index 00000000000..79ea1b38d47 --- /dev/null +++ b/.changeset/36648-studio-edit-after-save-kept.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(studio): an edit typed right as a Save ends is kept, not replaced by the Save's re-read of the object + +Clause-②: no +Metadata-protocol: none + +A Save in the Data pillar makes the object live, and the object is read again from the server once the Save has ended, so the page shows what the server holds. An edit made while that read is out was already kept. An edit made in the moment between the Save ending and the read starting was not: the page marked the object unchanged as the read started, the read then replaced the object with the server's copy, and the edit and the top bar's Save disappeared with it. That edit is now kept the same way, and its Save sends it. diff --git a/ui/packages/app-shell/src/views/metadata-admin/romanizeHan.test.ts b/ui/packages/app-shell/src/views/metadata-admin/romanizeHan.test.ts index ba16eadeff3..6643850217d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/romanizeHan.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/romanizeHan.test.ts @@ -4,14 +4,17 @@ * objectstack#29690 — the one Chinese step every Studio create door takes * before it derives an identifier from a display name (`romanizeHan`). * - * The cases run in file order on purpose: the first describe reads the module - * BEFORE the pinyin dictionary is loaded (its state is module-wide, as it is - * in the Console), the rest after `loadHanRomanizer()` resolved. The door - * sanitizers are the real ones, so each expectation is the identifier a door - * offers, not an intermediate string. + * The first describe reads the module BEFORE the pinyin dictionary is loaded + * (its state is module-wide, as it is in the Console), the rest after + * `loadHanRomanizer()` resolved. The `unit` project runs files with + * `isolate: false`, so an earlier file in the same worker may already have + * loaded the dictionary into the shared module instance: the first describe + * therefore reads a fresh instance (`vi.resetModules()` + a dynamic import), + * never the one other files share. The door sanitizers are the real ones, so + * each expectation is the identifier a door offers, not an intermediate string. */ -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { loadHanRomanizer, romanizeHan, romanizerPending } from './romanizeHan'; import { toFieldName, toFieldNameLoose, toFieldNameOrEmpty } from './previews/object-fields-io'; import { slugify } from './createDerive'; @@ -20,16 +23,29 @@ import { slugify } from './createDerive'; const fieldName = (label: string) => toFieldNameLoose(romanizeHan(label).trim()); describe('romanizeHan before the dictionary has loaded', () => { + /** A module instance no other file has touched: nothing has loaded the dictionary into it. */ + let fresh: typeof import('./romanizeHan'); + beforeAll(async () => { + vi.resetModules(); + fresh = await import('./romanizeHan'); + }); + it('returns the text unchanged and reports the Chinese text as pending', () => { - expect(romanizeHan('维修中心')).toBe('维修中心'); - expect(romanizerPending('维修中心')).toBe(true); + expect(fresh.romanizeHan('维修中心')).toBe('维修中心'); + expect(fresh.romanizerPending('维修中心')).toBe(true); }); it('is never pending for text that needs no dictionary', () => { - expect(romanizerPending('Repair Center')).toBe(false); - expect(romanizerPending('カスタマー')).toBe(false); - expect(romanizerPending('顧客リスト')).toBe(false); - expect(romanizerPending('')).toBe(false); + expect(fresh.romanizerPending('Repair Center')).toBe(false); + expect(fresh.romanizerPending('カスタマー')).toBe(false); + expect(fresh.romanizerPending('顧客リスト')).toBe(false); + expect(fresh.romanizerPending('')).toBe(false); + }); + + it('stays unchanged and pending until its own instance has loaded', async () => { + await fresh.loadHanRomanizer(); + expect(fresh.romanizerPending('维修中心')).toBe(false); + expect(fresh.romanizeHan('维修中心')).not.toBe('维修中心'); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pulseAfterSave-36648.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pulseAfterSave-36648.test.tsx new file mode 100644 index 00000000000..c5b61236286 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pulseAfterSave-36648.test.tsx @@ -0,0 +1,201 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36648 — an edit made right after a Save is the author's, even + * when it lands before the Save's re-read. + * + * A Save's publish sends the live-metadata pulse; the Data pillar holds it + * while the object's buffer carries work (`useMetadataRefreshNonce(hold)`) and + * releases it the moment the Save ends, and the release re-reads the object. + * A keystroke between that release and the re-read's effect used to be + * dropped: the effect cleared the dirty flag as it started, the read then saw + * nothing held and installed the server's body over the edit, and the top + * bar's Save was gone with the edit (the merge-queue red of + * `DataPillar.panelGate`'s first case, which types into exactly that window + * on a loaded runner). + * + * The window is a scheduler gap, too narrow to hit on purpose with real + * timing, so the hook is wrapped to report its release and the case types in + * the microtask right after it: before the re-read's effect, deterministically. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const objectDef = { + name: 'showcase_task', + label: 'Task', + fields: [{ name: 'status', label: 'Status', type: 'text' }], + validations: [ + { + type: 'script', + name: 'rule_a', + label: 'Rule A', + message: 'nope', + severity: 'error', + active: true, + }, + ], +}; + +const mockClient = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), + save: vi.fn(async () => ({})), + list: vi.fn(async () => [{ name: 'showcase_task', label: 'Task' }]), + listDrafts: vi.fn(async () => []), + layered: vi.fn(async () => ({ effective: objectDef, code: objectDef })), + getDraft: vi.fn(async () => null), +}; + +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 tabs live in a Radix DropdownMenu; rendered as passthroughs, as +// in DataPillar.panelGate.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 }; +}); + +/** What runs in the microtask right after the next pulse release, once. */ +const onRelease: { next: (() => void) | null } = { next: null }; + +// The real hook, word for word, plus the report of its release. +vi.mock('./useMetadataRefreshNonce', async () => { + const { useEffect, useState } = await import('react'); + const { subscribeMetadataRefresh } = await import('../../assistant/assistantBus.js'); + return { + useMetadataRefreshNonce(hold = false): number { + const [received, setReceived] = useState(0); + const [released, setReleased] = useState(0); + useEffect(() => subscribeMetadataRefresh(() => setReceived((n) => n + 1)), []); + useEffect(() => { + if (hold) return; + setReleased((cur) => (cur === received ? cur : received)); + if (released !== received && onRelease.next) { + const run = onRelease.next; + onRelease.next = null; + queueMicrotask(run); + } + }, [hold, received, released]); + return released; + }, + }; +}); + +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import * as React from 'react'; +import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; +import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; + +const dataSource = createEmptyDataSource(); +failOnAbsorbedFetchError(); + +registerBuiltinInspectors(); + +const DANGLING = /[*+\-/&|=<>]\s*$/; + +beforeEach(() => { + __setCelFormulaLoader(() => + Promise.resolve({ + validateExpression: (_role: string, input: unknown) => { + const src = typeof input === 'string' ? input : String((input as { source?: string })?.source ?? ''); + return DANGLING.test(src) + ? { ok: false, errors: [{ message: 'Parse error: expression ends after an operator' }], warnings: [] } + : { ok: true, errors: [], warnings: [] }; + }, + introspectScope: () => ({ fields: ['status'], roots: ['record'], functions: ['has'] }), + inferExpressionType: () => 'boolean' as const, + }), + ); +}); +afterEach(() => { + cleanup(); + __setCelFormulaLoader(undefined); + onRelease.next = null; + mockClient.save.mockClear(); +}); + +async function openRuleGuard(): Promise { + render( + + + , + ); + fireEvent.click(await screen.findByTestId('data-tab-flat-rules')); + fireEvent.click(await screen.findByText('Expression')); + return screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; +} + +/** Save the guard `first`, and type `next` the moment the Save's pulse is released. */ +async function saveThenTypeAtRelease(box: HTMLTextAreaElement, first: string, next: string): Promise { + fireEvent.change(box, { target: { value: first } }); + let typed = false; + onRelease.next = () => { + typed = true; + fireEvent.change(box, { target: { value: next } }); + }; + await pressStudioSave(); + await waitFor(() => expect(typed).toBe(true), { timeout: 4000 }); + expect(mockClient.save).toHaveBeenCalledTimes(1); + mockClient.save.mockClear(); +} + +describe('DataPillar — an edit made as a Save ends survives its re-read (objectstack#36648)', () => { + it('keeps a guard typed before the re-read, and its Save sends it', async () => { + const box = await openRuleGuard(); + await saveThenTypeAtRelease(box, "record.status == 'open'", "record.status == 'closed'"); + + // The edit is still on the page, and the top bar still offers its Save. + expect(box).toBeInTheDocument(); + expect(box.value).toBe("record.status == 'closed'"); + await pressStudioSave(); + await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 4000 }); + expect(JSON.stringify(mockClient.save.mock.calls[0])).toContain("record.status == 'closed'"); + }); + + it('keeps a guard that does not parse held, not dropped', async () => { + const box = await openRuleGuard(); + await saveThenTypeAtRelease(box, "record.status == 'open'", 'record.status =='); + + expect(box).toBeInTheDocument(); + expect(box.value).toBe('record.status =='); + await pressStudioSave(); + expect(mockClient.save).not.toHaveBeenCalled(); + }); +}); 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 bed4c6beb0a..09d9abc72b5 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -6230,14 +6230,24 @@ export function DataPillar({ setLoading(true); setError(null); if (!refreshOnly) setFieldSel(null); - // objectstack#27485 — kept CEL verdicts judged the buffer this load replaces. - setCelVerdicts({}); - setPanelCelVerdicts({}); - // objectstack#27644 — and so did the served one; a save's re-read in flight is dropped. - objVerdictSeq.current += 1; - setObjVerdict(undefined); - setObjVerdictBody(undefined); - setDirty(false); + // What the buffer this load replaces carried, dropped with it. + const dropReplacedBuffer = () => { + // objectstack#27485 — kept CEL verdicts judged the buffer this load replaces. + setCelVerdicts({}); + setPanelCelVerdicts({}); + // objectstack#27644 — and so did the served one; a save's re-read in flight is dropped. + objVerdictSeq.current += 1; + setObjVerdict(undefined); + setObjVerdictBody(undefined); + setDirty(false); + }; + // objectstack#36648 — a re-read on the pulse alone drops nothing until it + // installs: the pulse is released the moment a Save ends, and an edit made + // before this effect runs (a keystroke right after the Save) is the + // author's, kept by the in-flight rule below exactly as one made while the + // read is out. Dropped here, its dirty flag went, the read then installed + // over it, and the edit was lost with no Save left to press. + if (!refreshOnly) dropReplacedBuffer(); (async () => { try { // objectui#11773 — the draft is read at the address the object saves @@ -6281,7 +6291,10 @@ export function DataPillar({ // objectstack#32610 — an edit begun while the re-read was in flight // keeps its buffer; its save is pinned to the read it was made on. if (refreshOnly && objBuffersHeldRef.current) return; - if (refreshOnly) refreshInstalledRef.current = true; + if (refreshOnly) { + refreshInstalledRef.current = true; + dropReplacedBuffer(); + } objStoredRef.current = authored.body; setDestructive(null); setObjDraft(authored.body);