();
+ 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();
+
+const AI_GUARD = { ...guard, label: 'Guard (AI)', condition: "record.status == 'held'" };
+const aiDraft = (by: 'copilot' | 'mcp' = 'copilot'): DraftRow => ({
+ body: AI_GUARD,
+ version: 'hmac-sha256:ai',
+ draftChanges: [{ path: ['condition'], by, actor: 'u1', at: '2026-11-27T10:00:00.000Z' }],
+});
+
+const confirmSpy = vi.fn((_message?: string) => true);
+
+beforeEach(() => {
+ door.drafts.clear();
+ door.resets.length = 0;
+ for (const fn of [mockClient.list, mockClient.listDrafts, mockClient.getDraft, mockClient.save, mockClient.publish, mockClient.reset]) {
+ fn.mockClear();
+ }
+ confirmSpy.mockReset();
+ confirmSpy.mockReturnValue(true);
+ vi.stubGlobal('confirm', confirmSpy);
+ __setCelFormulaLoader(() =>
+ Promise.resolve({
+ validateExpression: () => ({ ok: true, errors: [], warnings: [] }),
+ introspectScope: () => ({ fields: ['status'], roots: ['record'], functions: ['has'] }),
+ inferExpressionType: () => 'boolean' as const,
+ }),
+ );
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ __setCelFormulaLoader(undefined);
+});
+
+async function openHook(label: string) {
+ render();
+ fireEvent.click(await screen.findByText(label, undefined, { timeout: 8000 }));
+}
+
+async function editCondition(value: string) {
+ fireEvent.click(await screen.findByText('Expression'));
+ const box = screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement;
+ fireEvent.change(box, { target: { value } });
+}
+
+describe('ObjectHooksPanel — the AI assistant\'s pending draft of a hook (objectstack#36660)', () => {
+ it('the open hook shows the AI version with the notice, and a person\'s Save makes it live', async () => {
+ door.drafts.set('guard_hook', aiDraft());
+ await openHook('Guard (AI)');
+ expect(await screen.findByTestId('studio-ai-draft-notice')).toHaveTextContent(
+ t('engine.studio.aiDraft.notice', 'en-US'),
+ );
+ await editCondition("record.status == 'closed'");
+ await pressStudioSave();
+ await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 });
+ await waitFor(() => expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull());
+ });
+
+ it('an MCP-written draft is the AI\'s too', async () => {
+ door.drafts.set('guard_hook', aiDraft('mcp'));
+ await openHook('Guard (AI)');
+ expect(await screen.findByTestId('studio-ai-draft-notice')).toBeInTheDocument();
+ });
+
+ it('a person\'s own pending draft gets no AI line', async () => {
+ door.drafts.set('guard_hook', {
+ ...aiDraft(),
+ draftChanges: [{ path: ['condition'], by: 'studio', actor: 'u1', at: '2026-11-20T10:00:00.000Z' }],
+ });
+ await openHook('Guard (AI)');
+ await screen.findByText('Expression');
+ expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull();
+ });
+
+ it('a draft whose read recorded no provenance is a person\'s too', async () => {
+ const { draftChanges: _omitted, ...bare } = aiDraft();
+ door.drafts.set('guard_hook', bare);
+ await openHook('Guard (AI)');
+ await screen.findByText('Expression');
+ expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull();
+ });
+
+ it('discard with nothing unsaved asks nothing, drops that one hook\'s draft at its package, and the live hook is back', async () => {
+ door.drafts.set('guard_hook', aiDraft());
+ await openHook('Guard (AI)');
+ fireEvent.click(await screen.findByTestId('studio-ai-draft-discard'));
+ await waitFor(() => expect(door.resets).toHaveLength(1), { timeout: 8000 });
+ expect(confirmSpy).not.toHaveBeenCalled();
+ expect(door.resets[0]).toEqual({ type: 'hook', name: 'guard_hook', options: { state: 'draft', packageId: PKG } });
+ expect(mockClient.publish).not.toHaveBeenCalled();
+ // The published row is what the list and the open hook hold now.
+ expect(await screen.findAllByText('Guard', undefined, { timeout: 8000 })).not.toHaveLength(0);
+ await waitFor(() => expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull());
+ expect(screen.queryByText('Guard (AI)')).toBeNull();
+ });
+
+ it('discard over an unsaved edit asks first; declined, the draft and the edit stay', async () => {
+ door.drafts.set('guard_hook', aiDraft());
+ confirmSpy.mockReturnValue(false);
+ await openHook('Guard (AI)');
+ await editCondition("record.status == 'unsaved'");
+ fireEvent.click(screen.getByTestId('studio-ai-draft-discard'));
+ expect(confirmSpy).toHaveBeenCalledWith(t('engine.studio.aiDraft.discardConfirmUnsaved', 'en-US'));
+ expect(mockClient.reset).not.toHaveBeenCalled();
+ expect(door.drafts.has('guard_hook')).toBe(true);
+ expect(screen.getByTestId('studio-ai-draft-notice')).toBeInTheDocument();
+ });
+
+ it('discard over an unsaved edit, confirmed: the draft and the edit go', async () => {
+ door.drafts.set('guard_hook', aiDraft());
+ await openHook('Guard (AI)');
+ await editCondition("record.status == 'unsaved'");
+ fireEvent.click(screen.getByTestId('studio-ai-draft-discard'));
+ expect(confirmSpy).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(door.drafts.has('guard_hook')).toBe(false), { timeout: 8000 });
+ expect(door.resets[0]).toEqual({ type: 'hook', name: 'guard_hook', options: { state: 'draft', packageId: PKG } });
+ // The list re-read installs the published hook.
+ await waitFor(() => expect(screen.queryAllByText('Guard (AI)')).toHaveLength(0), { timeout: 8000 });
+ expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull();
+ });
+});
diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx
index 1b07b110542..f8dfb2155a8 100644
--- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx
+++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx
@@ -34,6 +34,7 @@ import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js'
import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js';
import { formatMetadataError } from '@object-ui/data-objectstack';
import type { HookItem, ObjectHooksBuffer } from './objectHooksBuffer.js';
+import { StudioAiDraftNotice } from './StudioAiDraftNotice.js';
export function ObjectHooksPanel({
buffer,
@@ -80,6 +81,9 @@ export function ObjectHooksPanel({
replace,
addHook,
reportCel,
+ aiDraft,
+ discardAiDraft,
+ discardingAiDraft,
} = buffer;
// objectui#12514 — an object no hook targets is one centered block whose
@@ -203,6 +207,17 @@ export function ObjectHooksPanel({
) : null}
+ {/* objectstack#36660 — the AI assistant's draft of this hook is what
+ the buffer holds: Save makes it live too, and its discard drops
+ that one hook's draft, the designers' line. */}
+ {aiDraft && (
+
+ )}
{renamedFrom !== null && !disabled && (
({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+import { t } from '../metadata-admin/i18n';
+import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel';
+import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness';
+
+const PKG = 'com.example.showcase';
+const en = (key: string) => t(key, 'en-US');
+const PUBLIC_READ = en('engine.studio.settings.sharingPublicRead');
+
+type Body = Record;
+type Change = { path: string[]; by: string; actor?: string; at: string };
+
+interface Server {
+ published: Map;
+ drafts: Map;
+ saves: Array<{ name: string; body: Body }>;
+ publishes: string[];
+ resets: Array<{ name: string; opts: unknown }>;
+}
+
+let server: Server;
+
+function makeClient() {
+ return {
+ list: vi.fn(async (type: string) =>
+ type === 'object' ? [...server.published.values()].map((b) => ({ name: b.name, label: b.label })) : [],
+ ),
+ listDrafts: vi.fn(async () => [...server.drafts.keys()].map((name) => ({ type: 'object', name }))),
+ layered: vi.fn(async (_type: string, name: string) => {
+ const pub = server.published.get(name) ?? null;
+ return { effective: pub, code: null, overlay: pub };
+ }),
+ getDraft: vi.fn(async (_type: string, name: string) => {
+ const row = server.drafts.get(name);
+ if (!row) return null;
+ return { type: 'object', name, item: structuredClone(row.body), version: `draft:${name}`, ...(row.changes ? { draftChanges: row.changes } : {}) };
+ }),
+ save: vi.fn(async (_type: string, name: string, body: Body) => {
+ server.saves.push({ name, body: structuredClone(body) });
+ server.drafts.set(name, { body: structuredClone(body), changes: server.drafts.get(name)?.changes });
+ return { success: true, version: `draft:${name}:2`, state: 'draft' };
+ }),
+ publish: vi.fn(async (_type: string, name: string) => {
+ server.publishes.push(name);
+ const d = server.drafts.get(name);
+ if (d) server.published.set(name, d.body);
+ server.drafts.delete(name);
+ return { success: true };
+ }),
+ reset: vi.fn(async (_type: string, name: string, opts?: unknown) => {
+ server.resets.push({ name, opts });
+ server.drafts.delete(name);
+ return { success: true };
+ }),
+ };
+}
+
+const AI_CHANGE: Change = { path: ['fields', 'notes'], by: 'copilot', actor: 'u1', at: '2026-11-27T10:00:00.000Z' };
+
+function freshServer(changes: Change[] | null = [AI_CHANGE]): Server {
+ const account = { name: 'crm_account', label: 'Account', sharingModel: 'private', fields: { name: { type: 'text' } } };
+ const contact = { name: 'crm_contact', label: 'Contact', sharingModel: 'private' };
+ return {
+ published: new Map([
+ ['crm_account', account],
+ ['crm_contact', contact],
+ ]),
+ // The AI added a field to Account: its draft is the whole object.
+ drafts: new Map([
+ ['crm_account', { body: { ...account, fields: { ...account.fields, notes: { type: 'textarea' } } }, changes: changes ?? undefined }],
+ ]),
+ saves: [],
+ publishes: [],
+ resets: [],
+ };
+}
+
+let client: ReturnType;
+const confirmSpy = vi.fn((_message?: string) => true);
+
+function renderPanel() {
+ client = makeClient();
+ render(
+
+
+ ,
+ );
+}
+
+async function pickOwd(testId: string, label: string): Promise {
+ fireEvent.keyDown(screen.getByTestId(testId), { key: 'ArrowDown' });
+ const listbox = await screen.findByRole('listbox');
+ fireEvent.click(within(listbox).getByRole('option', { name: label }));
+}
+
+const accountRow = () => screen.getByTestId('owd-row-crm_account');
+const contactRow = () => screen.getByTestId('owd-row-crm_contact');
+
+beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ confirmSpy.mockReset();
+ confirmSpy.mockReturnValue(true);
+ vi.stubGlobal('confirm', confirmSpy);
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('PackageOwdOverviewPanel — an object whose pending draft is the AI assistant\'s (objectstack#36660)', () => {
+ it('the row says the object has the AI\'s unpublished changes, and its Save makes all of them live', async () => {
+ server = freshServer();
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ expect(within(accountRow()).getByTestId('studio-ai-draft-notice')).toHaveTextContent(en('engine.studio.owd.aiDraftNotice'));
+ expect(within(contactRow()).queryByTestId('studio-ai-draft-notice')).toBeNull();
+
+ await pickOwd('owd-internal-crm_account', PUBLIC_READ);
+ await pressStudioSave();
+ await waitFor(() => expect(server.publishes).toEqual(['crm_account']));
+ // The row's Save carried the AI's field, as the notice said.
+ expect(server.saves[0]!.body).toMatchObject({ sharingModel: 'public_read', fields: { notes: { type: 'textarea' } } });
+ await waitFor(() => expect(within(accountRow()).queryByTestId('studio-ai-draft-notice')).toBeNull());
+ });
+
+ it('an MCP-written draft is the AI\'s too', async () => {
+ server = freshServer([{ ...AI_CHANGE, by: 'mcp' }]);
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ expect(within(accountRow()).getByTestId('studio-ai-draft-notice')).toBeInTheDocument();
+ });
+
+ it('a person\'s own draft, or one whose read recorded nothing, keeps the plain unpublished chip and no AI line', async () => {
+ for (const changes of [[{ ...AI_CHANGE, by: 'studio' }], null]) {
+ server = freshServer(changes);
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ expect(within(accountRow()).queryByTestId('studio-ai-draft-notice')).toBeNull();
+ expect(within(accountRow()).getByText(en('engine.studio.unpublishedDraft'))).toBeInTheDocument();
+ cleanup();
+ }
+ });
+
+ it('discard with the row unedited asks nothing and drops that object\'s draft at the package; another row keeps its edit', async () => {
+ server = freshServer();
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ await pickOwd('owd-internal-crm_contact', PUBLIC_READ);
+ fireEvent.click(within(accountRow()).getByTestId('studio-ai-draft-discard'));
+ await waitFor(() => expect(server.resets).toHaveLength(1));
+ expect(confirmSpy).not.toHaveBeenCalled();
+ expect(server.resets[0]).toEqual({ name: 'crm_account', opts: { state: 'draft', packageId: PKG } });
+ expect(server.publishes).toEqual([]);
+ await waitFor(() => expect(within(accountRow()).queryByTestId('studio-ai-draft-notice')).toBeNull());
+ expect(screen.getByTestId('owd-dirty-crm_contact')).toBeInTheDocument();
+ expect(screen.getByTestId('owd-internal-crm_contact')).toHaveTextContent(PUBLIC_READ);
+ });
+
+ it('discard over the row\'s own unsaved edit asks first; declined, nothing is sent and the edit stays', async () => {
+ server = freshServer();
+ confirmSpy.mockReturnValue(false);
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ await pickOwd('owd-internal-crm_account', PUBLIC_READ);
+ fireEvent.click(within(accountRow()).getByTestId('studio-ai-draft-discard'));
+ expect(confirmSpy).toHaveBeenCalledWith(en('engine.studio.owd.aiDraftDiscardConfirmUnsaved'));
+ expect(client.reset).not.toHaveBeenCalled();
+ expect(screen.getByTestId('owd-dirty-crm_account')).toBeInTheDocument();
+ });
+
+ it('discard over the row\'s own unsaved edit, confirmed: the draft and the edit go', async () => {
+ server = freshServer();
+ renderPanel();
+ await screen.findByTestId('owd-row-crm_account');
+ await pickOwd('owd-internal-crm_account', PUBLIC_READ);
+ fireEvent.click(within(accountRow()).getByTestId('studio-ai-draft-discard'));
+ expect(confirmSpy).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(server.resets).toHaveLength(1));
+ await waitFor(() => expect(screen.queryByTestId('owd-dirty-crm_account')).toBeNull());
+ expect(within(accountRow()).queryByTestId('studio-ai-draft-notice')).toBeNull();
+ });
+});
diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx
index b5b15b56a65..09c1b89026b 100644
--- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx
+++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx
@@ -29,6 +29,10 @@
* read of the load the edit was made on (objectstack#37515): a draft
* written since, or one that appeared after the page loaded, is refused
* and asked about, never overwritten or published unseen.
+ * • A row whose object holds the AI assistant's pending draft (copilot or
+ * MCP) says so (objectstack#36660): its Save publishes that whole draft,
+ * not only the sharing model, and its discard drops that object's draft
+ * at the package, asking first only over the row's own unsaved edit.
* • `controlled_by_parent` rows show the master link (read-only) under the
* row's dial.
* • There is no external column: `externalSharingModel` is retired by
@@ -46,7 +50,10 @@ import type { MetadataClient, MetadataLayered } from '@object-ui/data-objectstac
// …and `formatMetadataError`, the one metadata-save error reader (objectui#11302).
// …and `dropServedPicklistOptions`, the served -> authored conversion of a
// picklist-bound field (objectui#10202, objectui#11692).
-import { dropServedPicklistOptions, extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack';
+import { dropServedPicklistOptions, extractDraftBody, formatMetadataError, readDraftChanges } from '@object-ui/data-objectstack';
+import { StudioAiDraftNotice } from './StudioAiDraftNotice.js';
+import { isAgentDraftSurface } from './StudioDraftMark.js';
+import { emitMetadataRefresh } from '../../assistant/assistantBus.js';
import {
Button,
Dialog,
@@ -109,6 +116,12 @@ interface OwdRow {
master?: string;
/** True when this object already has an unpublished draft. */
hasDraft: boolean;
+ /**
+ * objectstack#36660 — that draft was written by the AI assistant (a
+ * `copilot` or `mcp` entry in its read's `draftChanges`). The row's Save
+ * publishes the whole draft, so the row says so and offers its discard.
+ */
+ aiDraft: boolean;
/** True when the package's published list held this object at load (objectui#11799). */
saved: boolean;
/** What this load read, for an edit made on this row ({@link RowBasis}). */
@@ -466,6 +479,7 @@ export function PackageOwdOverviewPanel({
internal === 'controlled_by_parent' ? body.fields : requireCbpMasterDetails(body.fields),
),
hasDraft: !!draftBody,
+ aiDraft: !!draftBody && (readDraftChanges(draftRead.answer) ?? []).some((change) => isAgentDraftSurface(change.by)),
saved,
basis: { ...draftBasis, published: publishedPinOfRow(layRaw, saved) },
};
@@ -747,6 +761,38 @@ export function PackageOwdOverviewPanel({
}
}, [rowState, client, packageId, load, locale, publishPinned, recordPublished, recordRead, saveDraftGuarded, heldDraftVersion]);
+ // objectstack#36660 (epic objectstack#36510 decision 1) — 放弃 AI 的改动 on a
+ // row: that object's whole pending draft is dropped at this package
+ // (`DELETE /meta/object/NAME?state=draft&package=`), never the package's
+ // batch. The table is read back; the other rows keep their unsaved edits,
+ // and this row's own unsaved edit, which goes with the draft, is asked about first.
+ const [discardingAiDraft, setDiscardingAiDraft] = React.useState(null);
+ const discardAiDraft = React.useCallback(
+ 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;
+ const others = rowState.filter((s) => s.dirty && s.row.name !== name);
+ setDiscardingAiDraft(name);
+ setSaveError(null);
+ try {
+ await client.reset('object', name, { state: 'draft', packageId });
+ // The ledger behind Changes re-reads, one item fewer.
+ emitMetadataRefresh();
+ if (await load(new Set(others.map((o) => o.row.name)))) {
+ if (others.length > 0) {
+ setEdits((prev) => ({ ...prev, ...Object.fromEntries(others.map((o) => [o.row.name, o.edit])) }));
+ }
+ }
+ } catch (e) {
+ setSaveError(tFormat('engine.studio.aiDraft.discardFailed', locale, { reason: formatMetadataError(e) }));
+ } finally {
+ setDiscardingAiDraft(null);
+ }
+ },
+ [rowState, client, packageId, load, locale],
+ );
+
// Cancel: every dial back at what the server holds, nothing sent.
const doCancel = React.useCallback(() => {
setEdits(Object.fromEntries(rows.map((r) => [r.name, { internal: r.internal }])));
@@ -879,12 +925,23 @@ export function PackageOwdOverviewPanel({
{t('engine.studio.owd.unsaved', locale)}
)}
- {row.hasDraft && !dirty && (
+ {row.hasDraft && !row.aiDraft && !dirty && (
{t('engine.studio.unpublishedDraft', locale)}
)}
+ {/* objectstack#36660 — the object's pending draft is the
+ AI assistant's: this row's Save publishes all of it. */}
+ {row.aiDraft && (
+ void discardAiDraft(row.name)}
+ busy={discardingAiDraft !== null || saving}
+ className="mt-1"
+ />
+ )}
diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx
index 3d8d05488ba..f6c4e4dfed4 100644
--- a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx
+++ b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx
@@ -18,11 +18,14 @@ import { t } from '../metadata-admin/i18n.js';
export function StudioAiDraftNotice({
locale,
+ text,
onDiscard,
busy = false,
className,
}: {
locale: string;
+ /** The sentence, where the page names what the draft covers; else the item line's own. */
+ text?: string;
/** Drop the item's draft; `undefined` draws no button (a read-only item). */
onDiscard?: () => void;
busy?: boolean;
@@ -39,7 +42,7 @@ export function StudioAiDraftNotice({
>
- {t('engine.studio.aiDraft.notice', locale)}
+ {text ?? t('engine.studio.aiDraft.notice', locale)}
{onDiscard && (