From 71ac78567dc5e0c261050d62f87c54d0b81bed46 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:08:19 +0000 Subject: [PATCH 1/4] test(app-shell): Hooks tab pins for the AI assistant's pending hook draft (failing first) Claude-Session: https://claude.ai/code/session_01L9qibxGxp6swERUK2T9NML Co-Authored-By: Claude --- ...ectHooksPanel.aiDraftNotice-36660.test.tsx | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.aiDraftNotice-36660.test.tsx diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.aiDraftNotice-36660.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.aiDraftNotice-36660.test.tsx new file mode 100644 index 00000000000..6b4fd0e0cee --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.aiDraftNotice-36660.test.tsx @@ -0,0 +1,194 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36660 — the object designer's Hooks tab buffers a hook's pending + * draft and the top bar's Save publishes it at once. When the AI assistant + * (copilot or MCP) wrote that draft, the open hook carries the designers' line + * (`StudioAiDraftNotice`): Save makes the AI's change live too, and 「放弃 AI + * 的改动」 drops that one hook's draft at its package, asking first only when + * the hook holds unsaved edits. A person's own draft, or one whose read + * recorded no provenance, gets no such line. + */ + +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 { t } from '../metadata-admin/i18n'; + +const PKG = 'com.example.showcase'; +const guard = { name: 'guard_hook', label: 'Guard', object: 'invoice', events: ['beforeInsert'], handler: 'guard_fn' }; + +interface DraftRow { + body: Record; + version: string; + draftChanges?: Array<{ path: string[]; by: string; actor?: string; at: string }>; +} + +const door = { + drafts: new Map(), + resets: [] as Array<{ type: string; name: string; options: unknown }>, +}; + +const mockClient = { + list: vi.fn(async () => [guard]), + listDrafts: vi.fn(async () => [...door.drafts.keys()].map((name) => ({ type: 'hook', name }))), + getDraft: vi.fn(async (_type: string, name: string) => { + const row = door.drafts.get(name); + if (!row) return null; + return { + type: 'hook', + name, + item: JSON.parse(JSON.stringify(row.body)), + version: row.version, + ...(row.draftChanges ? { draftChanges: row.draftChanges } : {}), + }; + }), + get: vi.fn(async () => null), + withPreviewDrafts() { + return this; + }, + save: vi.fn(async (_type: string, name: string, body: Record) => { + door.drafts.set(name, { body: JSON.parse(JSON.stringify(body)), version: 'hmac-sha256:receipt' }); + return { success: true, version: 'hmac-sha256:receipt', state: 'draft' }; + }), + publish: vi.fn(async (_type: string, name: string) => { + door.drafts.delete(name); + return { success: true }; + }), + reset: vi.fn(async (type: string, name: string, options?: unknown) => { + door.resets.push({ type, name, options }); + door.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(); + +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' }], +}); + +let confirmSpy: ReturnType; + +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 = vi.spyOn(window, 'confirm').mockReturnValue(true); + __setCelFormulaLoader(() => + Promise.resolve({ + validateExpression: () => ({ ok: true, errors: [], warnings: [] }), + introspectScope: () => ({ fields: ['status'], roots: ['record'], functions: ['has'] }), + inferExpressionType: () => 'boolean' as const, + }), + ); +}); +afterEach(() => { + cleanup(); + confirmSpy.mockRestore(); + __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 } }); + await waitFor(() => expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(), { timeout: 8000 }); + expect(screen.queryByText('Guard (AI)')).toBeNull(); + }); +}); From dc26ca9a0ad0067c91e03c7d03cc9f98502ea963 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:12:32 +0000 Subject: [PATCH 2/4] feat(app-shell): the AI assistant's pending draft on a hook, a pair action and an OWD row gets the designers' line and discard Claude-Session: https://claude.ai/code/session_01L9qibxGxp6swERUK2T9NML Co-Authored-By: Claude --- ...taPillar.pairActionsAiDraft-36660.test.tsx | 331 ++++++++++++++++++ .../studio-design/ObjectActionsPanel.tsx | 14 + .../views/studio-design/ObjectHooksPanel.tsx | 15 + ...OverviewPanel.aiDraftNotice-36660.test.tsx | 196 +++++++++++ .../studio-design/PackageOwdOverviewPanel.tsx | 61 +++- .../studio-design/StudioAiDraftNotice.tsx | 5 +- .../views/studio-design/objectHooksBuffer.ts | 71 +++- .../views/studio-design/pairObjectActions.ts | 80 ++++- ui/packages/i18n/src/namespaces/studio/en.ts | 7 + ui/packages/i18n/src/namespaces/studio/zh.ts | 4 + 10 files changed, 771 insertions(+), 13 deletions(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsAiDraft-36660.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.aiDraftNotice-36660.test.tsx diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsAiDraft-36660.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsAiDraft-36660.test.tsx new file mode 100644 index 00000000000..4dd7b4049a9 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActionsAiDraft-36660.test.tsx @@ -0,0 +1,331 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36660 — on a read-only base's object, an action the base's pair + * adds is its own `action` item, buffered from its pending draft and published + * by the top bar's Save. When the AI assistant (copilot or MCP) wrote that + * draft, the open action carries the designers' line (`StudioAiDraftNotice`): + * Save makes the AI's change live too, and 「放弃 AI 的改动」 drops that one + * action's draft at the pair the ensure door answers, asking first only over + * the row's unsaved edit. A person's own draft gets no such line. + * + * The REAL `DataPillar`, Actions view and action editor over the metadata + * client double of DataPillar.pairActions-30088.test.tsx. + */ + +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'; + +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_page'], + type: 'script', + body: { language: 'expression', source: 'true' }, +}; + +/** An action the pair already holds on the object: published, and with a pending draft. */ +const KEPT = { + name: 'crm_lead_action_7', + label: 'Qualify', + objectName: OBJECT, + locations: ['record_page'], component: 'action:menu', + operation: 'update', + patch: { status: 'qualified' }, +}; + +const srv = vi.hoisted(() => ({ + /** The pair's published actions (every object's). */ + pairPublished: [] as Array>, + /** The pair's pending action drafts, by name. */ + pairDrafts: {} as Record>, + /** The provenance each pair draft's read serves, by name (absent: none recorded). */ + pairDraftChanges: {} as Record>>, + /** + * objectstack#35054 — what the pair's layered read serves for an action, by + * name, where it differs from the served reads above (which are then the + * translated copies). `draft: undefined` serves no `draft` key at all. + */ + stored: {} as Record | null; draft?: Record | null }>, +})); + +const servedObject = () => ({ + name: OBJECT, + label: 'Lead', + fields: { + name: { type: 'text', label: 'Name' }, + status: { + type: 'select', + label: 'Status', + options: [ + { label: 'New', value: 'new' }, + { label: 'Qualified', value: 'qualified' }, + ], + }, + }, + // The published pair action is served folded into the object, under the pair. + actions: [VENDOR, ...srv.pairPublished.filter((a) => a.objectName === OBJECT).map((a) => ({ ...a, _packageId: PAIR }))], +}); + +const mockClient = { + list: vi.fn(async (type: string, opts?: { packageId?: string }) => { + if (type === 'action') return opts?.packageId === PAIR ? srv.pairPublished.map((a) => ({ ...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 + ? Object.keys(srv.pairDrafts).map((name) => ({ type: 'action', name })) + : [], + ), + layered: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => { + if (type === 'action' && opts?.packageId === PAIR) { + // The pair's action as stored: by default the served rows (no translation in play). + const own = srv.stored[name]; + if (own) { + const layers: Record = { code: null, overlay: own.published, effective: own.published }; + if ('draft' in own) layers.draft = own.draft; + return layers; + } + const published = srv.pairPublished.find((a) => a.name === name) ?? null; + return { code: null, overlay: published, effective: published, draft: srv.pairDrafts[name] ?? null }; + } + return { effective: servedObject(), code: servedObject() }; + }), + getDraft: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => + type === 'action' && opts?.packageId === PAIR && srv.pairDrafts[name] + ? // Served decorated, as the draft read serves it. + { + type, + name, + item: { ...srv.pairDrafts[name], _packageId: PAIR }, + version: 'v1', + ...(srv.pairDraftChanges[name] ? { draftChanges: srv.pairDraftChanges[name] } : {}), + } + : null, + ), + get: vi.fn(async () => null), + // The pair's action drafts are kept, so a read after a write serves them. + publish: vi.fn(async () => ({})), + save: vi.fn(async (type: string, name: string, body: unknown, opts?: { packageId?: string }) => { + if (type === 'action' && opts?.packageId === PAIR) srv.pairDrafts[name] = body as Record; + return { ok: true, version: 'v2', state: 'draft' }; + }), + reset: vi.fn(async (type: string, name: string, opts?: { packageId?: string; state?: string }) => { + if (type === 'action' && opts?.packageId === PAIR) { + if (opts.state === 'draft') delete srv.pairDrafts[name]; + else srv.pairPublished = srv.pairPublished.filter((a) => a.name !== 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.actionRefusal-26736.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 '@object-ui/plugin-detail'; +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'; +import { indexCustomizations } from './customizationMarks'; +import type { PackageCustomizationsState } from './CustomizationMark'; + +const dataSource = createEmptyDataSource(); +registerBuiltinInspectors(); + +const L = (key: string) => t(key, 'en'); +let confirmSpy: ReturnType; +const ensure = vi.fn(async (): Promise => PAIR); + +/** 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 customizationOf(over: Partial = {}): StudioBaseCustomization { + return { + base: BASE, + baseLabel: 'CRM', + basedOn: '4.0.0', + walled: false, + pairId: PAIR, + ensure, + ensurePackage: vi.fn() as unknown as StudioBaseCustomization['ensurePackage'], + marks: marksRead(), + ...over, + }; +} + +beforeEach(() => { + srv.pairPublished = []; + srv.pairDrafts = {}; + srv.pairDraftChanges = {}; + srv.stored = {}; + confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true); + ensure.mockImplementation(async () => PAIR); +}); + +afterEach(() => { + cleanup(); + confirmSpy.mockRestore(); + vi.clearAllMocks(); +}); + +async function mountOnActions(props: { readOnly: boolean; customization?: StudioBaseCustomization | null }) { + render( + + + , + ); + // The first match is the flat tab (the passthrough menu draws a second). + fireEvent.click((await screen.findAllByRole('button', { name: L('engine.studio.data.tab.actions') }, { timeout: 8000 }))[0]); + await within(await screen.findByTestId('actions-list', undefined, { timeout: 8000 })).findByText('Convert'); +} + +/** Past the retired autosave's 1.5 s debounce: nothing may leave before Save. */ +async function outlastDebounce(): Promise { + await act(async () => { + await new Promise((r) => setTimeout(r, 2300)); + }); +} + +const list = () => screen.getByTestId('actions-list'); + +const AI_KEPT = { ...KEPT, label: 'Qualify (AI)', patch: { status: 'new' } }; +const AI_CHANGE = { path: ['patch'], by: 'copilot', actor: 'u1', at: '2026-11-27T10:00:00.000Z' }; +const notice = () => screen.queryByTestId('studio-ai-draft-notice'); + +async function openAiRow(changes: Array> | undefined = [AI_CHANGE]) { + srv.pairPublished = [KEPT]; + srv.pairDrafts = { [KEPT.name]: AI_KEPT }; + if (changes) srv.pairDraftChanges = { [KEPT.name]: changes }; + await mountOnActions({ readOnly: true, customization: customizationOf() }); + fireEvent.click(await within(list()).findByText('Qualify (AI)', undefined, { timeout: 8000 })); +} + +describe('a pair action\'s pending draft written by the AI assistant (objectstack#36660)', () => { + it('the open action shows the AI version with the notice, and a person\'s Save makes it live', async () => { + await openAiRow(); + expect(await screen.findByTestId('studio-ai-draft-notice')).toHaveTextContent(L('engine.studio.aiDraft.notice')); + fireEvent.change(screen.getByRole('textbox', { name: L('engine.inspector.action.label') }), { + target: { value: 'Qualify (AI, reviewed)' }, + }); + await pressStudioSave(); + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1)); + expect(mockClient.publish).toHaveBeenCalledWith('action', KEPT.name, { packageId: PAIR, draftVersion: expect.any(String) }); + await waitFor(() => expect(notice()).toBeNull()); + }, 30_000); + + it('an MCP-written draft is the AI\'s too', async () => { + await openAiRow([{ ...AI_CHANGE, by: 'mcp' }]); + expect(await screen.findByTestId('studio-ai-draft-notice')).toBeInTheDocument(); + }, 30_000); + + it('a person\'s own pending draft, or one whose read recorded nothing, gets no AI line', async () => { + await openAiRow([{ ...AI_CHANGE, by: 'studio' }]); + expect(screen.getByRole('textbox', { name: L('engine.inspector.action.label') })).toHaveValue('Qualify (AI)'); + expect(notice()).toBeNull(); + cleanup(); + await openAiRow(undefined); + expect(screen.getByRole('textbox', { name: L('engine.inspector.action.label') })).toHaveValue('Qualify (AI)'); + expect(notice()).toBeNull(); + }, 30_000); + + it('discard with nothing unsaved asks nothing and drops that one action\'s draft at the door\'s pair; the published action is back', async () => { + await openAiRow(); + fireEvent.click(await screen.findByTestId('studio-ai-draft-discard')); + await waitFor(() => expect(mockClient.reset).toHaveBeenCalledTimes(1)); + expect(confirmSpy).not.toHaveBeenCalled(); + expect(mockClient.reset).toHaveBeenCalledWith('action', KEPT.name, { state: 'draft', packageId: PAIR }); + expect(ensure).toHaveBeenCalledTimes(1); + expect(mockClient.publish).not.toHaveBeenCalled(); + expect(await within(list()).findByText('Qualify', undefined, { timeout: 8000 })).toBeInTheDocument(); + await waitFor(() => expect(notice()).toBeNull()); + expect(within(list()).queryByText('Qualify (AI)')).toBeNull(); + }, 30_000); + + it('discard over the row\'s unsaved edit asks first; declined, nothing is sent and the edit stays', async () => { + confirmSpy.mockReturnValue(false); + await openAiRow(); + const label = screen.getByRole('textbox', { name: L('engine.inspector.action.label') }); + fireEvent.change(label, { target: { value: 'Unsaved' } }); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(L('engine.studio.aiDraft.discardConfirmUnsaved')); + await outlastDebounce(); + expect(mockClient.reset).not.toHaveBeenCalled(); + expect(label).toHaveValue('Unsaved'); + expect(notice()).toBeInTheDocument(); + }, 30_000); + + it('discard over the row\'s unsaved edit, confirmed: the draft and the edit go', async () => { + await openAiRow(); + fireEvent.change(screen.getByRole('textbox', { name: L('engine.inspector.action.label') }), { + target: { value: 'Unsaved' }, + }); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledTimes(1); + await waitFor(() => expect(mockClient.reset).toHaveBeenCalledWith('action', KEPT.name, { state: 'draft', packageId: PAIR })); + expect(await within(list()).findByText('Qualify', undefined, { timeout: 8000 })).toBeInTheDocument(); + await waitFor(() => expect(notice()).toBeNull()); + }, 30_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx index 0aa8c150443..61e7a3251d8 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx @@ -97,6 +97,7 @@ import type { PairActionsDoor, PairObjectActions } from './pairObjectActions.js' import { RailCustomizationFilter, RailCustomizationMark, useRailCustomizationsOnly } from './StudioRailCustomizations.js'; import { FlowLedgerSwitch } from './FlowLedgerSwitch.js'; import { isStudioOrgScope } from './studioScope.js'; +import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; import { useActionLedger } from '../setup/packagedActionLedger.js'; interface ActionItem { @@ -160,6 +161,8 @@ const NO_PAIR_ACTIONS: PairObjectActions = { patch: () => undefined, remove: async () => undefined, reportBlocking: () => undefined, + discardAiDraft: () => undefined, + discardingAiDraft: null, dialog: <>, }; @@ -820,6 +823,17 @@ export function ObjectActionsPanel({ {tFormat('engine.studio.actions.renameHeld', locale, { name: selRenamedFrom })}

)} + {/* objectstack#36660 — the AI assistant's draft of this pair action is + what the row holds: Save makes it live too, and its discard + drops that one action's draft at the pair, the designers' line. */} + {selRow?.aiDraft && ( + added.discardAiDraft(selRow.name) : undefined} + busy={added.discardingAiDraft !== null || added.saving} + className="m-2 mb-0" + /> + )} {/* eslint-disable-next-line react-hooks/static-components -- useRegisteredMetadataDefaultInspector returns a registered component (stable), not one created during render */} ) : 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[] | undefined = [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 }]]), + saves: [], + publishes: [], + resets: [], + }; +} + +let client: ReturnType; +let confirmSpy: ReturnType; + +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 = vi.spyOn(window, 'confirm').mockReturnValue(true); +}); +afterEach(() => { + cleanup(); + confirmSpy.mockRestore(); +}); + +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' }], undefined]) { + 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({ > {onDiscard && (