Skip to content

Commit e05445e

Browse files
feat(studio): the Studio AI panel matches the console's AI assistant (#34851)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB82ZDV2ys7SBHwCdUAguKiU)_ Fixes #34725 Child of epic #34571, the Studio half of #34608. Built on #34713 (merged 14619f5). ## 维护者速读 - 改了什么:Studio 右侧的 AI 面板与控制台的 AI 助手抽屉统一。名称统一为「AI 助手」。顶栏右端换成控制台同一个机器人按钮,只负责开关右栏,`⌘.` 保留。标题栏收成一行:属性 | AI 助手,加历史、铺满、关闭。用量和分享移进历史视图。默认宽 420,可拖动。上下文 chip 显示「正在看:任务 · 记录」。数据画布上,AI 改过的字段在表格列头和表单卡片上带草稿标记,画布上方有一行「AI 刚改了 N 处」,带「查看」和「放弃全部未发布改动」。 - 为什么改:#34725 的 8 项,对齐 #34608 / PR #34665 的控制台抽屉。第 4 项(原地铺满)和第 8 项(结果卡不带发布)已由 #34713 完成,这里没有重做。 - 风险与回滚:只改控制台前端(app-shell;components 一个可选成员;i18n studio 新键和几处文案值),不动元数据、契约和服务端。回滚即 revert。 - 偏差:第 7 项(验收 4)的「表格列头标记」只对已发布字段生效。AI 新加的字段是草稿,Studio 表格只选已发布字段(cloud#1652),发布前没有这一列,表单卡片和画布那一行照样标出。席位已认可。 - 先看:`StudioRightSlot.tsx`(单行标题栏、拖宽)、`StudioAiCopilot.tsx`(历史视图)、`StudioDesignSurface.tsx` 的顶栏机器人与 DataPillar 的草稿标记和那一行、`studio-tokens.ts`(顶栏按自身宽度显示支柱名)。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx packages/app-shell/src/views/studio-design/__tests__/studioCopilotSlotBody-12725.test.tsx packages/components/src/renderers/complex/__tests__/data-table-columnMarks-34725.test.tsx`,预期全部通过。 ## What changes **One name.** `engine.studio.aiCopilot` and `engine.studio.draftMark.agent.copilot` read "AI Assistant" / 「AI 助手」, so the panel, its tab, the folded strip and the draft-source sentence all use the console's name. The drafts panel's `preview.changes.draftedByCopilot` follows ("AI assistant") in every pack that said copilot. **The robot in the top bar** (`StudioDesignSurface.tsx`). With a copilot served, the top bar's right-most control is the console's `AssistantTopBarButton`, under a `ChatDockControlProvider` whose `toggle` shows or hides the right slot and always opens it on the AI assistant. `⌘.` still switches the halves. Without a copilot the panel icon (`studio-slot-toggle`) stays for the properties. **One header row** (`StudioRightSlot.tsx`). Left: the Properties | AI Assistant switch, or the title when only one half exists. Right, while the assistant shows: History, widen (the #34713 control, moved here) and Close. `ChatPane` gains an optional `hideHeader` so the copilot draws no second header. History lays the conversation list (`ConversationsSidebar` with the console drawer's callbacks), Share and the usage reading over the chat; the pane stays mounted underneath, so a streaming answer is never cut. Picking a row opens that conversation; New chat asks for a fresh one. **Width** (`studioRightSlotState.ts`). The slot opens at the console drawer's 420 px (`DOCK_DEFAULT_WIDTH`), resizes from its left edge by pointer or arrow keys, clamps with `clampDockWidth` (the canvas keeps 520 px), and remembers its width under its own key `studio-right-slot-width`, never the console's. Widened, it takes `wideWidth` and drops the handle. On a phone it stays the overlay. **The top bar keeps its right end on screen** (`studio-tokens.ts`). With a resizable slot, a 1163 px window can leave the top bar 520 px. The pillar names used the viewport's `lg`, so in en the bar overflowed and the robot sat under the slot (live reading below). The names, "All metadata" and Create app now answer a container query on the bar (`@container/studio-header`): 724 px and 920 px, the widths the old breakpoints gave beside the old fixed slot. **The context chip.** The Data pillar reports the open object's label and the view on screen (`Task · Records`, `Task · Form`), so the chip reads 「正在看:任务 · 记录」; `console.ai.discussing` reads Viewing / 正在看 in all 11 packs. The internal name stays on the chip's tooltip only where no label is known (objectui#7254). **Draft marks on the canvas** (`StudioDesignSurface.tsx` DataPillar, `ObjectFormDesigner.tsx`). From the open object's existing draft read (`draftChanges`, no new server read): - the Form canvas's card of each field an AI tool changed carries the 草稿 chip; - the records grid's column header does too, through a new optional `GridFieldAuthoring.columnMarks` that `data-table` draws after the header label; - a line over the canvas counts the AI entries (「AI 刚改了 N 处」, with a singular), with 查看 (opens the pending-changes sheet in review) and 放弃全部未发布改动 (confirm, then `packages.discardDrafts(packageId)`). A failed discard names each item as the rail does (the object's label, else its name, joined by a translated separator) and keeps the server's own words under the strip's Details. There is no per-turn undo. **i18n.** New studio-namespace keys only: `engine.studio.slot.history`, `engine.studio.slot.resize`, `engine.studio.copilotChanges.{lineOne,line,view,discardAll,discardConfirm,discardFailed,itemSeparator}`. Changed values: the two studio keys above, `console.ai.discussing` (11 packs, zh-Hant regenerated), `preview.changes.draftedByCopilot` (en and eight packs; ar already said مساعد الذكاء الاصطناعي and is waived in `ui/scripts/i18n-en-drift-baseline.json`, the ratchet `WAIVER_CEILING` 6 → 7 with its history line). Two inline `defaultValue`s now copy their en value. `engine.studio.slot.openFullPage` is no longer read; retiring it is a separate change. ## Why #34725 asks Studio's AI panel to be the console's AI assistant: one name, one entry, one width, one title bar (figure 20 on the card). #34608 / PR #34665 shipped the console drawer this matches; #34713 (ADR-0057 Amendment A3) made the widen control widen in place. ## Acceptance notes - Items 4 (widen in place and restore) and 8 (no Publish on result cards) were done by #34713; measured on its head and not redone. - Item 7 (acceptance 4), grid column marks: a field the assistant **adds** is a draft, and the Studio records grid selects published fields only (cloud#1652), so it has no column until published. Changed published fields are marked on their column; added fields are marked on their Form card and counted in the line. The seat accepted this deviation; no follow-up card. - The robot sits at the right end of Studio's top bar, the console's place for it. In Studio the slot runs the full height beside the bar, so the robot is left of the slot rather than at the window's edge. ## Verification - **Live readings**, 1163 × 820 window, zh-CN and en, the real console (Vite) over a fresh showcase backend, standing in only for `/api/v1/ai/**` (agents list with a build agent, in-memory conversations). Script, logs and shots: `/mnt/project-files/objectstack-seat3/34725-live/`. - Acceptance 1: the robot's accessible name, the panel title and tab read 「AI 助手」 / "AI Assistant". - Acceptance 2: `topbar-ai-assistant` is the top bar's last control, pressed while the slot shows; clicking it hides the slot, clicking again opens it on the assistant; no `studio-slot-toggle` remains. - Acceptance 3: the header is one 44 px row: 「AI 助手」, 历史, 展开, 收起右栏. History shows Share, New and the two stand-in conversations. - Acceptance 4 (#34713's): widen takes the slot to 643 px (canvas 520) with the URL unchanged; the same control restores. - Acceptance 5: the slot opens at 420 px; a 100 px drag makes it 520 px, stored, and kept after a reload. - Chip: 「正在看:任务 · 记录」 / "Viewing: Task · Records", then 「· 表单」 / "· Form" on the Form tab. - Found and fixed by the en reading: with the slot at 520 px the en top bar overflowed and the robot sat under the slot (a click on it was intercepted). After the container query: the header's `scrollWidth` equals its `clientWidth` at 643 px and 520 px in both languages, and the robot is clickable. - **Draft-mark readings (L1-b rework M1)**, head `c2034e76feb1bfa767fe16fe828bc45726271de7`, 1163 × 820, zh-CN and en, same rig, on an editable object: a writable package `com.qa.x` with object `x_ticket` (fields Title, Priority, Due on; one record so the grid draws its header), published, then a real draft staged over HTTP that relabels the published field `priority` to "Urgency". **Stand-in, stated plainly:** HTTP refuses `?surface=copilot` (`packages/rest/src/meta-save-request.ts`) and MCP has no metadata write, so the draft's ledger row says `by: "api"`; the page's draft read (`GET /api/v1/meta/object/x_ticket?state=draft…`) is relabelled `by: "copilot"` in flight. Nothing else of the read is touched, and the discard is the real `packages.discardDrafts`. Script `check2.mjs`, logs `*-m1-log.txt`, shots `*-m1-*.png` in the same folder. 1. The line reads 「AI 刚改了 1 处」 with 放弃全部未发布改动 and 查看 / "The AI assistant just made 1 change" with "Discard all unpublished changes" and "Review". 2. The records grid's Priority column header carries `studio-grid-column-draft-chip` (「草稿」 / "Draft", `data-draft-of="priority"`); the Form card "Urgency" carries `studio-form-field-draft-chip`. One chip each, on that field only. 3. 查看 opens the 待发布的变更 / "Pending changes" sheet in review posture: the one row (Ticket · x_ticket · 更新 / Update) folded, nothing publishes until 全部发布 / "Publish all". 4. 放弃全部未发布改动: the confirm reads 「放弃本包的全部未发布改动(包括你自己的)?此操作不可撤销。」 / "Discard every unpublished change in this package, yours included? This cannot be undone."; after OK the line is gone, grid column chips 1 → 0, form card chips 1 → 0, no refusal strip, and the server's draft read answers 404 `NO_DRAFT`. 5. Ask-data table at the 420 px default: the build agent's stand-in answer is a 3-column markdown table (Priority · Open tickets · Average age (days)). It renders 313 px wide inside its own `overflow-x: auto` box whose `clientWidth` equals `scrollWidth` (313 = 313), the slot spans 743–1163, and no cell is clipped. 6. With the field selected the header is one 44 px row: 属性 | AI 助手 tabs (Properties selected), and on the AI 助手 tab 历史 · 展开 · 收起右栏 / History · Expand · "Hide the right panel"; all five controls sit at y 8, 28 px high. - **i18n budget** (seat ruling 08:40Z): on the merged tree (main dfbc316, with #34713), a console build and `check-eager-closure-budget.mjs` read `i18n-locale-en` at **61,823 B gzip (60.4 KB of the 60.5 KB ceiling, headroom 177 B)**, exit 0; #34713's own reading was 61,824 B. New keys are in the studio namespace; the eager pack changed values only. The ceiling is untouched. - **S1 (L1-b rework):** `DataPillar.copilotChangesLine-34725` gains a failed-discard case: the sentence names `Task` (the rail label) and `showcase_task_grid` (no label known) with the separator, holds neither `E_LOCKED` nor `object/`, and the raw `object/showcase_task: E_LOCKED…` sits under Details. 6/6 pass. - **Tests:** after merging main, `views/studio-design`, `preview`, the chip pin, the column-marks pin and the drift-ledger test: 385 files, 2,997 tests, all green. - Re-pointed: the slot unit pins (420 px and resize instead of 300/360, the 「AI 助手」 strip, the overlay), the surface pins (`studio-slot-toggle` → the robot when a copilot is served; the panel icon without one), the slot-body pins (widen is the slot's now), the widen-in-place pin (mounts the slot around the copilot), the chip pins (正在看 and the object label), the pillar-name class pins. - New: the slot header (History, widen, Close, pressed states, phone), history (pick, New chat, Share), `DataPillar.copilotChangesLine-34725` (the line, singular, 查看, discard with and without confirm, the chip label, the person-written control), `ObjectFormDesigner.draftMarkedFields-34725`, `data-table-columnMarks-34725` (components), `ChatPane hideHeader`. - Five edited tests load `@objectstack/lint` at module top (`check:test-source-alias`). - **Type-check:** app-shell `tsc` and `tsc -p tsconfig.test.json`, components `tsc -p tsconfig.test.json`: exit 0. eslint on every changed file: 0 errors. - **i18n gates:** `check:i18n-keys`, `check:i18n-drift` exit 0; `check:i18n-dead-keys` reports nothing new. - **`dispatch-gates --ran`:** re-run in full on head `c2034e76` (after S1): 40 derived, 40 run, all exit 0, 0 not measured. On the previous head: 40 derived families ran on the final diff, 40 accounted for, 0 not measured. One first-run red, `check:test-source-alias` on the edited `narrowHeader-12509` pin, was answered with a module-top `import '@objectstack/lint'` and re-run exit 0. The other 39 exit 0. - **Overlap:** `scripts/pm/overlap-check.mjs` on `c2034e76`: merges cleanly with main (7752cac), #34677, #34799, #34825 and #34850. - **Merges:** #34713's head merged into the branch as it moved, then `origin/main` after #34713 landed (conflicts were only #34713's own lines, whose main version equals the head already merged). 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 ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The 维护者速读 block is the seat's maintainer summary.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzfd562n5Rccarjf31X <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfd562n5Rccarjf31X --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 583bbf3 commit e05445e

40 files changed

Lines changed: 1239 additions & 151 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/components': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
feat(studio): the Studio AI panel matches the console's AI assistant
8+
9+
Clause-②: yes (widening — new studio-namespace locale keys, and one optional `columnMarks` member on the published `GridFieldAuthoring` interface of @object-ui/components)
10+
Metadata-protocol: none
11+
12+
The AI panel on Studio's right side now looks and works like the console's AI assistant drawer.
13+
14+
- It is called "AI Assistant" (「AI 助手」) everywhere, including the line that says which tool drafted a change.
15+
- 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.
16+
- 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.
17+
- 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.
18+
- The chip above the composer reads "Viewing: <object label> · <view>" (「正在看:会议 · 记录」), never the internal name.
19+
- 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.
20+
21+
`@object-ui/components`: `GridFieldAuthoring` takes an optional `columnMarks`, a node per accessorKey that `data-table` draws after the column's header label.
22+
23+
`@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`.

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1783,6 +1783,14 @@ interface ChatPaneProps {
17831783
onDebug?: () => void;
17841784
/** Show the Build Doctor button — true only for build-agent conversations. */
17851785
showDebug?: boolean;
1786+
/**
1787+
* objectstack#34725 — the host draws the panel's one title bar itself (the
1788+
* Studio right slot: 属性 | AI 助手, History, widen, Close), so the pane
1789+
* omits its own header row: the agent switcher, the app chip, Share and the
1790+
* Build Doctor button. The host then offers Share where it chooses.
1791+
* @default false
1792+
*/
1793+
hideHeader?: boolean;
17861794
}
17871795

17881796
export function ChatPane({
@@ -1812,6 +1820,7 @@ export function ChatPane({
18121820
onShare,
18131821
onDebug,
18141822
showDebug,
1823+
hideHeader = false,
18151824
}: ChatPaneProps) {
18161825
const { t, language } = useObjectTranslation();
18171826
const navigate = useNavigate();
@@ -2989,7 +2998,7 @@ export function ChatPane({
29892998
packageRemovalPartialLabel={(failed) => t('console.ai.packageRemovalPartial', { count: failed })}
29902999
surface="plain"
29913000
maxHeight="100%"
2992-
headerSlot={headerSlot}
3001+
headerSlot={hideHeader ? undefined : headerSlot}
29933002
// objectui#12978 — the drafts line (`pendingDraftsBar` above) is a row
29943003
// of the composer's own area, in
29953004
// flow above the input. The bar used to float (`absolute bottom-20`)
@@ -3280,7 +3289,7 @@ export function ChatPane({
32803289
surfaceContextLabel={
32813290
surfaceContext?.artifact
32823291
? t('console.ai.discussing', {
3283-
defaultValue: 'Discussing: {{target}}',
3292+
defaultValue: 'Viewing: {{target}}',
32843293
target:
32853294
surfaceArtifactLabel ||
32863295
`${surfaceContext.artifact.type} · ${surfaceContext.artifact.name}`,

‎ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* objectui#7254's ruling: what is READ is the label; the internal identity
88
* stays REACHABLE on a tooltip. Before this, ChatPane built the chip from the
99
* `context.surface` artifact alone, so the chip printed
10-
* `Discussing: dashboard · customer_dashboard` at the reader.
10+
* `Viewing: dashboard · customer_dashboard` at the reader.
1111
*
1212
* The display label reaches ChatPane as its OWN optional prop
1313
* (`surfaceArtifactLabel`), never inside `surfaceContext` — that object is the
@@ -85,7 +85,7 @@ const SURFACE = {
8585
artifact: { type: 'dashboard', name: 'customer_dashboard' },
8686
};
8787

88-
function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typeof SURFACE }) {
88+
function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typeof SURFACE; hideHeader?: boolean }) {
8989
cleanup();
9090
captured = {};
9191
chatOptions = {};
@@ -110,6 +110,7 @@ function renderPane(extra: { surfaceArtifactLabel?: string; surfaceContext?: typ
110110
pendingFirstMessageRef={{ current: null }}
111111
onSent={vi.fn()}
112112
onShare={vi.fn()}
113+
hideHeader={extra.hideHeader}
113114
{...labelProp}
114115
/>
115116
</MemoryRouter>
@@ -124,13 +125,13 @@ afterEach(() => cleanup());
124125
describe('AI chat "discussing" chip — label read, internal id on the tooltip (objectui#8219)', () => {
125126
it('with a display label: the chip reads the label and its title is the type · name pair', () => {
126127
const { props } = renderPane({ surfaceContext: SURFACE, surfaceArtifactLabel: 'Customer dashboard' });
127-
expect(props.surfaceContextLabel).toBe('Discussing: Customer dashboard');
128+
expect(props.surfaceContextLabel).toBe('Viewing: Customer dashboard');
128129
expect(props.surfaceContextTitle).toBe('dashboard · customer_dashboard');
129130
});
130131

131132
it('with no display label: the chip falls back to the type · name pair, still reachable as its title', () => {
132133
const { props } = renderPane({ surfaceContext: SURFACE });
133-
expect(props.surfaceContextLabel).toBe('Discussing: dashboard · customer_dashboard');
134+
expect(props.surfaceContextLabel).toBe('Viewing: dashboard · customer_dashboard');
134135
expect(props.surfaceContextTitle).toBe('dashboard · customer_dashboard');
135136
});
136137

@@ -157,3 +158,12 @@ describe('AI chat "discussing" chip — label read, internal id on the tooltip (
157158
expect(JSON.stringify(bodyOf(withLabel))).not.toContain('Customer dashboard');
158159
});
159160
});
161+
162+
// objectstack#34725 — a host that draws its own title bar (the Studio slot's
163+
// one header row) asks the pane for none; every other host keeps the header.
164+
describe('ChatPane hideHeader (objectstack#34725)', () => {
165+
it('draws its header by default, and none when the host asks', () => {
166+
expect(renderPane({ surfaceContext: SURFACE }).props.headerSlot).toBeTruthy();
167+
expect(renderPane({ surfaceContext: SURFACE, hideHeader: true }).props.headerSlot).toBeUndefined();
168+
});
169+
});

‎ui/packages/app-shell/src/preview/DraftChangesPanel.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1266,7 +1266,7 @@ function EntryDetail({
12661266
data-testid="draft-entry-agent"
12671267
>
12681268
{source.by === 'copilot'
1269-
? t('preview.changes.draftedByCopilot', { defaultValue: 'Includes changes drafted by the AI copilot' })
1269+
? t('preview.changes.draftedByCopilot', { defaultValue: 'Includes changes drafted by the AI assistant' })
12701270
: source.client
12711271
? t('preview.changes.draftedByMcpClient', {
12721272
client: source.client,

‎ui/packages/app-shell/src/preview/__tests__/DraftChangesPanel.agentSource-27176.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
3030
}),
3131
}));
3232

33+
// The source loads `@objectstack/lint` lazily; paid here, at collection, not
34+
// inside a case's clock (check:test-source-alias).
35+
import '@objectstack/lint';
3336
import { DraftChangesPanel, draftAgentSources } from '../DraftChangesPanel';
3437

3538
const PKG = 'com.x';
@@ -78,7 +81,7 @@ describe('objectstack#27176 — the drill-in names the AI tools that drafted the
7881
await renderConfirm();
7982
expect(agentLines()).toEqual([
8083
'Includes changes drafted by the MCP client “Claude”',
81-
'Includes changes drafted by the AI copilot',
84+
'Includes changes drafted by the AI assistant',
8285
]);
8386
});
8487

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#34725 item 7 — the AI assistant's drafts on the Data canvas:
5+
* - a line over the canvas, 「AI 刚改了 N 处」, counting the pending draft's
6+
* `draftChanges` entries an AI tool wrote (copilot or MCP), with 查看 (the
7+
* pending-changes sheet) and 放弃全部未发布改动 (the package's discard door,
8+
* `packages.discardDrafts`, after a confirm) — the one undo there is;
9+
* - the Form canvas's card of each field the assistant changed carries the
10+
* 草稿 chip;
11+
* - item 6: the copilot's chip names the open object by its label and the view
12+
* on screen (`Task · Records`), never its internal name.
13+
* CONTROL: entries a person wrote in Studio, or no draft, draw no line.
14+
*
15+
* The records grid's column marks ride on `GridFieldAuthoring.columnMarks`,
16+
* pinned in `@object-ui/components` (`data-table-columnMarks-34725`): a
17+
* field the assistant added is a draft, and the grid selects published fields
18+
* only (cloud#1652), so a new field has no column until it is published.
19+
*/
20+
21+
import '@testing-library/jest-dom/vitest';
22+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
23+
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
24+
import { MemoryRouter } from 'react-router-dom';
25+
26+
const objectDef = {
27+
name: 'showcase_task',
28+
label: 'Task',
29+
fields: {
30+
priority: { name: 'priority', label: 'Priority', type: 'text' },
31+
renewal_count: { name: 'renewal_count', label: 'Renewals', type: 'number' },
32+
},
33+
};
34+
35+
const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toISOString();
36+
37+
/** What the next draft read serves: `null` for no draft. */
38+
let draftEnvelope: Record<string, unknown> | null = null;
39+
40+
const mockClient = {
41+
save: vi.fn(async () => ({})),
42+
list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'showcase_task', label: 'Task' }] : [])),
43+
listDrafts: vi.fn(async () => []),
44+
layered: vi.fn(async () => ({ effective: objectDef, code: objectDef, draft: draftEnvelope?.item ?? null })),
45+
getDraft: vi.fn(async () => draftEnvelope),
46+
get: vi.fn(async () => null),
47+
withPreviewDrafts() {
48+
return this;
49+
},
50+
};
51+
52+
vi.mock('../metadata-admin/useMetadata', async (importOriginal) => {
53+
const mod = await importOriginal<typeof import('../metadata-admin/useMetadata')>();
54+
return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) };
55+
});
56+
57+
vi.mock('./packages-io', async (importOriginal) => {
58+
const mod = await importOriginal<typeof import('./packages-io')>();
59+
return { ...mod, fetchPackages: vi.fn(async () => []) };
60+
});
61+
62+
vi.mock('@object-ui/react', async (importOriginal) => {
63+
const mod = await importOriginal<typeof import('@object-ui/react')>();
64+
return { ...mod, useAdapter: () => dataSource };
65+
});
66+
67+
import '@objectstack/lint';
68+
import { DataPillar } from './StudioDesignSurface';
69+
import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource';
70+
import { t, tFormat } from '../metadata-admin/i18n';
71+
72+
const discardDrafts = vi.fn(async () => ({ success: true, failedCount: 0, failed: [], discarded: [] }));
73+
const dataSource = Object.assign(createEmptyDataSource(), {
74+
getClient: () => ({ packages: { discardDrafts } }),
75+
});
76+
failOnAbsorbedFetchError();
77+
78+
beforeEach(() => {
79+
draftEnvelope = null;
80+
});
81+
afterEach(() => {
82+
cleanup();
83+
vi.clearAllMocks();
84+
});
85+
86+
const L = (key: string) => t(key, 'en-US');
87+
88+
function serveDraft(draftChanges?: unknown[]) {
89+
draftEnvelope = {
90+
type: 'object',
91+
name: 'showcase_task',
92+
item: { ...objectDef, _draft: true },
93+
version: 'v1',
94+
...(draftChanges ? { draftChanges } : {}),
95+
};
96+
}
97+
98+
function renderPillar(props: Partial<React.ComponentProps<typeof DataPillar>> = {}) {
99+
return render(
100+
<MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
101+
<DataPillar packageId="com.example.showcase" {...props} />
102+
</MemoryRouter>,
103+
);
104+
}
105+
106+
const AI_TWO = [
107+
{ path: [], by: 'studio', actor: 'usr_1', at: minutesAgo(30) },
108+
{ path: ['fields', 'renewal_count'], by: 'copilot', actor: 'usr_1', at: minutesAgo(2) },
109+
{ path: ['fields', 'priority', 'label'], by: 'mcp', client: 'Claude Desktop', actor: 'usr_1', at: minutesAgo(1) },
110+
];
111+
112+
describe('the AI assistant’s drafts on the Data canvas (objectstack#34725)', () => {
113+
it('a line counts the AI entries; 查看 opens the review; the AI-changed field cards carry the chip', async () => {
114+
serveDraft(AI_TWO);
115+
const onReviewChanges = vi.fn();
116+
renderPillar({ onReviewChanges });
117+
const line = await screen.findByTestId('studio-copilot-changes');
118+
expect(line).toHaveTextContent(tFormat('engine.studio.copilotChanges.line', 'en-US', { count: 2 }));
119+
fireEvent.click(within(line).getByTestId('studio-copilot-changes-view'));
120+
expect(onReviewChanges).toHaveBeenCalledTimes(1);
121+
122+
fireEvent.click(screen.getByRole('button', { name: L('engine.studio.data.tab.form') }));
123+
await waitFor(() => expect(screen.getAllByTestId('studio-form-field-draft-chip')).toHaveLength(2));
124+
expect(
125+
screen.getAllByTestId('studio-form-field-draft-chip').map((chip) => chip.getAttribute('data-draft-of')).sort(),
126+
).toEqual(['priority', 'renewal_count']);
127+
});
128+
129+
it('one AI entry reads in the singular', async () => {
130+
serveDraft([AI_TWO[1]]);
131+
renderPillar();
132+
expect(await screen.findByTestId('studio-copilot-changes')).toHaveTextContent(
133+
tFormat('engine.studio.copilotChanges.lineOne', 'en-US', { count: 1 }),
134+
);
135+
});
136+
137+
it('放弃全部未发布改动 discards the package’s drafts after a confirm; a declined confirm sends nothing', async () => {
138+
serveDraft(AI_TWO);
139+
// jsdom draws no confirm; the pillar asks the window's.
140+
const confirm = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
141+
const original = window.confirm;
142+
window.confirm = confirm;
143+
renderPillar();
144+
const discard = await screen.findByTestId('studio-copilot-changes-discard');
145+
expect(discard).toHaveTextContent(L('engine.studio.copilotChanges.discardAll'));
146+
fireEvent.click(discard);
147+
expect(confirm).toHaveBeenCalledWith(L('engine.studio.copilotChanges.discardConfirm'));
148+
expect(discardDrafts).not.toHaveBeenCalled();
149+
150+
const reads = mockClient.getDraft.mock.calls.length;
151+
draftEnvelope = null;
152+
fireEvent.click(discard);
153+
await waitFor(() => expect(discardDrafts).toHaveBeenCalledWith('com.example.showcase'));
154+
// The open object is read again, and the line goes with the draft.
155+
await waitFor(() => expect(mockClient.getDraft.mock.calls.length).toBeGreaterThan(reads));
156+
await waitFor(() => expect(screen.queryByTestId('studio-copilot-changes')).toBeNull());
157+
window.confirm = original;
158+
});
159+
160+
it('a discard that fails names each item by its label; the server’s words stay under Details', async () => {
161+
serveDraft(AI_TWO);
162+
discardDrafts.mockResolvedValueOnce({
163+
success: false,
164+
failedCount: 2,
165+
failed: [
166+
{ type: 'object', name: 'showcase_task', error: 'E_LOCKED: row held by txn 42' },
167+
{ type: 'view', name: 'showcase_task_grid', error: 'E_GONE' },
168+
],
169+
discarded: [],
170+
} as never);
171+
const original = window.confirm;
172+
window.confirm = vi.fn(() => true);
173+
renderPillar();
174+
fireEvent.click(await screen.findByTestId('studio-copilot-changes-discard'));
175+
const message = await screen.findByTestId('studio-refusal-message');
176+
expect(message).toHaveTextContent(
177+
tFormat('engine.studio.copilotChanges.discardFailed', 'en-US', {
178+
items: ['Task', 'showcase_task_grid'].join(L('engine.studio.copilotChanges.itemSeparator')),
179+
}),
180+
);
181+
expect(message.textContent).not.toContain('E_LOCKED');
182+
expect(message.textContent).not.toContain('object/');
183+
expect(screen.getByTestId('studio-refusal-detail')).toHaveTextContent('object/showcase_task: E_LOCKED: row held by txn 42');
184+
window.confirm = original;
185+
});
186+
187+
it('the copilot’s chip reads the object’s label and the view on screen', async () => {
188+
const onSurfaceLabelChange = vi.fn();
189+
renderPillar({ onSurfaceLabelChange });
190+
await waitFor(() =>
191+
expect(onSurfaceLabelChange).toHaveBeenLastCalledWith({
192+
type: 'object',
193+
name: 'showcase_task',
194+
label: `Task · ${L('engine.studio.data.tab.records')}`,
195+
}),
196+
);
197+
fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') }));
198+
await waitFor(() =>
199+
expect(onSurfaceLabelChange).toHaveBeenLastCalledWith(
200+
expect.objectContaining({ label: `Task · ${L('engine.studio.data.tab.form')}` }),
201+
),
202+
);
203+
});
204+
205+
it('CONTROL: entries a person wrote in Studio, or no draft at all, draw no line', async () => {
206+
serveDraft([{ path: ['fields', 'renewal_count'], by: 'studio', actor: 'usr_1', at: minutesAgo(2) }]);
207+
renderPillar();
208+
await screen.findByRole('button', { name: L('engine.studio.data.tab.form') });
209+
await waitFor(() => expect(mockClient.getDraft).toHaveBeenCalled());
210+
expect(screen.queryByTestId('studio-copilot-changes')).toBeNull();
211+
cleanup();
212+
213+
renderPillar();
214+
await screen.findByRole('button', { name: L('engine.studio.data.tab.form') });
215+
expect(screen.queryByTestId('studio-copilot-changes')).toBeNull();
216+
});
217+
});

0 commit comments

Comments
 (0)