diff --git a/.changeset/34725-studio-ai-assistant-panel.md b/.changeset/34725-studio-ai-assistant-panel.md new file mode 100644 index 00000000000..3e3052c2ae5 --- /dev/null +++ b/.changeset/34725-studio-ai-assistant-panel.md @@ -0,0 +1,23 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(studio): the Studio AI panel matches the console's AI assistant + +Clause-②: yes (widening — new studio-namespace locale keys, and one optional `columnMarks` member on the published `GridFieldAuthoring` interface of @object-ui/components) +Metadata-protocol: none + +The AI panel on Studio's right side now looks and works like the console's AI assistant drawer. + +- It is called "AI Assistant" (「AI 助手」) everywhere, including the line that says which tool drafted a change. +- Studio's top bar shows the console's robot button in the same place. It shows or hides the right panel and always opens it on the AI assistant. `⌘.` still switches between properties and the assistant. Without an assistant, the panel icon stays. +- The panel has one header row: the Properties | AI Assistant switch on the left; History, widen and Close on the right. Usage and Share moved into the History view, which covers the chat and lists earlier conversations with New chat. +- The panel opens 420 px wide, like the console drawer. It can be dragged or keyed wider from its left edge and remembers the width under its own key. On a small screen it stays an overlay. Studio's top bar now names its pillars by its own width rather than the window's, so a wide panel never pushes the robot under it. +- The chip above the composer reads "Viewing: · " (「正在看:会议 · 记录」), never the internal name. +- On the Data canvas, the fields the AI assistant changed in the pending draft carry a draft chip on their records-grid column header and on their Form card. A line above the canvas says "The AI assistant just made N changes", with Review, which opens the pending changes, and "Discard all unpublished changes", which discards the package's drafts after a confirm. + +`@object-ui/components`: `GridFieldAuthoring` takes an optional `columnMarks`, a node per accessorKey that `data-table` draws after the column's header label. + +`@object-ui/i18n`: new studio keys `engine.studio.slot.history`, `engine.studio.slot.resize` and `engine.studio.copilotChanges.*`. Changed values: `engine.studio.aiCopilot` and `engine.studio.draftMark.agent.copilot` (AI Assistant), `console.ai.discussing` (Viewing / 正在看, in every pack), and `draftedByCopilot` (AI assistant). No key was removed. Studio no longer reads `engine.studio.slot.openFullPage`. diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 2969ba231c6..46d0cf580cf 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -1783,6 +1783,14 @@ interface ChatPaneProps { onDebug?: () => void; /** Show the Build Doctor button — true only for build-agent conversations. */ showDebug?: boolean; + /** + * objectstack#34725 — the host draws the panel's one title bar itself (the + * Studio right slot: 属性 | AI 助手, History, widen, Close), so the pane + * omits its own header row: the agent switcher, the app chip, Share and the + * Build Doctor button. The host then offers Share where it chooses. + * @default false + */ + hideHeader?: boolean; } export function ChatPane({ @@ -1812,6 +1820,7 @@ export function ChatPane({ onShare, onDebug, showDebug, + hideHeader = false, }: ChatPaneProps) { const { t, language } = useObjectTranslation(); const navigate = useNavigate(); @@ -2985,7 +2994,7 @@ export function ChatPane({ packageRemovalPartialLabel={(failed) => t('console.ai.packageRemovalPartial', { count: failed })} surface="plain" maxHeight="100%" - headerSlot={headerSlot} + headerSlot={hideHeader ? undefined : headerSlot} // objectui#12978 — the drafts line (`pendingDraftsBar` above) is a row // of the composer's own area, in // flow above the input. The bar used to float (`absolute bottom-20`) @@ -3276,7 +3285,7 @@ export function ChatPane({ surfaceContextLabel={ surfaceContext?.artifact ? t('console.ai.discussing', { - defaultValue: 'Discussing: {{target}}', + defaultValue: 'Viewing: {{target}}', target: surfaceArtifactLabel || `${surfaceContext.artifact.type} · ${surfaceContext.artifact.name}`, diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx index d02446c49cc..3e784124af1 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx @@ -7,7 +7,7 @@ * objectui#7254's ruling: what is READ is the label; the internal identity * stays REACHABLE on a tooltip. Before this, ChatPane built the chip from the * `context.surface` artifact alone, so the chip printed - * `Discussing: dashboard · customer_dashboard` at the reader. + * `Viewing: dashboard · customer_dashboard` at the reader. * * The display label reaches ChatPane as its OWN optional prop * (`surfaceArtifactLabel`), never inside `surfaceContext` — that object is the @@ -85,7 +85,7 @@ const SURFACE = { artifact: { type: 'dashboard', name: 'customer_dashboard' }, }; -function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typeof SURFACE }) { +function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typeof SURFACE; hideHeader?: boolean }) { cleanup(); captured = {}; chatOptions = {}; @@ -110,6 +110,7 @@ function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typ pendingFirstMessageRef={{ current: null }} onSent={vi.fn()} onShare={vi.fn()} + hideHeader={extra.hideHeader} {...labelProp} /> @@ -124,13 +125,13 @@ afterEach(() => cleanup()); describe('AI chat "discussing" chip — label read, internal id on the tooltip (objectui#8219)', () => { it('with a display label: the chip reads the label and its title is the type · name pair', () => { const { props } = renderPane({ surfaceContext: SURFACE, surfaceArtifactLabel: 'Customer dashboard' }); - expect(props.surfaceContextLabel).toBe('Discussing: Customer dashboard'); + expect(props.surfaceContextLabel).toBe('Viewing: Customer dashboard'); expect(props.surfaceContextTitle).toBe('dashboard · customer_dashboard'); }); it('with no display label: the chip falls back to the type · name pair, still reachable as its title', () => { const { props } = renderPane({ surfaceContext: SURFACE }); - expect(props.surfaceContextLabel).toBe('Discussing: dashboard · customer_dashboard'); + expect(props.surfaceContextLabel).toBe('Viewing: dashboard · customer_dashboard'); expect(props.surfaceContextTitle).toBe('dashboard · customer_dashboard'); }); @@ -157,3 +158,12 @@ describe('AI chat "discussing" chip — label read, internal id on the tooltip ( expect(JSON.stringify(bodyOf(withLabel))).not.toContain('Customer dashboard'); }); }); + +// objectstack#34725 — a host that draws its own title bar (the Studio slot's +// one header row) asks the pane for none; every other host keeps the header. +describe('ChatPane hideHeader (objectstack#34725)', () => { + it('draws its header by default, and none when the host asks', () => { + expect(renderPane({ surfaceContext: SURFACE }).props.headerSlot).toBeTruthy(); + expect(renderPane({ surfaceContext: SURFACE, hideHeader: true }).props.headerSlot).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index 11548ecb0f8..ad54f8f4443 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -1247,7 +1247,7 @@ function EntryDetail({ data-testid="draft-entry-agent" > {source.by === 'copilot' - ? t('preview.changes.draftedByCopilot', { defaultValue: 'Includes changes drafted by the AI copilot' }) + ? t('preview.changes.draftedByCopilot', { defaultValue: 'Includes changes drafted by the AI assistant' }) : source.client ? t('preview.changes.draftedByMcpClient', { client: source.client, diff --git a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx index 66b7a49ab6f..ee5f0b020e5 100644 --- a/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx +++ b/ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx @@ -30,6 +30,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ }), })); +// The source loads `@objectstack/lint` lazily; paid here, at collection, not +// inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { DraftChangesPanel, draftAgentSources } from '../DraftChangesPanel'; const PKG = 'com.x'; @@ -78,7 +81,7 @@ describe('objectstack#27176 — the drill-in names the AI tools that drafted the await renderConfirm(); expect(agentLines()).toEqual([ 'Includes changes drafted by the MCP client “Claude”', - 'Includes changes drafted by the AI copilot', + 'Includes changes drafted by the AI assistant', ]); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx new file mode 100644 index 00000000000..061fe31a72a --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34725 item 7 — the AI assistant's drafts on the Data canvas: + * - a line over the canvas, 「AI 刚改了 N 处」, counting the pending draft's + * `draftChanges` entries an AI tool wrote (copilot or MCP), with 查看 (the + * pending-changes sheet) and 放弃全部未发布改动 (the package's discard door, + * `packages.discardDrafts`, after a confirm) — the one undo there is; + * - the Form canvas's card of each field the assistant changed carries the + * 草稿 chip; + * - item 6: the copilot's chip names the open object by its label and the view + * on screen (`Task · Records`), never its internal name. + * CONTROL: entries a person wrote in Studio, or no draft, draw no line. + * + * The records grid's column marks ride on `GridFieldAuthoring.columnMarks`, + * pinned in `@object-ui/components` (`data-table-columnMarks-34725`): a + * field the assistant added is a draft, and the grid selects published fields + * only (cloud#1652), so a new field has no column until it is published. + */ + +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 objectDef = { + name: 'showcase_task', + label: 'Task', + fields: { + priority: { name: 'priority', label: 'Priority', type: 'text' }, + 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 | null = null; + +const mockClient = { + save: vi.fn(async () => ({})), + list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'showcase_task', label: 'Task' }] : [])), + listDrafts: vi.fn(async () => []), + layered: vi.fn(async () => ({ effective: objectDef, code: objectDef, 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(); + 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 }; +}); + +import '@objectstack/lint'; +import { DataPillar } from './StudioDesignSurface'; +import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; +import { t, tFormat } from '../metadata-admin/i18n'; + +const discardDrafts = vi.fn(async () => ({ success: true, failedCount: 0, failed: [], discarded: [] })); +const dataSource = Object.assign(createEmptyDataSource(), { + getClient: () => ({ packages: { discardDrafts } }), +}); +failOnAbsorbedFetchError(); + +beforeEach(() => { + draftEnvelope = null; +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +const L = (key: string) => t(key, 'en-US'); + +function serveDraft(draftChanges?: unknown[]) { + draftEnvelope = { + type: 'object', + name: 'showcase_task', + item: { ...objectDef, _draft: true }, + version: 'v1', + ...(draftChanges ? { draftChanges } : {}), + }; +} + +function renderPillar(props: Partial> = {}) { + return render( + + + , + ); +} + +const AI_TWO = [ + { path: [], by: 'studio', actor: 'usr_1', at: minutesAgo(30) }, + { path: ['fields', 'renewal_count'], by: 'copilot', actor: 'usr_1', at: minutesAgo(2) }, + { path: ['fields', 'priority', 'label'], by: 'mcp', client: 'Claude Desktop', actor: 'usr_1', at: minutesAgo(1) }, +]; + +describe('the AI assistant’s drafts on the Data canvas (objectstack#34725)', () => { + it('a line counts the AI entries; 查看 opens the review; the AI-changed field cards carry the chip', async () => { + serveDraft(AI_TWO); + const onReviewChanges = vi.fn(); + renderPillar({ onReviewChanges }); + const line = await screen.findByTestId('studio-copilot-changes'); + expect(line).toHaveTextContent(tFormat('engine.studio.copilotChanges.line', 'en-US', { count: 2 })); + fireEvent.click(within(line).getByTestId('studio-copilot-changes-view')); + expect(onReviewChanges).toHaveBeenCalledTimes(1); + + fireEvent.click(screen.getByRole('button', { name: L('engine.studio.data.tab.form') })); + await waitFor(() => expect(screen.getAllByTestId('studio-form-field-draft-chip')).toHaveLength(2)); + expect( + screen.getAllByTestId('studio-form-field-draft-chip').map((chip) => chip.getAttribute('data-draft-of')).sort(), + ).toEqual(['priority', 'renewal_count']); + }); + + it('one AI entry reads in the singular', async () => { + serveDraft([AI_TWO[1]]); + renderPillar(); + expect(await screen.findByTestId('studio-copilot-changes')).toHaveTextContent( + tFormat('engine.studio.copilotChanges.lineOne', 'en-US', { count: 1 }), + ); + }); + + it('放弃全部未发布改动 discards the package’s drafts after a confirm; a declined confirm sends nothing', async () => { + serveDraft(AI_TWO); + // jsdom draws no confirm; the pillar asks the window's. + const confirm = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true); + const original = window.confirm; + window.confirm = confirm; + renderPillar(); + const discard = await screen.findByTestId('studio-copilot-changes-discard'); + expect(discard).toHaveTextContent(L('engine.studio.copilotChanges.discardAll')); + fireEvent.click(discard); + expect(confirm).toHaveBeenCalledWith(L('engine.studio.copilotChanges.discardConfirm')); + expect(discardDrafts).not.toHaveBeenCalled(); + + const reads = mockClient.getDraft.mock.calls.length; + draftEnvelope = null; + fireEvent.click(discard); + await waitFor(() => expect(discardDrafts).toHaveBeenCalledWith('com.example.showcase')); + // The open object is read again, and the line goes with the draft. + await waitFor(() => expect(mockClient.getDraft.mock.calls.length).toBeGreaterThan(reads)); + await waitFor(() => expect(screen.queryByTestId('studio-copilot-changes')).toBeNull()); + window.confirm = original; + }); + + it('a discard that fails names each item by its label; the server’s words stay under Details', async () => { + serveDraft(AI_TWO); + discardDrafts.mockResolvedValueOnce({ + success: false, + failedCount: 2, + failed: [ + { type: 'object', name: 'showcase_task', error: 'E_LOCKED: row held by txn 42' }, + { type: 'view', name: 'showcase_task_grid', error: 'E_GONE' }, + ], + discarded: [], + } as never); + const original = window.confirm; + window.confirm = vi.fn(() => true); + renderPillar(); + fireEvent.click(await screen.findByTestId('studio-copilot-changes-discard')); + const message = await screen.findByTestId('studio-refusal-message'); + expect(message).toHaveTextContent( + tFormat('engine.studio.copilotChanges.discardFailed', 'en-US', { + items: ['Task', 'showcase_task_grid'].join(L('engine.studio.copilotChanges.itemSeparator')), + }), + ); + expect(message.textContent).not.toContain('E_LOCKED'); + expect(message.textContent).not.toContain('object/'); + expect(screen.getByTestId('studio-refusal-detail')).toHaveTextContent('object/showcase_task: E_LOCKED: row held by txn 42'); + window.confirm = original; + }); + + it('the copilot’s chip reads the object’s label and the view on screen', async () => { + const onSurfaceLabelChange = vi.fn(); + renderPillar({ onSurfaceLabelChange }); + await waitFor(() => + expect(onSurfaceLabelChange).toHaveBeenLastCalledWith({ + type: 'object', + name: 'showcase_task', + label: `Task · ${L('engine.studio.data.tab.records')}`, + }), + ); + fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') })); + await waitFor(() => + expect(onSurfaceLabelChange).toHaveBeenLastCalledWith( + expect.objectContaining({ label: `Task · ${L('engine.studio.data.tab.form')}` }), + ), + ); + }); + + it('CONTROL: entries a person wrote in Studio, or no draft at all, draw no line', async () => { + serveDraft([{ path: ['fields', 'renewal_count'], by: 'studio', actor: 'usr_1', at: minutesAgo(2) }]); + renderPillar(); + await screen.findByRole('button', { name: L('engine.studio.data.tab.form') }); + await waitFor(() => expect(mockClient.getDraft).toHaveBeenCalled()); + expect(screen.queryByTestId('studio-copilot-changes')).toBeNull(); + cleanup(); + + renderPillar(); + await screen.findByRole('button', { name: L('engine.studio.data.tab.form') }); + expect(screen.queryByTestId('studio-copilot-changes')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.draftMarkedFields-34725.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.draftMarkedFields-34725.test.tsx new file mode 100644 index 00000000000..e3bc0233d52 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.draftMarkedFields-34725.test.tsx @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34725 item 7 — the form canvas marks the fields the AI assistant + * changed in the pending draft: a 草稿 chip after the field card's label, for + * the names the Data pillar hands in `draftMarkedFields`, and on no other card. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { ObjectFormDesigner } from './ObjectFormDesigner'; +import { t } from '../metadata-admin/i18n'; + +afterEach(cleanup); + +const draft = { + name: 'hcpl_borrowing', + fields: [ + { name: 'title', type: 'text', label: 'Title' }, + { name: 'renew_count', type: 'number', label: 'Renewals' }, + ], +}; + +function renderDesigner(draftMarkedFields?: ReadonlySet) { + render( + {}} + onSelectGroup={() => {}} + draftMarkedFields={draftMarkedFields} + />, + ); +} + +describe('the form designer marks the AI assistant’s draft fields (objectstack#34725)', () => { + it('a marked field card carries the 草稿 chip; the others do not', () => { + renderDesigner(new Set(['renew_count'])); + const chips = screen.getAllByTestId('studio-form-field-draft-chip'); + expect(chips).toHaveLength(1); + expect(chips[0]).toHaveAttribute('data-draft-of', 'renew_count'); + expect(chips[0]).toHaveTextContent(t('engine.studio.draftMark.chip', 'en-US')); + }); + + it('with no marked fields, no chips', () => { + renderDesigner(); + expect(screen.queryByTestId('studio-form-field-draft-chip')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.tsx index 7a20429d957..a1bf5631253 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.tsx @@ -71,6 +71,7 @@ import { AddFieldPopover } from './AddFieldPopover.js'; import type { FieldTypeId } from '../metadata-admin/previews/field-types.js'; import { fieldTypeName } from '../metadata-admin/previews/fieldTypeName.js'; import { ContributionMark, contributedItemTitle } from './StudioRailCustomizations.js'; +import { DraftChip } from './StudioDraftMark.js'; import type { ContributedOnObject } from './contributionRows.js'; import { addFormSection, @@ -340,6 +341,12 @@ export interface ObjectFormDesignerProps { * read-only). */ contributedFields?: ReadonlyMap; + /** + * objectstack#34725 — the fields the AI assistant (or an agent through MCP) + * changed in the pending draft, by name (`agentDraftMarkOf`): their cards + * carry the 草稿 chip the properties panel shows. + */ + draftMarkedFields?: ReadonlySet; /** * objectstack#30057 — the form view the app opens for this object * (`selectRecordFormView`): its `sections` are the canvas, and every layout @@ -371,6 +378,8 @@ interface DesignerSection { const NO_CONTRIBUTED_FIELDS: ReadonlyMap = new Map(); const ContributedFieldsContext = React.createContext>(NO_CONTRIBUTED_FIELDS); +const NO_DRAFT_MARKED_FIELDS: ReadonlySet = new Set(); +const DraftMarkedFieldsContext = React.createContext>(NO_DRAFT_MARKED_FIELDS); /** * The Form tab's one toolbar row (objectui#12451): the host's mode control and @@ -477,6 +486,7 @@ function SortableField({ // objectstack#29786 — a field another package contributes reads as a // read-only card on any surface, and names its package. const contributed = React.useContext(ContributedFieldsContext).get(entry.name) ?? null; + const draftMarked = React.useContext(DraftMarkedFieldsContext).has(entry.name); const locked = readOnly || contributed !== null; const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: fid(entry.name), @@ -546,6 +556,7 @@ function SortableField({ {label} {required && *} + {draftMarked && } {contributed && ( )} @@ -772,6 +783,7 @@ export function ObjectFormDesigner({ readOnly = false, modeControl, contributedFields = NO_CONTRIBUTED_FIELDS, + draftMarkedFields = NO_DRAFT_MARKED_FIELDS, formView = null, }: ObjectFormDesignerProps): React.ReactElement { const locale = useMetadataLocale(); @@ -1071,6 +1083,7 @@ export function ObjectFormDesigner({ return ( +
+
); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx index 5ce70bc1a8a..475df72b6b9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx @@ -3,14 +3,16 @@ import React from 'react'; import { useLocation, useParams } from 'react-router-dom'; import { useAuth } from '@object-ui/auth'; -import { Button } from '@object-ui/components'; -import { Maximize2, Minimize2 } from 'lucide-react'; +import { Button, ShareDialog } from '@object-ui/components'; +import { Share2 } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/i18n'; import { useAgents } from '@object-ui/plugin-chatbot/core'; import { useChatConversation } from '../../hooks/useChatConversation.js'; import { chatConversationScope, chatProductOfAgent } from '../../hooks/chatScope.js'; import { resolveSurfaceAgent } from '../../hooks/surfaceAgent.js'; import { ChatPane, resolveApiBase, type PendingFirstMessage } from '../../console/ai/AiChatPage.js'; +import { ConversationsSidebar } from '../../console/ai/ConversationsSidebar.js'; +import { resolvePublicShareBase } from '../../console/organizations/resolveHomeUrl.js'; import { AiUsageIndicator } from '../../layout/AiUsageIndicator.js'; import { usePlanApprovalPendingCount } from '../../assistant/assistantBus.js'; @@ -35,6 +37,21 @@ interface StudioCopilotConversationProps { * `context.surface`). Absent → the chip reads `type · name`. */ surfaceLabel?: StudioSurfaceLabel | null; + /** + * objectstack#34725 — a thread picked from the History list: that + * conversation, or (`fresh`) a new one. Absent → the package's build thread. + */ + target?: StudioCopilotTarget | null; + /** The conversation the pane shows, reported for the History list's active row and Share. */ + onConversationChange?: (conversationId: string | undefined) => void; + /** Bumped after a send, so the History list re-reads (a new thread is titled after its first answer). */ + onSent?: (firstUserMessage?: string) => void; +} + +/** objectstack#34725 — what the History list opened in the Studio copilot. */ +export interface StudioCopilotTarget { + conversationId?: string; + fresh?: boolean; } /** @@ -47,6 +64,9 @@ interface StudioCopilotConversationProps { export function StudioCopilotConversation({ packageId, surfaceLabel, + target, + onConversationChange, + onSent, }: StudioCopilotConversationProps): React.ReactElement | null { // cloud#1610 — the URL is the single source of the surface context: the // pillar is the :tab route segment, the artifact is the `?surface=type:name` @@ -104,9 +124,16 @@ export function StudioCopilotConversation({ ? chatConversationScope({ appId: packageId, product: chatProductOfAgent(activeAgent) }) : undefined, apiBase, - activeId: undefined, - forceNew: false, + activeId: target?.conversationId, + forceNew: Boolean(target?.fresh) && !target?.conversationId, + }); + const onConversationChangeRef = React.useRef(onConversationChange); + React.useEffect(() => { + onConversationChangeRef.current = onConversationChange; }); + React.useEffect(() => { + onConversationChangeRef.current?.(conversationId); + }, [conversationId]); const pendingFirstMessageRef = React.useRef(null); // ADR-0028 — the composer's picked model, held here so it outlives the keyed @@ -135,9 +162,12 @@ export function StudioCopilotConversation({ conversationCreateError={createError} selectedModelId={selectedModelId} onSelectedModelChange={setSelectedModelId} - onSent={() => {}} + onSent={onSent ?? (() => {})} onShare={() => {}} showDebug={false} + // objectstack#34725 — the right slot draws the one title bar; Share + // and the usage reading sit in the History view (`StudioChatDock`). + hideHeader /> ); } @@ -170,12 +200,12 @@ export interface StudioChatDockProps { */ onStatusChange?: (status: StudioCopilotStatus) => void; /** - * objectstack#34610 (ADR-0057 Amendment A3) — the slot is widened in place. - * The expand control toggles it through `onWideChange`; the Studio page - * stays where it is. + * objectstack#34725 — the conversation history covers the chat while open + * (the pane stays mounted under it, so a streaming answer is never cut); the + * slot header's History button toggles it. Picking a row or New chat closes it. */ - wide?: boolean; - onWideChange?: (wide: boolean) => void; + historyOpen?: boolean; + onHistoryOpenChange?: (open: boolean) => void; } /** @@ -183,23 +213,26 @@ export interface StudioChatDockProps { * it was the ADR-0057 P3c right dock in the shared `ChatDockPanel` chrome * until then). Same conversation as before — the build agent over the P1 * `(user, package, build)` scope — and the same open-in-full-page door; only - * its host moved. The slot owns showing and hiding, its width and the small - * screen; this renders the conversation and its toolbar. + * its host moved. The slot owns showing and hiding, its width, the small + * screen and the one title bar (objectstack#34725); this renders the + * conversation and, behind the slot's History button, the history list with + * Share and the usage reading (the console drawer keeps them in its header). * - * - objectstack#34610 — the expand control widens the slot in place - * (`wide` / `onWideChange`) and the same control narrows it again. It used - * to open `/ai/build?package=…`, which after objectstack#34608 lands on Home - * with the drawer full window, so the Studio page was lost. + * - objectstack#34610 — the slot's widen control (in its header) widens the + * slot in place and narrows it again. It used to open + * `/ai/build?package=…`, which after objectstack#34608 lands on Home with + * the drawer full window, so the Studio page was lost. */ export function StudioChatDock({ packageId, surfaceLabel, onStatusChange, - wide = false, - onWideChange, + historyOpen = false, + onHistoryOpenChange, }: StudioChatDockProps): React.ReactElement | null { const { t: tc } = useObjectTranslation(); const apiBase = React.useMemo(() => resolveApiBase(), []); + const { user } = useAuth(); // The catalog gate lives HERE: the slot asks it, and draws nothing of a // copilot the catalog does not serve (community edition / no seat). @@ -221,38 +254,91 @@ export function StudioChatDock({ [], ); + // objectstack#34725 — the History list's pick, and the thread on screen. + const [target, setTarget] = React.useState(null); + const [conversationId, setConversationId] = React.useState(undefined); + // A fresh thread is named once its first send mints it, so the pick stops + // asking for a new one; the id on screen when New chat was pressed is never it. + const freshFromRef = React.useRef(undefined); + const onConversationChange = React.useCallback((id: string | undefined) => { + setConversationId(id); + if (!id || id === freshFromRef.current) return; + setTarget((prev) => (prev?.fresh ? { conversationId: id } : prev)); + }, []); + const activeAgent = React.useMemo(() => resolveSurfaceAgent('studio-build', { agents }), [agents]); + const [refreshKey, setRefreshKey] = React.useState(0); + const onSent = React.useCallback(() => setRefreshKey((k) => k + 1), []); + const [shareOpen, setShareOpen] = React.useState(false); + const restApiBase = React.useMemo( + () => apiBase.replace(/\/v1\/ai$/, '').replace(/\/ai$/, '') || '/api', + [apiBase], + ); + const publicShareBase = React.useMemo(() => resolvePublicShareBase(), []); + if (!available) return null; - const maximizeLabel = wide - ? tc('console.ai.dock.restore', { defaultValue: 'Restore side panel' }) - : tc('console.ai.dock.expand', { defaultValue: 'Expand' }); return ( <> -
- {/* ADR-0057 #8 — proactive AI usage indicator (hides itself when the - usage endpoint is absent / returns nothing to show). */} - - -
{/* flex-col so the ChatPane child (its root is `flex min-h-0 flex-1`) gets a bounded flex-column parent and keeps its composer on screen. */} -
+
+ {historyOpen ? ( +
+
+ {/* ADR-0057 #8 — proactive AI usage indicator (hides itself when the + usage endpoint is absent / returns nothing to show). */} + + +
+ { + if (conversation.id !== conversationId) setTarget({ conversationId: conversation.id }); + onHistoryOpenChange?.(false); + }} + onNewConversation={() => { + freshFromRef.current = conversationId; + setTarget({ fresh: true }); + onHistoryOpenChange?.(false); + }} + className="min-h-0 flex-1 border-r-0" + /> +
+ ) : null}
+ {conversationId ? ( + + ) : null} ); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx index 85ad7e7d68a..c6292755d42 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx @@ -107,6 +107,9 @@ vi.mock('../../providers/AdapterProvider', async (importOriginal) => { vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); +// The source loads `@objectstack/lint` lazily; paid here, at collection, not +// inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { StudioDesignSurface } from './StudioDesignSurface'; window.matchMedia = ((query: string) => ({ @@ -193,7 +196,7 @@ describe('Studio copilot chip reads the selected item label (objectui#8219 item it('a labelled leaf: the chip reads the label, its title is type · name, and the agent data is unchanged', async () => { renderStudio(); await screen.findByRole('button', { name: '客户仪表盘 仪表盘' }); - await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在讨论:客户仪表盘'), { timeout: 4000 }); + await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在看:客户仪表盘'), { timeout: 4000 }); expect(chip.surfaceContextTitle).toBe('dashboard · b2r4_customer_dashboard'); // The label is display-only: the agent still receives exactly the // URL-derived surface, and no label under any key. @@ -210,7 +213,7 @@ describe('Studio copilot chip reads the selected item label (objectui#8219 item renderStudio(); // The rail row and the chip read the same inherited text. fireEvent.click(await screen.findByRole('button', { name: '客户 对象' })); - await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在讨论:客户'), { + await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在看:客户'), { timeout: 4000, }); expect(chip.surfaceContextTitle).toBe('object · b2r4_customer'); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx index 205d4ee5f58..e19146df1d4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx @@ -156,6 +156,8 @@ window.matchMedia = ((query: string) => ({ let serverDrafts: Array> = []; /** How many `_drafts` reads the page sent. */ let draftReads = 0; +/** What the package's published object list answers (the Data pillar's rail). */ +let objectRows: Array> = []; function json(body: unknown) { return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); @@ -216,6 +218,7 @@ const THREAD = [ beforeEach(() => { serverDrafts = [BORROWING_ROW]; draftReads = 0; + objectRows = []; sdk.discardDrafts.mockReset(); chat.set({ messages: uiMessagesToChatMessages(THREAD as never, { isStreaming: false }), isLoading: false }); window.sessionStorage.clear(); @@ -227,6 +230,7 @@ beforeEach(() => { draftReads += 1; return json({ drafts: serverDrafts }); } + if (url === `/api/v1/meta/object?package=${encodeURIComponent(PACKAGE_ID)}`) return json(objectRows); return json([]); }) as unknown as typeof fetch, ); @@ -301,6 +305,7 @@ describe('the Studio copilot\'s applied card opens the 变更 drawer in place (o describe('the Studio copilot\'s composer (objectui#12725 Target item 4)', () => { it('zh: the placeholder reads「问问数据,或让我改改这个应用…」, and the chip names the item in view', async () => { + objectRows = [{ name: 'hcpl_borrowing', label: '借阅记录' }]; render( @@ -314,10 +319,11 @@ describe('the Studio copilot\'s composer (objectui#12725 Target item 4)', () => const composer = await within(slot).findByRole('textbox'); expect(composer).toHaveAttribute('placeholder', '问问数据,或让我改改这个应用…'); // The chip `plugin-chatbot` declares (`surfaceContextLabel`), naming the - // item the URL has open. + // item the URL has open — objectstack#34725: 「正在看:借阅记录 · 记录」, + // the object's label and the view on screen, never the internal name. const chip = within(slot).getByTestId('surface-context-chip'); - expect(chip).toHaveTextContent('正在讨论:'); - expect(chip).toHaveTextContent('hcpl_borrowing'); + await waitFor(() => expect(chip).toHaveTextContent('正在看:借阅记录 · 记录')); + expect(chip).not.toHaveTextContent('hcpl_borrowing'); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx index 6082de9bca0..e0591e0ede9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx @@ -61,8 +61,11 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); +// The source loads `@objectstack/lint` lazily; paid here, at collection, not +// inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { StudioDesignSurface } from './StudioDesignSurface'; -import { STUDIO_HEADER, STUDIO_HEADER_PILLAR, STUDIO_HEADER_PILLAR_NAV } from './studio-tokens'; +import { STUDIO_HEADER, STUDIO_HEADER_PILLAR, STUDIO_HEADER_PILLAR_NAME, STUDIO_HEADER_PILLAR_NAV } from './studio-tokens'; import { t } from '../metadata-admin/i18n'; const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); @@ -158,7 +161,11 @@ describe('Studio shell header below and above 640 px (objectui#12509)', () => { expect(link).toHaveClass(...STUDIO_HEADER_PILLAR.split(' ')); // objectui#12725 — named from 1024 px (`lg`, was `xl`): the right slot // leaves the top bar room for the four names at the card's 1010 reading. - expect(within(link).getByText(t(`engine.studio.pillar.${key}`, 'en'))).toHaveClass('sr-only', 'lg:not-sr-only'); + // objectstack#34725 — from a 724 px BAR (the old 1024 − 300 px slot): + // the slot is resizable now, so the bar's own width decides. + expect(within(link).getByText(t(`engine.studio.pillar.${key}`, 'en'))).toHaveClass( + ...STUDIO_HEADER_PILLAR_NAME.split(' '), + ); } // The chip is the piece that gives way on a tight row. diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx index b8fdc33e750..17c6494520d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx @@ -113,6 +113,9 @@ vi.mock('./StudioAiCopilot', () => ({ }, })); +// The source loads `@objectstack/lint` lazily; paid here, at collection, not +// inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; @@ -388,7 +391,7 @@ describe('Automations: the Configuration is in the right slot (objectui#12725)', // while the panel is hidden unfolds it on that node's configuration. it('a hidden slot unfolds on a selection, on the selected node’s configuration', async () => { await openFlow(); - fireEvent.click(screen.getByTestId('studio-slot-toggle')); + fireEvent.click(screen.getByTestId('topbar-ai-assistant')); expect(slot()).not.toBeVisible(); expect(window.sessionStorage.getItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY)).toBe('0'); @@ -396,7 +399,7 @@ describe('Automations: the Configuration is in the right slot (objectui#12725)', await waitFor(() => expect(slot()).toBeVisible()); expect(slot()).toHaveAttribute('data-mode', 'props'); expect(within(slotProps()).getByLabelText('Node start')).toBeVisible(); - expect(screen.getByTestId('studio-slot-toggle')).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByTestId('topbar-ai-assistant')).toHaveAttribute('aria-pressed', 'true'); expect(window.sessionStorage.getItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY)).toBe('1'); expect(screen.queryByTestId('auto-config-drawer')).toBeNull(); }); @@ -406,7 +409,7 @@ describe('Automations: the Configuration is in the right slot (objectui#12725)', fireEvent.click(screen.getByTestId('pick-node')); await waitFor(() => expect(within(slotProps()).getByTestId('stub-flow-inspector')).toBeVisible()); - fireEvent.click(screen.getByTestId('studio-slot-toggle')); + fireEvent.click(screen.getByTestId('topbar-ai-assistant')); await act(async () => {}); expect(slot()).not.toBeVisible(); // The same node again is no new selection. diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx index 14ed6b84a71..19ffbeb806c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx @@ -84,7 +84,11 @@ vi.mock('./StudioAiCopilot', () => ({ }, })); +// The source loads `@objectstack/lint` lazily; paid here, at collection, not +// inside a case's clock (check:test-source-alias). +import '@objectstack/lint'; import { StudioDesignSurface } from './StudioDesignSurface'; +import { STUDIO_HEADER_PILLAR_NAME, STUDIO_HEADER_WIDE_WORD } from './studio-tokens'; import { t, tFormat } from '../metadata-admin/i18n'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; @@ -235,7 +239,9 @@ describe('Studio right slot: properties OR the copilot (objectui#12725)', () => await waitFor(() => expect(within(slotProps()).queryByTestId('stub-inspector')).toBeNull()); }); - it('⌘. and Ctrl+. switch the halves; the top bar’s right-most icon hides the slot, under the Studio key', async () => { + // objectstack#34725 — with a copilot served, the right-most icon is the + // console top bar's robot: same component, same place, toggling the slot. + it('⌘. and Ctrl+. switch the halves; the top bar’s right-most icon (the robot) hides the slot, under the Studio key', async () => { await openDashboard(); await waitFor(() => expect(slot()).toHaveAttribute('data-mode', 'copilot')); @@ -249,11 +255,12 @@ describe('Studio right slot: properties OR the copilot (objectui#12725)', () => expect(slot()).toHaveAttribute('data-mode', 'copilot'); const header = screen.getByTestId('studio-shell-header'); - const toggle = within(header).getByTestId('studio-slot-toggle'); + expect(within(header).queryByTestId('studio-slot-toggle')).toBeNull(); + const toggle = within(header).getByTestId('topbar-ai-assistant'); const actions = toggle.parentElement as HTMLElement; expect(actions.lastElementChild).toBe(toggle); expect(toggle).toHaveAttribute('aria-pressed', 'true'); - expect(toggle).toHaveAccessibleName(t('engine.studio.slot.collapse', 'en')); + expect(toggle).toHaveAccessibleName('AI Assistant'); fireEvent.click(toggle); expect(slot()).not.toBeVisible(); @@ -267,11 +274,29 @@ describe('Studio right slot: properties OR the copilot (objectui#12725)', () => expect(window.sessionStorage.getItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY)).toBe('1'); }); + // objectstack#34725 — the robot always opens the panel on the AI assistant; + // the slot header's Close hides it the same way. + it('the robot opens a hidden slot on the AI assistant; the header’s Close hides it', async () => { + await openDashboard(); + await selectBlock(); + expect(slot()).toHaveAttribute('data-mode', 'props'); + fireEvent.click(within(slot()).getByTestId('studio-slot-close')); + expect(slot()).not.toBeVisible(); + expect(window.sessionStorage.getItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY)).toBe('0'); + + const robot = screen.getByTestId('topbar-ai-assistant'); + expect(robot).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(robot); + expect(slot()).toBeVisible(); + expect(slot()).toHaveAttribute('data-mode', 'copilot'); + expect(robot).toHaveAttribute('aria-pressed', 'true'); + }); + // objectstack#26737 — a selection is never drawn nowhere: at a desktop width // it unfolds a hidden slot on the selected block's properties. it('selecting a block while the slot is hidden unfolds it on the properties', async () => { await openDashboard(); - fireEvent.click(screen.getByTestId('studio-slot-toggle')); + fireEvent.click(screen.getByTestId('topbar-ai-assistant')); expect(slot()).not.toBeVisible(); fireEvent.click(screen.getByTestId('pick-block')); @@ -280,7 +305,7 @@ describe('Studio right slot: properties OR the copilot (objectui#12725)', () => expect(within(slotProps()).getByTestId('stub-inspector')).toBeVisible(); }); - // objectstack#25943 — 「AI 副驾 · N 项待确认」: the count of items the + // objectstack#25943 — 「AI 助手 · N 项待确认」: the count of items the // copilot proposed, on the tab's badge and in the folded strip. it('the copilot tab and strip count the items that await approval', async () => { copilot.planPendingCount = 2; @@ -319,20 +344,27 @@ describe('Studio right slot: properties OR the copilot (objectui#12725)', () => expect(within(sheet).getByTestId('if-definition-json')).toHaveTextContent('"name": "sales_overview"'); }); - it('the pillar names are visible from 1024 px (lg), icons below', async () => { + // objectstack#34725 — the names answer the top bar's own width, not the + // viewport's: the slot beside it is resizable, and a viewport breakpoint + // kept the names on while pushing the robot under the slot (en, 1163 px + // window, slot dragged to 520 px). The thresholds are the bar widths the old + // breakpoints gave beside the old fixed slot. + it('the pillar names show from a 724 px top bar, icons below; the area from 920 px', async () => { await openDashboard(); + expect(screen.getByTestId('studio-shell-header')).toHaveClass('@container/studio-header'); const links = within(screen.getByTestId('studio-pillar-nav')).getAllByRole('link'); // The four pillars, then (objectstack#28561) the "All metadata" area. expect(links).toHaveLength(5); + expect(STUDIO_HEADER_PILLAR_NAME).toBe('sr-only @min-[724px]/studio-header:not-sr-only'); + expect(STUDIO_HEADER_WIDE_WORD).toBe('sr-only @min-[920px]/studio-header:not-sr-only'); for (const link of links.slice(0, 4)) { const name = link.querySelector('span') as HTMLElement; - expect(name).toHaveClass('sr-only', 'lg:not-sr-only'); - expect(name).not.toHaveClass('xl:not-sr-only'); + expect(name).toHaveClass(...STUDIO_HEADER_PILLAR_NAME.split(' ')); + expect(name).not.toHaveClass('lg:not-sr-only', 'xl:not-sr-only'); } - // The area is named from 1280 px: the 1024 px row holds the four names. const area = links[4].querySelector('span') as HTMLElement; - expect(area).toHaveClass('sr-only', 'xl:not-sr-only'); - expect(area).not.toHaveClass('lg:not-sr-only'); + expect(area).toHaveClass(...STUDIO_HEADER_WIDE_WORD.split(' ')); + expect(area).not.toHaveClass('lg:not-sr-only', 'xl:not-sr-only'); }); }); @@ -345,9 +377,9 @@ describe('Studio right slot — controls (objectui#12725)', () => { window.sessionStorage.setItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY, '0'); renderAt('data'); - await screen.findByTestId('studio-slot-toggle'); + await screen.findByTestId('topbar-ai-assistant'); expect(slot()).not.toBeVisible(); - expect(screen.getByTestId('studio-slot-toggle')).toHaveAttribute('aria-pressed', 'false'); + expect(screen.getByTestId('topbar-ai-assistant')).toHaveAttribute('aria-pressed', 'false'); }); // objectui#12725 phase 2 — Data and Automations now claim the slot, so the @@ -371,6 +403,9 @@ describe('Studio right slot — controls (objectui#12725)', () => { await waitFor(() => expect(slot()).toHaveAttribute('data-mode', 'props')); expect(within(slot()).queryAllByRole('tab')).toHaveLength(0); expect(screen.queryByTestId('studio-slot-copilot-strip')).toBeNull(); + // objectstack#34725 — no assistant, no robot: the panel icon stays. + expect(screen.getByTestId('studio-slot-toggle')).toHaveAccessibleName(t('engine.studio.slot.collapse', 'en')); + expect(screen.queryByTestId('topbar-ai-assistant')).toBeNull(); expect(screen.queryByTestId('if-canvas-hint')).toBeNull(); cleanup(); @@ -379,6 +414,7 @@ describe('Studio right slot — controls (objectui#12725)', () => { await act(async () => {}); expect(slot()).not.toBeVisible(); expect(screen.queryByTestId('studio-slot-toggle')).toBeNull(); + expect(screen.queryByTestId('topbar-ai-assistant')).toBeNull(); }); it('an injected aiSlot keeps the classic layout: no slot, and the properties beside the canvas', async () => { @@ -387,6 +423,7 @@ describe('Studio right slot — controls (objectui#12725)', () => { await screen.findByTestId('pick-block', undefined, { timeout: 4000 }); expect(screen.queryByTestId('studio-right-slot')).toBeNull(); expect(screen.queryByTestId('studio-slot-toggle')).toBeNull(); + expect(screen.queryByTestId('topbar-ai-assistant')).toBeNull(); expect(screen.getByTestId('if-inspector')).toBeVisible(); expect(screen.getByTestId('if-properties-toggle')).toBeInTheDocument(); expect(screen.getByTestId('if-canvas-main')).toHaveClass('px-6'); 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 1725066a975..dbae4173e7c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -37,6 +37,8 @@ import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; import { customizationNamespace } from '@objectstack/spec/kernel'; import { StudioChatDock, type StudioCopilotStatus, type StudioSurfaceLabel } from './StudioAiCopilot.js'; import { StudioRightSlot } from './StudioRightSlot.js'; +import { AssistantTopBarButton } from '../../layout/AssistantTopBarButton.js'; +import { ChatDockControlProvider, type ChatDockControl } from '../../layout/chatDockControl.js'; import { StudioRightSlotContext, isSlotEscapeExempt, @@ -58,12 +60,14 @@ import { STUDIO_HEADER, STUDIO_HEADER_ICON_BUTTON, STUDIO_HEADER_PACKAGE_COLUMN, + STUDIO_HEADER_PILLAR_NAME, + STUDIO_HEADER_WIDE_WORD, STUDIO_HEADER_PILLAR, STUDIO_HEADER_PILLAR_NAV, STUDIO_KIND_CHIP, } from './studio-tokens.js'; import { StudioInspector } from './StudioInspector.js'; -import { agentDraftMarkOf, DraftChip, DraftSourceLine } from './StudioDraftMark.js'; +import { agentDraftMarkOf, DraftChip, DraftSourceLine, isAgentDraftSurface } from './StudioDraftMark.js'; import { StudioItemHeader, StudioItemHeaderFoldedItems, @@ -217,6 +221,7 @@ import { FileQuestion, PackageX, Library, + Sparkles, type LucideIcon, } from 'lucide-react'; import { @@ -1477,6 +1482,8 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // objectstack#34610 — the copilot's expand control widens the slot in place // (it used to navigate to `/ai/build`, losing this page). const [copilotWide, setCopilotWide] = React.useState(false); + // objectstack#34725 — the copilot's history list, behind the slot header's History button. + const [copilotHistoryOpen, setCopilotHistoryOpen] = React.useState(false); const slotHasProps = slotPropsClaims > 0; const copilotAvailable = copilotStatus.available; // What the slot SHOWS: a missing half never shows. @@ -1521,6 +1528,21 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re document.addEventListener('keydown', onKey); return () => document.removeEventListener('keydown', onKey); }, [slotHost, slotOpen, setSlotOpen, slotHasProps, copilotAvailable, shownSlotMode]); + // objectstack#34725 — the top-bar robot's handle on the slot: pressed while + // the slot shows; a press hides it, or shows it on the AI assistant. + const openSlotOnCopilot = React.useCallback(() => { + setSlotMode('copilot'); + setSlotOpen(true); + }, [setSlotOpen]); + const slotRobotControl = React.useMemo( + () => ({ + expanded: slotOpen, + fullWindow: copilotWide, + toggle: () => (slotOpen ? setSlotOpen(false) : openSlotOnCopilot()), + open: openSlotOnCopilot, + }), + [slotOpen, copilotWide, setSlotOpen, openSlotOnCopilot], + ); /** * Host side of the live `?surface=` channel. Producers below the provider — @@ -1664,8 +1686,10 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re pillars read as icons, the name kept in the accessible name and the tooltip. objectstack#28561 — the "All metadata" area is named from 1280 px: the top bar's - 1024 px row was sized for the four pillar names. */} - + 1024 px row was sized for the four pillar names. + objectstack#34725 — both now answer the bar's own width + (see STUDIO_HEADER_PILLAR_NAME). */} + {t(`engine.studio.pillar.${p.key}`, locale)} @@ -1708,7 +1732,7 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re className="inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-50" > - {t('engine.studio.app.create', locale)} + {t('engine.studio.app.create', locale)} )} {/* objectui#12459 — the pending count is a pill, not "· N" text. */} @@ -1771,8 +1795,20 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re )} )} {/* objectui#12725 — the top bar's right-most icon shows or hides - the right slot; `⌘.` switches what it shows. */} - {slotHost && slotHasContent && ( + the right slot; `⌘.` switches what it shows. + objectstack#34725 — with a copilot served, that icon is the + console top bar's robot (the same component, in the same + place), and it opens the slot on the AI assistant. Without + one, the panel icon stays for the properties. */} + {slotHost && slotHasContent && copilotAvailable && ( + <> +
)} + {/* objectstack#34725 — the AI assistant's drafts are on this + canvas: say how many, where to review them, and the one undo + there is (the package's discard). */} + {agentDraftCount > 0 && ( +
+ + + + {!readOnly && adapter && ( + + )} + {onReviewChanges && ( + + )} + +
+ )} {!objLoaded ? ( // objectui#11272 — no view of another object's buffer under // this one; after a failed load, the error above says why. @@ -7474,6 +7651,8 @@ export function DataPillar({ } }, editColumnLabel: t('engine.studio.data.editFieldProps', locale), + // objectstack#34725 — the AI assistant's draft marks on the column headers. + ...(agentColumnMarks ? { columnMarks: agentColumnMarks } : {}), }} > {/* Provide the adapter as the dataSource context so the object-grid's @@ -7544,6 +7723,7 @@ export function DataPillar({ readOnly={formViewLayout ? formViewReadOnly || !formView.sections : readOnly} modeControl={formToolbarLeading} contributedFields={contributedFields} + draftMarkedFields={agentMarkedFields} formView={formViewLayout} /> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDraftMark.test.ts b/ui/packages/app-shell/src/views/studio-design/StudioDraftMark.test.ts index 6a3bfd02866..7742b2a4202 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDraftMark.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/StudioDraftMark.test.ts @@ -68,20 +68,20 @@ describe('addedArrayElements — the draft array against the published one (obje describe('draftSourceText — the source sentence (objectui#12725)', () => { it('reads the ruled zh copy, N minutes from `at`', () => { - expect(draftSourceText(copilot(ago(2)), 'zh-CN', [], NOW)).toBe('由 AI 副驾在 2 分钟前作为草稿加入'); - expect(draftSourceText(copilot(ago(2)), 'zh-CN', ['读者', '应还日期'], NOW)).toBe('「读者」「应还日期」 2 项由 AI 副驾在 2 分钟前作为草稿加入'); + expect(draftSourceText(copilot(ago(2)), 'zh-CN', [], NOW)).toBe('由 AI 助手在 2 分钟前作为草稿加入'); + expect(draftSourceText(copilot(ago(2)), 'zh-CN', ['读者', '应还日期'], NOW)).toBe('「读者」「应还日期」 2 项由 AI 助手在 2 分钟前作为草稿加入'); }); it('reads the en copy, and moves to hours and days past an hour', () => { - expect(draftSourceText(copilot(ago(2)), 'en-US', [], NOW)).toBe('Added as a draft by the AI copilot 2 min ago'); - expect(draftSourceText(copilot(ago(125)), 'en-US', [], NOW)).toBe('Added as a draft by the AI copilot 2 h ago'); - expect(draftSourceText(copilot(ago(3 * 1440)), 'zh-CN', [], NOW)).toBe('由 AI 副驾在 3 天前作为草稿加入'); - expect(draftSourceText(copilot(ago(2)), 'en-US', ['Reader', 'Due date'], NOW)).toBe('"Reader", "Due date": 2 added as a draft by the AI copilot 2 min ago'); + expect(draftSourceText(copilot(ago(2)), 'en-US', [], NOW)).toBe('Added as a draft by the AI assistant 2 min ago'); + expect(draftSourceText(copilot(ago(125)), 'en-US', [], NOW)).toBe('Added as a draft by the AI assistant 2 h ago'); + expect(draftSourceText(copilot(ago(3 * 1440)), 'zh-CN', [], NOW)).toBe('由 AI 助手在 3 天前作为草稿加入'); + expect(draftSourceText(copilot(ago(2)), 'en-US', ['Reader', 'Due date'], NOW)).toBe('"Reader", "Due date": 2 added as a draft by the AI assistant 2 min ago'); }); it('under a minute reads "just now", never "0 minutes ago"', () => { - expect(draftSourceText(copilot(ago(0)), 'zh-CN', [], NOW)).toBe('由 AI 副驾刚刚作为草稿加入'); - expect(draftSourceText(copilot(ago(0)), 'en-US', [], NOW)).toBe('Added as a draft by the AI copilot just now'); + expect(draftSourceText(copilot(ago(0)), 'zh-CN', [], NOW)).toBe('由 AI 助手刚刚作为草稿加入'); + expect(draftSourceText(copilot(ago(0)), 'en-US', [], NOW)).toBe('Added as a draft by the AI assistant just now'); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx b/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx index a69c40978e1..7dd142d8783 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx @@ -6,9 +6,13 @@ * open item's properties OR the AI copilot, never both, and never beside a * second right-hand panel. * - * - A segmented header 属性 | AI 副驾 switches the two; `⌘.` / `Ctrl+.` does - * the same (`matchStudioSlotShortcut`); the top bar's right-most icon - * hides the whole slot. + * - objectstack#34725 — ONE header row, the console drawer's: on the left a + * segmented 属性 | AI 助手 switch (`⌘.` / `Ctrl+.` does the same, + * `matchStudioSlotShortcut`); on the right, while the copilot shows, + * History, the in-place widen (objectstack#34610) and Close. The top bar's + * robot opens and closes the slot as the console's robot opens its drawer. + * - Its width is the console drawer's default, resizable from the left edge + * (`useStudioSlotWidth`); under `md` it overlays the page. * - Properties are a portal target: a pillar that hosts its inspector here * claims the slot through `useStudioRightSlot` (`studioRightSlotState.ts`) * and renders into @@ -29,10 +33,11 @@ */ import * as React from 'react'; -import { ArrowRight, SlidersHorizontal, Sparkles } from 'lucide-react'; -import { cn } from '@object-ui/components'; +import { ArrowRight, History, Maximize2, Minimize2, SlidersHorizontal, Sparkles, X } from 'lucide-react'; +import { Button, cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; import { t, tFormat } from '../metadata-admin/i18n.js'; -import { STUDIO_SLOT_WIDTH, type StudioSlotMode } from './studioRightSlotState.js'; +import { useStudioSlotWidth, type StudioSlotMode } from './studioRightSlotState.js'; export interface StudioRightSlotProps { /** Whether the slot is shown (the top bar's toggle). */ @@ -55,6 +60,18 @@ export interface StudioRightSlotProps { propsTargetRef: (el: HTMLElement | null) => void; /** A width in px while the copilot is widened in place (objectstack#34610); `undefined` otherwise. */ wideWidth?: number; + /** + * objectstack#34610 / objectstack#34725 — whether the copilot is widened in + * place, and the header control that widens and narrows it (absent: no + * control). Drawn while the copilot shows, never in the phone overlay. + */ + wide?: boolean; + onWideChange?: (wide: boolean) => void; + /** objectstack#34725 — the copilot's conversation history is open over it; the header's History button toggles it. */ + historyOpen?: boolean; + onHistoryOpenChange?: (open: boolean) => void; + /** objectstack#34725 — the header's Close: hides the slot, as the top bar's robot does. */ + onClose?: () => void; /** Under `md`: the slot overlays the page instead of reflowing it. */ overlay?: boolean; onOverlayDismiss?: () => void; @@ -71,10 +88,17 @@ export function StudioRightSlot({ copilot, propsTargetRef, wideWidth, + wide = false, + onWideChange, + historyOpen = false, + onHistoryOpenChange, + onClose, overlay = false, onOverlayDismiss, locale, }: StudioRightSlotProps): React.ReactElement { + const { t: tc } = useObjectTranslation(); + const slotWidth = useStudioSlotWidth(); const shown = open && (hasProps || copilotAvailable); const showsProps = mode === 'props'; const switchable = hasProps && copilotAvailable; @@ -92,9 +116,16 @@ export function StudioRightSlot({ {planPendingCount} ) : null; + const copilotShown = !showsProps && copilotAvailable; + const widened = Boolean(wideWidth) && !showsProps; + const wideLabel = wide + ? tc('console.ai.dock.restore', { defaultValue: 'Restore side panel' }) + : tc('console.ai.dock.expand', { defaultValue: 'Expand' }); + const historyLabel = t('engine.studio.slot.history', locale); + const headerButton = 'h-7 w-7 text-muted-foreground hover:text-foreground'; const segment = (value: StudioSlotMode) => cn( - 'inline-flex h-7 flex-1 items-center justify-center gap-1.5 rounded-md text-[13px] transition-colors', + 'inline-flex h-7 items-center justify-center gap-1.5 rounded-md px-3 text-[13px] transition-colors', mode === value ? 'bg-background font-medium text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground', ); return ( @@ -107,20 +138,37 @@ export function StudioRightSlot({ data-mode={mode} aria-label={t('engine.studio.slot.label', locale)} hidden={!shown} - style={wideWidth && !showsProps ? { width: wideWidth } : undefined} + style={overlay ? undefined : { width: widened ? wideWidth : slotWidth.width }} className={cn( - 'shrink-0 flex-col overflow-hidden border-l bg-background [&:not([hidden])]:flex', - overlay ? 'fixed inset-y-0 right-0 z-40 w-[min(360px,100vw)] shadow-xl' : STUDIO_SLOT_WIDTH, - !overlay && 'transition-[width] duration-200 ease-out', + 'relative shrink-0 flex-col overflow-hidden border-l bg-background [&:not([hidden])]:flex', + overlay && 'fixed inset-y-0 right-0 z-40 w-[min(420px,100vw)] shadow-xl', + !overlay && !slotWidth.dragging && 'transition-[width] duration-200 ease-out', )} > -
+ {/* objectstack#34725 — the left-edge resize handle, the console drawer's. */} + {overlay || widened ? null : ( +
+ )} +
{switchable ? (
) : ( - + {showsProps ? ( )} + + {copilotShown && onHistoryOpenChange ? ( + + ) : null} + {copilotShown && onWideChange && !overlay ? ( + + ) : null} + {onClose ? ( + + ) : null} +
({ ChatPane: () => null, resolveApiBase: () => '/api/v1', })); +// Every option object the copilot hands the conversation hook, in order. +const conversationArgs = vi.hoisted(() => [] as Array>); vi.mock('../../../hooks/useChatConversation', () => ({ - useChatConversation: () => ({ conversationId: 'c1', initialMessages: [] }), + useChatConversation: (args: Record) => { + conversationArgs.push(args); + return { conversationId: (args.activeId as string | undefined) ?? 'c1', initialMessages: [] }; + }, +})); +// The list reads the network; a stub stands for its two callbacks. +const sidebarProps = vi.hoisted(() => ({ last: null as null | Record })); +vi.mock('../../../console/ai/ConversationsSidebar', () => ({ + ConversationsSidebar: (props: { + activeConversationId?: string; + onSelectConversation?: (c: { id: string }) => void; + onNewConversation?: () => void; + }) => { + sidebarProps.last = props as Record; + return ( +
+
+ ); + }, })); import { StudioChatDock, type StudioCopilotStatus } from '../StudioAiCopilot'; beforeEach(() => { dockOptions.length = 0; + conversationArgs.length = 0; + sidebarProps.last = null; catalog.agents = [{ name: 'build' }]; window.sessionStorage.clear(); window.localStorage.clear(); @@ -95,7 +123,9 @@ describe('StudioChatDock as the right slot\'s copilot (#2477 item 2, objectui#12 const reports: StudioCopilotStatus[] = []; const { unmount } = mountCopilot((s) => reports.push(s)); expect(reports.at(-1)).toEqual({ available: true, planPendingCount: 0 }); - expect(screen.getByTestId('studio-copilot-maximize')).toBeInTheDocument(); + // objectstack#34725 — the widen control is the slot header's, not the copilot's. + expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); + expect(screen.queryByTestId('studio-copilot-history')).toBeNull(); unmount(); expect(reports.at(-1)).toEqual({ available: false, planPendingCount: 0 }); }); @@ -108,3 +138,42 @@ describe('StudioChatDock as the right slot\'s copilot (#2477 item 2, objectui#12 expect(reports.at(-1)).toEqual({ available: false, planPendingCount: 0 }); }); }); + +describe('StudioChatDock history (objectstack#34725)', () => { + function mountWithHistory(onHistoryOpenChange = vi.fn(), historyOpen = true) { + const view = render( + + + , + ); + return { ...view, onHistoryOpenChange }; + } + + it('lays the list, Share and the usage reading over the chat while open', () => { + mountWithHistory(); + const history = screen.getByTestId('studio-copilot-history'); + expect(history).toContainElement(screen.getByTestId('stub-history-list')); + expect(screen.getByTestId('studio-copilot-share')).toBeEnabled(); + expect(screen.getByTestId('stub-history-list')).toHaveAttribute('data-active', 'c1'); + }); + + it('picking a row opens that conversation and closes the list', () => { + const { onHistoryOpenChange } = mountWithHistory(); + fireEvent.click(screen.getByTestId('stub-pick-c2')); + expect(onHistoryOpenChange).toHaveBeenLastCalledWith(false); + expect(conversationArgs.at(-1)).toMatchObject({ activeId: 'c2', forceNew: false }); + }); + + it('New chat asks for a fresh conversation and closes the list', () => { + const { onHistoryOpenChange } = mountWithHistory(); + fireEvent.click(screen.getByTestId('stub-new')); + expect(onHistoryOpenChange).toHaveBeenLastCalledWith(false); + expect(conversationArgs.at(-1)).toMatchObject({ forceNew: true }); + }); + + it('closed, the chat is all there is', () => { + mountWithHistory(vi.fn(), false); + expect(screen.queryByTestId('studio-copilot-history')).toBeNull(); + expect(screen.queryByTestId('studio-copilot-share')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx index 458c0afa79b..44ac4680e7b 100644 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx @@ -4,7 +4,8 @@ * * objectstack#34610 (ui ADR-0057 Amendment A3) — the Studio copilot's expand * control widens its slot IN PLACE and the same control narrows it again; the - * Studio page stays where it is. + * Studio page stays where it is. objectstack#34725 moved the control into the + * slot's one header row, so the pin mounts the slot around the copilot. * * It used to open `/ai/build?package=PKG` (objectui#12842). After * objectstack#34608 that address opens the console's drawer full window over @@ -37,6 +38,7 @@ vi.mock('../../../hooks/useChatConversation', () => ({ })); import { StudioChatDock } from '../StudioAiCopilot'; +import { StudioRightSlot } from '../StudioRightSlot'; function Where() { const location = useLocation(); @@ -48,7 +50,20 @@ function Slot() { return ( <>
{String(wide)}
- + {}} + hasProps={false} + copilotAvailable + planPendingCount={0} + propsTargetRef={() => {}} + wideWidth={wide ? 900 : undefined} + wide={wide} + onWideChange={setWide} + locale="en" + copilot={} + /> ); @@ -72,6 +87,7 @@ describe("the Studio copilot's expand control (objectstack#34610)", () => { expect(button).toHaveAttribute('aria-pressed', 'false'); fireEvent.click(button); expect(screen.getByTestId('slot-wide')).toHaveTextContent('true'); + expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '900px' }); expect(screen.getByTestId('studio-copilot-maximize')).toHaveAttribute('aria-pressed', 'true'); expect(screen.getByTestId('where')).toHaveTextContent('/studio/app.crm/interfaces?surface=nav_dash'); expect(screen.queryByTestId('left-studio')).not.toBeInTheDocument(); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx index 60ab69278ce..8c5ddd1835c 100644 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx @@ -3,7 +3,7 @@ * Copyright (c) 2024-present ObjectStack Inc. * * objectui#12725 — the right slot's own rules, without mounting the surface: - * its width (300 px, 360 px from 1280), its `⌘.` chord, which Escape keydowns + * its width (objectstack#34725: the console drawer's 420 px, resizable), its `⌘.` chord, which Escape keydowns * are not the canvas's, and the chrome's three shapes (a switch when both * halves exist, a title when one does, nothing when none does). The surface's * wiring is pinned in `StudioDesignSurface.rightSlot-12725.test.tsx`. @@ -13,14 +13,18 @@ import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { StudioRightSlot } from '../StudioRightSlot'; -import { STUDIO_SLOT_WIDTH, isSlotEscapeExempt, matchStudioSlotShortcut } from '../studioRightSlotState'; +import { STUDIO_SLOT_WIDTH_STORAGE_KEY, isSlotEscapeExempt, matchStudioSlotShortcut } from '../studioRightSlotState'; +import { DOCK_DEFAULT_WIDTH, DOCK_KEYBOARD_STEP, DOCK_WIDTH_STORAGE_KEY } from '../../../layout/chatDockState'; import { t } from '../../metadata-admin/i18n'; import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; // The zh studio catalogue loads on demand; the zh case below reads it. await loadStudioCatalogue('zh'); -afterEach(cleanup); +afterEach(() => { + cleanup(); + window.localStorage.clear(); +}); const key = { key: '.', metaKey: false, ctrlKey: false, shiftKey: false, altKey: false }; @@ -72,10 +76,33 @@ function renderSlot(props: Partial> } describe('StudioRightSlot', () => { - it('is 300 px wide, 360 px from 1280', () => { - expect(STUDIO_SLOT_WIDTH).toBe('w-[300px] xl:w-[360px]'); + // objectstack#34725 — the console drawer's default width, dragged or keyed + // wider from its left edge, remembered under the slot's own key. + it('is 420 px wide by default and resizes from its left edge, under its own key', () => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); const { slot } = renderSlot(); - expect(slot).toHaveClass('w-[300px]', 'xl:w-[360px]'); + expect(DOCK_DEFAULT_WIDTH).toBe(420); + expect(slot).toHaveStyle({ width: '420px' }); + const handle = screen.getByTestId('studio-slot-resize'); + expect(handle).toHaveAttribute('role', 'separator'); + fireEvent.keyDown(handle, { key: 'ArrowLeft' }); + expect(slot).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP}px` }); + expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEY)).toBe(String(420 + DOCK_KEYBOARD_STEP)); + expect(window.localStorage.getItem(DOCK_WIDTH_STORAGE_KEY)).toBeNull(); + fireEvent.pointerDown(handle, { clientX: 1000 }); + fireEvent.pointerMove(window, { clientX: 900 }); + fireEvent.pointerUp(window, { clientX: 900 }); + expect(slot).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP + 100}px` }); + cleanup(); + + // Read back on the next mount; never so wide the canvas drops under 520 px. + renderSlot(); + expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP + 100}px` }); + cleanup(); + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1163 }); + window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEY, '2000'); + renderSlot(); + expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: `${1163 - 520}px` }); }); it('switches with its segmented header when both halves exist', () => { @@ -120,20 +147,73 @@ describe('StudioRightSlot', () => { it('on a phone it overlays the page, and a tap beside it dismisses it', () => { const onOverlayDismiss = vi.fn(); const { slot } = renderSlot({ overlay: true, onOverlayDismiss }); - expect(slot).toHaveClass('fixed'); - expect(slot).not.toHaveClass('w-[300px]'); + expect(slot).toHaveClass('fixed', 'w-[min(420px,100vw)]'); + expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); fireEvent.click(slot.previousElementSibling as HTMLElement); expect(onOverlayDismiss).toHaveBeenCalledTimes(1); }); - // objectstack#25943 — the StudioRailProps strip, 「AI 副驾 · N 项待确认 · 回到对话 →」. - it('zh: the folded strip reads 「AI 副驾 · 3 项待确认」 and the copilot tab carries the 3', () => { + // objectstack#25943 — the StudioRailProps strip, 「AI 助手 · N 项待确认 · 回到对话 →」 + // (objectstack#34725 named the panel 「AI 助手」, as the console names it). + it('zh: the folded strip reads 「AI 助手 · 3 项待确认」 and the copilot tab carries the 3', () => { renderSlot({ mode: 'props', planPendingCount: 3, locale: 'zh-CN' }); const strip = screen.getByTestId('studio-slot-copilot-strip'); - expect(strip).toHaveTextContent('AI 副驾 · 3 项待确认'); + expect(strip).toHaveTextContent('AI 助手 · 3 项待确认'); expect(strip).toHaveTextContent(t('engine.studio.slot.backToChat', 'zh-CN')); const copilotTab = screen.getAllByRole('tab')[1]; expect(within(copilotTab).getByTestId('studio-slot-plan-pending')).toHaveTextContent('3'); expect(copilotTab).toHaveAccessibleDescription('3 项待确认'); }); }); + +// objectstack#34725 — one header row, the console drawer's: the switch on the +// left; History, widen and Close on the right while the AI assistant shows. +describe('StudioRightSlot header (objectstack#34725)', () => { + it('zh: one row — 属性 | AI 助手, then 历史, widen and close', () => { + const onHistoryOpenChange = vi.fn(); + const onWideChange = vi.fn(); + const onClose = vi.fn(); + renderSlot({ locale: 'zh-CN', onHistoryOpenChange, onWideChange, onClose }); + const header = screen.getByTestId('studio-slot-header'); + const [props, chat] = within(header).getAllByRole('tab'); + expect(props).toHaveTextContent('属性'); + expect(chat).toHaveTextContent('AI 助手'); + const history = within(header).getByTestId('studio-slot-history'); + expect(history).toHaveTextContent('历史'); + expect(history).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(history); + expect(onHistoryOpenChange).toHaveBeenLastCalledWith(true); + fireEvent.click(within(header).getByTestId('studio-copilot-maximize')); + expect(onWideChange).toHaveBeenLastCalledWith(true); + const close = within(header).getByTestId('studio-slot-close'); + expect(close).toHaveAccessibleName(t('engine.studio.slot.collapse', 'zh-CN')); + fireEvent.click(close); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('an open history reads as pressed and leads back to the chat', () => { + renderSlot({ historyOpen: true, onHistoryOpenChange: vi.fn() }); + const history = screen.getByTestId('studio-slot-history'); + expect(history).toHaveAttribute('aria-pressed', 'true'); + expect(history).toHaveAccessibleName(t('engine.studio.slot.backToChat', 'en')); + }); + + it('while the properties show, only Close; on a phone, no widen', () => { + renderSlot({ mode: 'props', onHistoryOpenChange: vi.fn(), onWideChange: vi.fn(), onClose: vi.fn() }); + expect(screen.queryByTestId('studio-slot-history')).toBeNull(); + expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); + expect(screen.getByTestId('studio-slot-close')).toBeInTheDocument(); + cleanup(); + + renderSlot({ overlay: true, onHistoryOpenChange: vi.fn(), onWideChange: vi.fn() }); + expect(screen.getByTestId('studio-slot-history')).toBeInTheDocument(); + expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); + }); + + it('widened, it takes the wide width and drops the resize handle', () => { + const { slot } = renderSlot({ wide: true, wideWidth: 900, onWideChange: vi.fn() }); + expect(slot).toHaveStyle({ width: '900px' }); + expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); + expect(screen.getByTestId('studio-copilot-maximize')).toHaveAttribute('aria-pressed', 'true'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/studio-tokens.ts b/ui/packages/app-shell/src/views/studio-design/studio-tokens.ts index d6e0ba88979..bd34b884b64 100644 --- a/ui/packages/app-shell/src/views/studio-design/studio-tokens.ts +++ b/ui/packages/app-shell/src/views/studio-design/studio-tokens.ts @@ -21,7 +21,7 @@ * the switcher at full width on the second (`STUDIO_HEADER_PILLAR_NAV`). */ export const STUDIO_HEADER = - 'grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 border-b px-3 py-2 sm:h-12 sm:grid-cols-[minmax(0,1fr)_auto_minmax(max-content,1fr)] sm:py-0'; + '@container/studio-header grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 border-b px-3 py-2 sm:h-12 sm:grid-cols-[minmax(0,1fr)_auto_minmax(max-content,1fr)] sm:py-0'; /** The pillar switcher: its own full-width row below `sm`, the middle column from `sm` up. */ export const STUDIO_HEADER_PILLAR_NAV = 'order-last col-span-2 flex items-center gap-0.5 rounded-lg bg-muted p-[3px] sm:order-none sm:col-span-1'; @@ -40,6 +40,21 @@ export const STUDIO_HEADER_PILLAR = * tooltip. Literal class strings: Tailwind finds a class by scanning source. */ export const STUDIO_HEADER_PACKAGE_COLUMN = '@container'; + +/** + * objectstack#34725 — the pillar names, and the words of "All metadata" and + * Create app, answer the top bar's OWN width, not the viewport's: the right + * panel beside it is resizable now (the console drawer's 420 px, dragged up to + * the canvas's 520 px floor), so a 1163 px window can leave the bar 520 px. A + * viewport breakpoint kept the names on and pushed the bar's right end, the AI + * assistant's robot, under the panel. The thresholds are the bar widths the + * old breakpoints gave beside the old fixed slot: 724 px (1024 − 300) for the + * four pillar names, 920 px (1280 − 360) for the two longer words. Below them + * the names stay in the accessible name and the tooltip. Literal class + * strings: Tailwind finds a class by scanning source. + */ +export const STUDIO_HEADER_PILLAR_NAME = 'sr-only @min-[724px]/studio-header:not-sr-only'; +export const STUDIO_HEADER_WIDE_WORD = 'sr-only @min-[920px]/studio-header:not-sr-only'; export const STUDIO_PKG_READONLY_WORD = 'hidden @min-[300px]:inline'; /** Rail: 240 px, the sidebar surface, a right border. */ diff --git a/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts b/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts index dc040b7a8c2..a835d11d6fd 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts @@ -2,22 +2,93 @@ /** * The Studio right slot's shared state (objectui#12725): the handle a pillar - * reads to host its properties in the slot, and the slot's pure rules — its - * width, its `⌘.` chord, and which Escape keydowns are not the canvas's. The + * reads to host its properties in the slot, its resizable width, and the + * slot's pure rules — its `⌘.` chord, and which Escape keydowns are not the canvas's. The * chrome is `StudioRightSlot.tsx`; these live apart so that file exports * components only. */ import * as React from 'react'; +import { clampDockWidth, DOCK_DEFAULT_WIDTH, DOCK_KEYBOARD_STEP } from '../../layout/chatDockState.js'; export type StudioSlotMode = 'props' | 'copilot'; /** - * The slot's width: 300 px below 1280, 360 px from 1280 up (the card's 1010 and - * 1280 readings). Fixed — the slot is not resizable; the copilot's Live Canvas - * is the one thing that widens it (see `wideWidth`). + * objectstack#34725 — the slot's width: the console drawer's default (420 px, + * `DOCK_DEFAULT_WIDTH`), resizable from its left edge and remembered per + * browser under its own key, so a width dragged here never moves the console + * drawer's. The drag keeps the canvas at least `DOCK_CONTENT_MIN_WIDTH` wide + * (`clampDockWidth`); the widened copilot is the one other width (`wideWidth`). */ -export const STUDIO_SLOT_WIDTH = 'w-[300px] xl:w-[360px]'; +export const STUDIO_SLOT_WIDTH_STORAGE_KEY = 'studio-right-slot-width'; + +function readStoredSlotWidth(): number { + try { + const raw = window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEY); + const n = raw ? Number.parseInt(raw, 10) : NaN; + return Number.isFinite(n) && n > 0 ? n : DOCK_DEFAULT_WIDTH; + } catch { + return DOCK_DEFAULT_WIDTH; + } +} + +function writeStoredSlotWidth(width: number): void { + try { + window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEY, String(Math.round(width))); + } catch { + /* private mode: the width just is not remembered */ + } +} + +export interface StudioSlotWidth { + /** The width to draw, already clamped to the window. */ + width: number; + dragging: boolean; + /** Pointer-down on the left-edge handle: dragging left widens the slot. */ + onResizePointerDown: (e: React.PointerEvent) => void; + /** Arrow keys on the focused handle: Left widens, Right narrows. */ + onResizeKeyDown: (e: React.KeyboardEvent) => void; +} + +/** The slot's resizable width; see {@link STUDIO_SLOT_WIDTH_STORAGE_KEY}. */ +export function useStudioSlotWidth(): StudioSlotWidth { + const [stored, setStored] = React.useState(readStoredSlotWidth); + const [dragging, setDragging] = React.useState(false); + const onResizePointerDown = React.useCallback( + (e: React.PointerEvent) => { + e.preventDefault(); + const startX = e.clientX; + const startWidth = clampDockWidth(stored, window.innerWidth); + const widthAt = (x: number) => clampDockWidth(startWidth + (startX - x), window.innerWidth); + setDragging(true); + const onMove = (ev: PointerEvent) => setStored(widthAt(ev.clientX)); + const onUp = (ev: PointerEvent) => { + const final = widthAt(ev.clientX); + setStored(final); + writeStoredSlotWidth(final); + setDragging(false); + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + }; + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + }, + [stored], + ); + const onResizeKeyDown = React.useCallback( + (e: React.KeyboardEvent) => { + if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; + e.preventDefault(); + const step = e.key === 'ArrowLeft' ? DOCK_KEYBOARD_STEP : -DOCK_KEYBOARD_STEP; + const next = clampDockWidth(clampDockWidth(stored, window.innerWidth) + step, window.innerWidth); + setStored(next); + writeStoredSlotWidth(next); + }, + [stored], + ); + const width = typeof window === 'undefined' ? stored : clampDockWidth(stored, window.innerWidth); + return { width, dragging, onResizePointerDown, onResizeKeyDown }; +} export interface StudioRightSlotHandle { /** The element a pillar portals its properties into; `null` until mounted. */ diff --git a/ui/packages/components/src/context/gridFieldAuthoring.tsx b/ui/packages/components/src/context/gridFieldAuthoring.tsx index 9c25153c981..ea22259929a 100644 --- a/ui/packages/components/src/context/gridFieldAuthoring.tsx +++ b/ui/packages/components/src/context/gridFieldAuthoring.tsx @@ -41,6 +41,13 @@ export interface GridFieldAuthoring { * reordering to the table's own `reorderableColumns`/`onColumnsReorder`. */ onReorderFields?: (orderedFieldNames: string[]) => void; + /** + * A mark drawn after a column's header label, keyed by the column's + * accessorKey (= field name); a column with no entry draws none. The Studio + * Data pillar marks the fields its AI assistant changed in the pending draft + * (objectstack#34725). Omit for no marks. + */ + columnMarks?: Readonly>; } const GridFieldAuthoringContext = React.createContext(null); diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-columnMarks-34725.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-columnMarks-34725.test.tsx new file mode 100644 index 00000000000..2c396248336 --- /dev/null +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-columnMarks-34725.test.tsx @@ -0,0 +1,58 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34725 — `GridFieldAuthoring.columnMarks`: a host-drawn mark after + * a column's header label, keyed by accessorKey. The Studio Data pillar marks + * the fields its AI assistant changed in the pending draft. A column with no + * entry draws nothing, and a table outside the provider draws no marks at all. + */ +import { describe, it, expect } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { ComponentRegistry } from '@object-ui/core'; +import { GridFieldAuthoringProvider } from '../../../context/gridFieldAuthoring'; +import '../data-table'; + +function table() { + const DataTable = ComponentRegistry.get('data-table') as any; + return ( + + ); +} + +const header = (name: string) => screen.getByRole('columnheader', { name: new RegExp(name) }); + +describe('data-table draws GridFieldAuthoring.columnMarks after the header label (objectstack#34725)', () => { + it('a marked column draws its mark; an unmarked one draws none', () => { + render( + AI } }}> + {table()} + , + ); + expect(within(header('Renewals')).getByTestId('mark')).toHaveTextContent('AI'); + expect(within(header('Title')).queryByTestId('mark')).toBeNull(); + expect(screen.getAllByTestId('mark')).toHaveLength(1); + }); + + it('outside the provider, no marks', () => { + render(table()); + expect(screen.queryByTestId('mark')).toBeNull(); + }); +}); diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index f19704007c0..6b221190e36 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -3561,6 +3561,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { {/* The full label on hover wherever the cell is too narrow for it and the ellipsis cuts it (objectstack#29945). */} {col.header} + {fieldAuthoring?.columnMarks?.[col.accessorKey]} {isColumnSortable(col) && getSortIcon(col.accessorKey)} {editColumnEnabled && (