Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/38302-ai-draft-discard-never-published.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

fix(app-shell): the AI-draft line's discard says it deletes an item that was never published

Clause-②: no
Metadata-protocol: none

Studio's AI-draft line (「放弃 AI 的改动」) titled its discard "go back to the live version" on every item. An item that was never published has no live version, and dropping its draft deletes it. The line now takes a `published` reading from its host and, for an item with none, titles the discard and words the unsaved-edit confirm as a delete (`engine.studio.aiDraft.discardTitleUnpublished`, `engine.studio.aiDraft.discardConfirmUnsavedUnpublished`, en and zh). A host that cannot tell keeps the live-version wording.
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ import {
import { usePackageCreateAsk } from './PackageCreateAsk.js';
// objectstack#36902 — Save takes effect at once; the AI draft's notice is the designers'.
import { isAiDraft, publishDetailSave } from './detailSaveAtOnce.js';
import { StudioAiDraftNotice } from '../studio-design/StudioAiDraftNotice.js';
import { StudioAiDraftNotice, aiDraftDiscardConfirmUnsaved } from '../studio-design/StudioAiDraftNotice.js';
import { publishFailureOf, publishRefusal, type StudioRefusal } from '../studio-design/metadataError.js';
import { emitMetadataRefresh } from '../../assistant/assistantBus.js';
// objectstack#29148 — the one strip a Studio editor draws for a refused draft read.
Expand Down Expand Up @@ -2648,7 +2648,8 @@ function MetadataResourceEditPageImpl({
setPendingConfirm({
kind: 'discardAi',
title: t('engine.studio.aiDraft.discard', locale),
description: t('engine.studio.aiDraft.discardConfirmUnsaved', locale),
// objectstack#38302 — an item that holds no layer was never published: the discard deletes it.
description: aiDraftDiscardConfirmUnsaved(locale, !holdsNoLayer(layered)),
actionLabel: t('engine.studio.aiDraft.discard', locale),
item: ownItemLabel() || `${type}/${name ?? ''}`,
});
Expand Down Expand Up @@ -3342,6 +3343,7 @@ function MetadataResourceEditPageImpl({
{aiDraft && (
<StudioAiDraftNotice
locale={locale}
published={!holdsNoLayer(layered)}
onDiscard={canWrite ? discardAiDraft : undefined}
busy={discardingAiDraft || saving || publishing}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { AUTOMATIONS_CONFIG_FOLD_WIDTH, useIsNarrowerThan } from './wideViewport
import { STUDIO_FOLD_LABEL } from './studio-tokens.js';
import { StudioInspector } from './StudioInspector.js';
import { isAgentDraftSurface } from './StudioDraftMark.js';
import { StudioAiDraftNotice } from './StudioAiDraftNotice.js';
import { StudioAiDraftNotice, aiDraftDiscardConfirmUnsaved } from './StudioAiDraftNotice.js';
import { StudioTab } from './StudioItemHeader.js';
import { ResourceDetailHeader, detailListHref } from '../metadata-admin/ResourceDetailHeader.js';
import { ItemToolTabPanel, ItemToolTabStrip } from '../item-tools/ItemToolTabs.js';
Expand Down Expand Up @@ -799,10 +799,14 @@ export function AutomationsPillar({
// read at), back to the live version. Edits not yet saved go with it, asked first.
const flowAiDraft =
flowLoaded && hasDraft && (flowDraftChanges ?? []).some((change) => isAgentDraftSurface(change.by));
// objectstack#38302 — a flow the published list does not hold has no live
// version: its discard deletes it, and the line and the confirm say so.
// `undefined` while that list is unread or its read failed.
const flowPublished = current && publishedFlowNames ? publishedFlowNames.has(current.name) : undefined;
const [discardingFlowDraft, setDiscardingFlowDraft] = React.useState(false);
const discardFlowDraft = React.useCallback(async () => {
if (!current) return;
if (autoDirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return;
if (autoDirty && !window.confirm(aiDraftDiscardConfirmUnsaved(locale, flowPublished))) return;
const at = flowReadAtRef.current?.key === `flow:${current.name}` ? flowReadAtRef.current.at : draftPackageId;
setDiscardingFlowDraft(true);
setError(null);
Expand All @@ -821,7 +825,7 @@ export function AutomationsPillar({
} finally {
setDiscardingFlowDraft(false);
}
}, [autoDirty, client, current, draftPackageId, locale, reloadFlowDraft]);
}, [autoDirty, client, current, draftPackageId, flowPublished, locale, reloadFlowDraft]);
// objectui#12725 — the header's draft line reads the badge's ledger.
const flowDraftStatus = useStudioItemDraftStatus(
current ? { type: 'flow', name: current.name } : null,
Expand Down Expand Up @@ -1497,6 +1501,7 @@ export function AutomationsPillar({
{flowAiDraft && (
<StudioAiDraftNotice
locale={locale}
published={flowPublished}
onDiscard={!editLocked ? () => void discardFlowDraft() : undefined}
busy={discardingFlowDraft || saving !== false}
/>
Expand Down Expand Up @@ -1597,7 +1602,7 @@ export function AutomationsPillar({
section,
onSectionChange: setFlowSection,
onProblemsChange: setProblemTally,
published: current && publishedFlowNames ? publishedFlowNames.has(current.name) : undefined,
published: flowPublished,
// objectstack#34818 — in the right slot, Debug draws the simulator there.
debugTarget: inSlot && section === 'debug' ? slot.propsTarget : null,
}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#38302 — the Data pillar's own AI line over the object canvas.
* Its 「放弃 AI 的改动」 drops the object's draft: for an object with a
* published or code version that goes back to it; for an object the AI
* created and nobody published there is none, and the discard deletes it.
* The button's title and the confirm asked over an unsaved edit say which,
* from the pillar's own reading of the object's layers (`hasBaseline`: an
* effective or code version). Keys are named, never copy.
*
* The harness is the one of `DataPillar.aiDraftDiscard-36511.test.tsx`, with
* the layers read able to serve an object that holds no layer.
*/

import '@testing-library/jest-dom/vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';

const PACKAGE = 'com.example.showcase';
const live = {
name: 'showcase_task',
label: 'Task',
fields: {
priority: { name: 'priority', label: 'Priority', type: 'text' },
},
};
/** The AI's version: one field added. */
const aiVersion = {
...live,
fields: { ...live.fields, renewal_count: { name: 'renewal_count', label: 'Renewals', type: 'number' } },
};

const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toISOString();

/** What the next draft read serves: `null` for no draft. */
let draftEnvelope: Record<string, unknown> | null = null;
/** Whether the object has a version beyond its draft. */
let published = true;

const mockClient = {
save: vi.fn(async () => ({})),
publish: vi.fn(async () => ({})),
reset: vi.fn(async () => {
draftEnvelope = null;
return {};
}),
list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'showcase_task', label: 'Task' }] : [])),
listDrafts: vi.fn(async () => []),
// objectstack#38302 — `published` false serves an object with no layer
// beyond its draft: no published row and no code baseline.
layered: vi.fn(async () =>
published
? { effective: live, code: live, draft: draftEnvelope?.item ?? null }
: { effective: null, code: null, overlay: null, draft: draftEnvelope?.item ?? null },
),
getDraft: vi.fn(async () => draftEnvelope),
get: vi.fn(async () => null),
withPreviewDrafts() {
return this;
},
};

vi.mock('../metadata-admin/useMetadata', async (importOriginal) => {
const mod = await importOriginal<typeof import('../metadata-admin/useMetadata')>();
return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) };
});

vi.mock('./packages-io', async (importOriginal) => {
const mod = await importOriginal<typeof import('./packages-io')>();
return { ...mod, fetchPackages: vi.fn(async () => []) };
});

vi.mock('@object-ui/react', async (importOriginal) => {
const mod = await importOriginal<typeof import('@object-ui/react')>();
return { ...mod, useAdapter: () => dataSource };
});

import '@objectstack/lint';
import '@object-ui/plugin-detail';
import { DataPillar } from './StudioDesignSurface';
import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource';
import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField';
import { StudioSaveHarness } from './__tests__/studioSaveHarness';
import { t } from '../metadata-admin/i18n';

const discardDrafts = vi.fn(async () => ({ success: true, failedCount: 0, failed: [], discarded: [] }));
const dataSource = Object.assign(createEmptyDataSource(), {
getClient: () => ({ packages: { discardDrafts } }),
});
failOnAbsorbedFetchError();

const L = (key: string) => t(key, 'en-US');

const confirmSpy = vi.fn((_message?: string) => true);
beforeEach(() => {
draftEnvelope = null;
published = true;
confirmSpy.mockReset();
confirmSpy.mockReturnValue(true);
window.confirm = confirmSpy as unknown as typeof window.confirm;
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});

function serveDraft(by: string) {
draftEnvelope = {
type: 'object',
name: 'showcase_task',
item: { ...aiVersion, _draft: true },
version: 'v1',
draftChanges: [{ path: ['fields', 'renewal_count'], by, actor: 'usr_1', at: minutesAgo(2) }],
};
}

function renderPillar(onDraftSaved = vi.fn()): { onDraftSaved: ReturnType<typeof vi.fn> } {
render(
<MemoryRouter initialEntries={[`/studio/${PACKAGE}/data`]}>
<StudioSaveHarness locale="en-US">
<DataPillar objectName="showcase_task" packageId={PACKAGE} onDraftSaved={onDraftSaved} />
</StudioSaveHarness>
</MemoryRouter>,
);
return { onDraftSaved };
}

async function openForm(): Promise<void> {
fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') }));
await screen.findByTestId('form-toolbar');
}

const LIVE_TITLE = 'engine.studio.aiDraft.discardTitle';
const DELETE_TITLE = 'engine.studio.aiDraft.discardTitleUnpublished';
const LIVE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsaved';
const DELETE_CONFIRM = 'engine.studio.aiDraft.discardConfirmUnsavedUnpublished';

describe('the Data pillar AI line on an object never published (objectstack#38302)', () => {
it('an object the AI created and nobody published: the discard title says it deletes it', async () => {
published = false;
serveDraft('copilot');
renderPillar();
const line = await screen.findByTestId('studio-copilot-changes');
await waitFor(() => expect(within(line).getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', L(DELETE_TITLE)));
});

it('…and over an unsaved edit the confirm says so too; declined, nothing is sent', async () => {
published = false;
serveDraft('copilot');
renderPillar();
await openForm();
await addFieldFromFormToolbar(undefined, { label: 'Due' });
await screen.findByTestId('studio-save');
confirmSpy.mockReturnValueOnce(false);
fireEvent.click(screen.getByTestId('studio-ai-draft-discard'));
expect(confirmSpy).toHaveBeenCalledWith(L(DELETE_CONFIRM));
expect(mockClient.reset).not.toHaveBeenCalled();
});

it('CONTROL: an object with a published version keeps the live-version wording on the title and the confirm', async () => {
serveDraft('copilot');
renderPillar();
const line = await screen.findByTestId('studio-copilot-changes');
await waitFor(() => expect(within(line).getByTestId('studio-ai-draft-discard')).toHaveAttribute('title', L(LIVE_TITLE)));
await openForm();
await addFieldFromFormToolbar(undefined, { label: 'Due' });
await screen.findByTestId('studio-save');
confirmSpy.mockReturnValueOnce(false);
fireEvent.click(screen.getByTestId('studio-ai-draft-discard'));
expect(confirmSpy).toHaveBeenCalledWith(L(LIVE_CONFIRM));
});
});
9 changes: 6 additions & 3 deletions ui/packages/app-shell/src/views/studio-design/DataPillar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js';
import { type Surface } from './navSurface.js';
import { useSurfaceActionDeepLink } from './useSurfaceDeepLink.js';
import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js';
import { aiDraftDiscardConfirmUnsaved, aiDraftDiscardTitle } from './StudioAiDraftNotice.js';
import { InspectorShellHostProvider } from '../metadata-admin/inspectors/_shared.js';
import type { DestructiveChangeIssue } from '@objectstack/spec/api';
import {
Expand Down Expand Up @@ -1463,7 +1464,9 @@ export function DataPillar({
const [discardingItemDraft, setDiscardingItemDraft] = React.useState(false);
const discardItemDraft = React.useCallback(async () => {
if (!current) return;
if (dirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return;
// objectstack#38302 — an object with no baseline (no published or code
// version) was never published: the discard deletes it, and the confirm says so.
if (dirty && !window.confirm(aiDraftDiscardConfirmUnsaved(locale, hasBaseline))) return;
setDiscardingItemDraft(true);
setError(null);
try {
Expand All @@ -1480,7 +1483,7 @@ export function DataPillar({
} finally {
setDiscardingItemDraft(false);
}
}, [client, current, dirty, locale, packageId, reloadObjDraft]);
}, [client, current, dirty, hasBaseline, locale, packageId, reloadObjDraft]);
// 放弃全部未发布改动 — the package's discard door (`packages.discardDrafts`),
// which drops every pending draft of the package, the author's own too; the
// confirm says so. There is no per-turn undo.
Expand Down Expand Up @@ -2154,7 +2157,7 @@ export function DataPillar({
data-testid="studio-ai-draft-discard"
onClick={() => void discardItemDraft()}
disabled={discardingItemDraft || discardingDrafts || saving !== false}
title={t('engine.studio.aiDraft.discardTitle', locale)}
title={aiDraftDiscardTitle(locale, hasBaseline)}
className="font-medium text-amber-700 hover:underline disabled:opacity-50 dark:text-amber-300"
>
{t('engine.studio.aiDraft.discard', locale)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,7 @@ export function ObjectActionsPanel({
{selRow?.aiDraft && (
<StudioAiDraftNotice
locale={locale}
published={selRow.published}
onDiscard={editable(sel.name) ? () => added.discardAiDraft(selRow.name) : undefined}
busy={added.discardingAiDraft !== null || added.saving}
className="m-2 mb-0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export function ObjectHooksPanel({
addHook,
reportCel,
aiDraft,
aiDraftPublished,
discardAiDraft,
discardingAiDraft,
} = buffer;
Expand Down Expand Up @@ -213,6 +214,7 @@ export function ObjectHooksPanel({
{aiDraft && (
<StudioAiDraftNotice
locale={locale}
published={aiDraftPublished}
onDiscard={disabled ? undefined : discardAiDraft}
busy={discardingAiDraft || saving}
className="m-3 mb-0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,15 @@ export function PackageOwdOverviewPanel({
async (name: string) => {
const own = rowState.find((s) => s.row.name === name);
if (!own?.row.aiDraft) return;
if (own.dirty && !window.confirm(t('engine.studio.owd.aiDraftDiscardConfirmUnsaved', locale))) return;
// objectstack#38302 — an object the published list did not hold is
// deleted by the discard; the other rows keep their edits either way.
const ask = t(
own.row.saved
? 'engine.studio.owd.aiDraftDiscardConfirmUnsaved'
: 'engine.studio.owd.aiDraftDiscardConfirmUnsavedUnpublished',
locale,
);
if (own.dirty && !window.confirm(ask)) return;
const others = rowState.filter((s) => s.dirty && s.row.name !== name);
setDiscardingAiDraft(name);
setSaveError(null);
Expand Down Expand Up @@ -937,6 +945,7 @@ export function PackageOwdOverviewPanel({
<StudioAiDraftNotice
locale={locale}
text={t('engine.studio.owd.aiDraftNotice', locale)}
published={row.saved}
onDiscard={readOnly ? undefined : () => void discardAiDraft(row.name)}
busy={discardingAiDraft !== null || saving}
className="mt-1"
Expand Down
Loading
Loading