Skip to content

Commit 4211f50

Browse files
feat(app-shell,components): Open the full form on an AI chat update card applies its proposed changes, before → after; a record in a list drawer is the chat's record in view (#31477)
<!-- claude-projects-attribution: {"github_login":"os-zhuang"} --> _Requested by **Sam** · [project thread](https://claude.ai/code/project/chan_01GsBogozeZG5sdpAARrN7HP?thread=cmsg_01GsBogozeZG5sdpAARrN7HPEvrGVfJq9tc5dC5mUCKJAd)_ Closes #28106 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:AI 聊天里的「修改记录」卡片点「打开完整表单」时,编辑页现在带着 AI 建议的新值打开:每个字段显示原值和新值,标「AI 建议」,可以逐个还原,不会自动保存。另外,列表页右侧抽屉打开某条记录时,聊天也会知道「这条」指的是哪条记录。 - 为什么改:之前点「打开完整表单」只打开原记录,AI 建议的修改要用户重新输入一遍;抽屉里问「把这条电话改成……」时 AI 不知道是哪条记录。 - 风险与回滚:只改控制台界面(三个前端包),不动规格和服务端;值走路由状态,不进网址。回滚即还原本 PR。 - 先看:`ui/packages/components/src/renderers/form/form.tsx`(建议值的应用、原值行和还原按钮)、`ui/packages/app-shell/src/views/RecordFormPage.tsx`(编辑页读取建议值)、`ui/packages/app-shell/src/layout/chatSurfaceContext.ts`(抽屉记录)。 - 两分钟验证:`cd ui && pnpm exec vitest run packages/components/src/renderers/form/__tests__/form-aiSuggestedMark-28104.test.tsx`,预期 11 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes The card's premise was re-measured before any code; two of its four items had already moved: - **Item 1 (record page sends the ask context) was already done** by objectstack#30043: the console dock sends `context.surface = { artifact: { type: 'object', name }, selection: { kind: 'record', id } }` on every record route (`ui/packages/app-shell/src/layout/chatSurfaceContext.ts`, `ConsoleLayout.tsx`), and cloud reads it (`service-ai/src/turn-grounding.ts`, whose record-focus block points the agent at `update_record`). What was still open is the record **drawer**: `?recordId=` over a list was read off the pathname only, so the dock sent the object alone. That gap is closed here. - **Item 2 (`open_record` with `proposedValues`) has no producer any more.** cloud#3565 removed that arm from `open_record` ("one way to propose a change, not two", `service-ai-studio/src/tools/open-record.tool.ts` header). An edit from chat is now `update_record`, rendered as the record-write card. A consumer for `proposedValues` would be dead code, so it is not built. - **What survives of items 2 and 3**, accepted by the dispatching seat: the update card's "Open the full form" opened `/record/:id/edit` on the stored record alone, so every change the card proposed had to be typed again. It now carries the card's proposed values there, through the router-state carrier objectstack#28104 introduced, and the edit form shows each as before → after, marked with the same 「AI 建议」 mark, with a per-field revert, and never submits on its own. ### The changes 1. **Drawer context** (`chatSurfaceContext.ts`, `ConsoleLayout.tsx`): on the three list routes (`:objectName`, `:objectName/data`, `:objectName/view/:viewId`), a non-empty `?recordId=` (`RECORD_DRAWER_PARAM`) makes the surface name the object and that record, exactly the shape the record page sends. The New page, a record page and pages with no artifact read as before. Same `context.surface` shape, no second one. 2. **Carrier** (`utils/recordFormAiDraft.ts`): `recordWriteFormTarget` gives an update the same `recordFormAiDraft` state key, now with the `recordId` the values were proposed for. Every named field is kept, an empty one included (clearing a field is a change). `readRecordFormAiChanges(state, recordId)` reads it for that record only; `readRecordFormAiDraft` (the create reader) ignores a draft that names a record. Nothing is added to the URL. 3. **Edit page** (`views/RecordFormPage.tsx`): in edit mode it reads the changes for its own record and provides them through the new `SuggestedFieldChangesContext`, and shows the same one-line notice the create page shows (`form.aiDraftNotice`). It still opens on the stored record: no create values, no `SuggestedFieldsContext`. 4. **Form renderer** (`components/src/renderers/form/form.tsx`, `suggested-fields-context.ts`): the new host slot `SuggestedFieldChangesContext` (field name → proposed value) is the edit-form sibling of #28104's `SuggestedFieldsContext`. The renderer applies each proposed value **once**, on the first reset that brings the record, **after** the reset window, with `setValue(…, { shouldDirty: true })`: the form reads dirty, the discard guard hears it, the value channels report it, and the save payload (which diffs against the loaded record) writes it, exactly as the person's own edit would. A proposal equal to the stored value, for a field the form does not draw, or for a statically read-only, disabled or hidden field is not applied. While the control holds the proposed value the field shows the #28104 mark (`form.aiSuggested`, the same span), a `Was: …` line with the stored value (option label, a lookup's name, a list joined, `empty` for none), and a **Revert** button that puts the stored value back; the person's own edit or the revert takes all three away. 5. **i18n**: `form.aiBefore`, `form.aiBeforeEmpty`, `form.aiRevert` in all eleven locale packs (no quote characters, so the de quote-pair count is unchanged). No `packages/spec` path, no new metadata key: both contexts are host slots, and the update card's own buttons and labels are unchanged. ## Why The record-write card (cloud#3565) is how chat proposes a change to one record; its "Open the full form" is the path for a person who wants to see the change in the whole form before saving. Opening that form without the change throws away what the card showed. And a record open in a list's drawer is as much "this record" as a record page. ## Tests Pins, each with a CONTROL: - `ui/packages/app-shell/src/layout/__tests__/chatSurfaceContext-30043.test.ts`: new describe, drawer `?recordId=` on all three list routes, encoded id; controls for no or empty param, the view selection without a drawer, the New page, a record page, pages with no artifact and host routes. - `ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx`: new describe, the REAL dock's chat POST body names the drawer record, and the next turn after the drawer closes names the object only. - `ui/packages/app-shell/src/utils/__tests__/recordFormAiDraft-28104.test.ts`: the #28104 "an update carries no draft" case now pins the update's state; new describe for nothing in the URL, empty (clearing) values kept, binding to the record, and a create page never reading it. - `ui/packages/app-shell/src/views/RecordFormPage.aiDraft-28104.test.tsx`: new describe, the edit page hands the form the changes and shows the notice once, through a real `navigate(to, { state })` with nothing after the edit path, still opens on the stored record; controls for another record's draft, a create's draft, no state, and a create page given an update's state. - `ui/packages/components/src/renderers/form/__tests__/form-aiSuggestedMark-28104.test.tsx`: new describe, a proposed change lands in the control, marked, with `Was: …` (option label for a select); a proposal equal to the stored value shows nothing; revert restores the stored value and removes mark, line and button; the person's own edit removes the mark; the form reports dirty; a read-only and an undrawn field are left alone and the save payload carries neither change; mounting submits nothing and Save submits the applied change; control with no provider. ### Ablation Each leg mutated through `scripts/ablation-replace.mjs` (anchor hit x1 → x0, distinct marker x0 → x1, restore proven by blob == HEAD and an empty `git diff HEAD`; the ui vitest config aliases `@object-ui/*` to `src`, so no build sits between the mutation and the run). The direction was written in each test file's header before the run. | leg | mutation | red | green | |---|---|---|---| | A renderer | skip every proposal in the apply loop | lands-marked, revert, dirty/read-only, Save payload (4) | the five #28104 cells, the own-edit cell, CONTROL | | B edit page | edit mode reads no changes | hands-the-form, navigate-with-state (2) | the six #28104 cells, stored-record, CONTROL | | C drawer | ignore `?recordId=` | the drawer pin, the dock wire pin (2) | the other 15 | | D carrier | update target drops its state | the two update-state pins (2) | the other 6 | In leg A the own-edit cell stayed green because it then asserted only the absence of the mark after an edit; it now first asserts the mark is present, so it reds under the same mutation. ## Acceptance notes - `open_record`'s `proposedValues` arm is gone from cloud (cloud#3565), so item 2's 「修改 X(N 个字段)→」 card variant is not built: no producer emits it. The update card keeps its own title and its "Open the full form" label. - A proposal is applied only to a field the form draws and the person could edit: not read-only, disabled or hidden by its config, and not locked by a `readonlyWhen` rule on the stored record (the same `readonlyFieldNames` verdict the save strips by). cloud's `update_record` already proposes only fields the user may write (`record-draft-validation.ts`, rule 1). - Each proposal is tried once per field, on the first pass where the form draws that field. An edit wizard draws one step at a time, so a step-2 proposal lands and is marked when step 2 opens, and a step-1 field the person reverted is not re-applied on Next or Back. - The `Was: …` line formats the stored value without a lookup read: an option field reads its option label, an expanded lookup its name, a bare lookup id is shown as the id. - Router state belongs to the tab's history entry, as for #28104: reload or Back to that entry reopens the proposals, a copied link opens the stored record. - Serial behind objectstack#28104: opened after #31445 landed, with `main` merged into this branch by a merge commit (`229de9fb`); the delta over `main` is this card's alone. ## Verification All readings on `objectstack-ai/objectstack` at head `229de9fb` (main `a40eb02e` merged, which carries #31445 as `bb618728`), after `pnpm install --frozen-lockfile` and a rebuild of the `@object-ui/app-shell` dependency closure (`turbo run build --filter='@object-ui/app-shell^...'`, 66/66), every heavy run under `scripts/pm/os-verify-lock.sh`. <details><summary>Type check and tests</summary> - `pnpm run type-check` in `ui/packages/components`, `ui/packages/i18n`, `ui/packages/app-shell` (both `tsc --noEmit` and `tsconfig.test.json`): exit 0 ×3. - `vitest run packages/components/`: Test Files 478 passed, 1 skipped (479); Tests 4584 passed, 24 skipped. - `vitest run packages/i18n/`: Test Files 99 passed (99); Tests 1804 passed, 13 skipped. - `vitest run packages/app-shell/src/layout/ packages/app-shell/src/utils/ packages/app-shell/src/console/ai/ packages/app-shell/src/views/RecordFormPage`: Test Files 256 passed, 1 skipped (257); Tests 2134 passed, 8 skipped. DECLARED NARROWING: the whole app-shell package is 2,218 test files, over an hour at two workers on this box; the full package runs in CI's `Test UI`. - The five files this PR edits, before the merge: Test Files 5 passed (5), Tests 46 passed. </details> <details><summary>Ablation</summary> Run on the pre-merge head (`ebd61fef`/`cb1a8535`), whose delta over the #28104 content is byte-identical to this PR's delta over `main` (checked per conflicted file during the merge). Results in the Tests section above. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` on `229de9fb` derives 39 families; all 39 ran locally, each exit captured before any pipe, all exit 0 (`check:type-check-debt` under the lock: 0 ledger entries re-measured above their number). `--ran` reconciliation: 39 derived, 39 run, 0 NOT-MEASURED (a derived zero), 0 UNRUN. One finding on the way: `check:test-source-alias` asked `ChatDock.requestContext-30043.test.tsx` to load `@objectstack/lint` at module top (the layout reaches it through a dynamic import); fixed in `d6b726d7`. The repo-wide scans (`pnpm lint` first) and the families outside the derived list are CI's. </details> ## Review round 1 (head `79a39a9c`) The seat review asked for two items, now done in `e50be7b9`. `79a39a9c` merges `main` `a1d243e0`, which carries the raised eager `i18n-locale-en` ceiling from objectstack#31465. These runs supersede the Verification readings above, which were taken at `229de9fb`. ### (1) Wizard: proposals tried per field `suggestedChangeAttemptsRef` is a `Set<string>`. Each proposal is tried once, on the first pass where the form draws that field, and never again. A layout effect on `drawnFieldNames` covers a step change that brings no reset. The before line and the revert read `appliedChangeBefore`, which holds the stored value per applied field. They do not read `defaultValues`, because the wizard refills it at every step boundary. The pin is a new file, `ui/packages/plugin-form/src/WizardForm.aiProposedChanges-28106.test.tsx`. It is an edit wizard with name on step 1 and phone on step 2: - Step 1: name is applied and marked, then reverted. - Next: phone is applied and marked on step 2, "Was: 13900001111". - CONTROL: Back, then Next and Back again. Name stays reverted. ### (2) readonlyWhen This was cheap, so it is done rather than left as a limit. The apply loop also skips `readonlyFieldNames.has(name)`, the same verdict the save strips by. That check is gated on `previousValues`, which both RecordFormPage edit and WizardForm edit supply. The pin is a new cell in `form-aiSuggestedMark-28104.test.tsx`: a field locked by `readonlyWhen: "previous.status != 'draft'"` beside an unlocked one. ### Ablation Run on the committed round with `scripts/ablation-replace.mjs`. Every leg was restored to HEAD (blob 5675c91). | Leg | Mutation | Red (as predicted) | |---|---|---| | A | old single try: attempt recorded before the drawn check | the wizard cell, on step 2's phone (expected 13800000000, got 13900001111) | | B | attempts not recorded | the wizard CONTROL (expected 张伟, got 李四) | | C | rule lock not consulted | the readonlyWhen cell | | restored | — | none: 13/13 green | ### Runs **Round head 2650aa2d** (its tree is identical to 43b7e4f): `vitest run packages/components packages/plugin-form packages/app-shell/src/views/RecordFormPage.aiDraft-28104.test.tsx` - Test Files: 704 passed, 1 skipped - Tests: 7055 passed, 25 skipped **Merged tree 79a39a9:** - `turbo run build --filter=@object-ui/console^...` (72/72), then `vite build` of apps/console. - `pnpm --dir ui run check:eager-closure`: exit 0. - `i18n-locale-en` is 60,065 gzip bytes against the 61,000 ceiling, so **935 bytes of headroom**. - The aggregate closure is 2185.2 KB against 2431.6 KB. - `pnpm run type-check`: exit 0 in components, plugin-form, app-shell and i18n. - `vitest run` on `packages/components/src/renderers/form`, `packages/plugin-form`, `packages/i18n`, and in app-shell `views/RecordFormPage`, `layout`, `utils` and `console/ai`: - Test Files: 665 passed, 1 skipped - Tests: 6996 passed, 39 skipped - `dispatch-gates --commands`: the same 39 families as before the merge. `--ran`: 39 run, 0 NOT-MEASURED, all exit 0. - DECLARED NARROWING (unchanged): the whole app-shell package runs in CI's Test UI. All heavy runs went through `scripts/pm/os-verify-lock.sh`. Their wall times are shared-box seconds. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (no `packages/spec` path) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (CI-owned, see Verification) - [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. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QUs3BvstGvKpRZPWDGvLmz --- _Generated by [Claude Code](https://claude.ai/code/session_01QUs3BvstGvKpRZPWDGvLmz)_ <!-- signed: repo:cloud#3 · os-zhuang · session_01QUs3BvRcDHXqRU4TSVE4u6 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e516cf2 commit 4211f50

26 files changed

Lines changed: 857 additions & 54 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/components': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
feat(app-shell,components): "Open the full form" on an AI chat update card opens the edit form with the proposed changes applied, before → after, marked 「AI 建议」 with a per-field revert; a record open in a list's drawer is sent to the chat as the record in view
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
- **`@object-ui/app-shell`:** on an update card from the AI chat (cloud#3565), "Open the full form" used to open the record's edit page on the stored record alone, so every change the card proposed had to be typed again. The card's proposed values now travel in the router state of that navigation, through the same carrier the create card uses (`utils/recordFormAiDraft.ts`), bound to the record they were proposed for, and nothing is added to the URL. `RecordFormPage` reads them in edit mode only, for that record only, hands them to the form, and shows the same one-line notice above it that nothing is saved until the person checks and saves. Nothing submits on its own. The console dock now also reads a list's record drawer (`?recordId=`): while a record is open in the drawer, the chat's `context.surface` names the object and that record, as it already did on the record page, so "change its phone to …" asked beside the drawer reaches the agent about that record.
13+
- **`@object-ui/components`:** new host slot `SuggestedFieldChangesContext` (field name → proposed value, default `undefined`), the edit-form sibling of `SuggestedFieldsContext`. A `form` renderer under it applies each proposed value once, over the record it opens on, as an unsaved change: the form reads dirty, the discard guard hears it and Save writes it. While a field still holds the proposed value it shows the same "AI suggestion" mark, a "Was: …" line with the stored value it replaces, and a Revert button that puts the stored value back. A proposal for a field the form does not draw, or one that is read-only (by its config or by a `readonlyWhen` rule on the stored record) or disabled, is not applied. Each proposal is tried once per field, when the form first draws it, so on an edit wizard a later step's proposal lands on that step and a field the person reverted stays reverted across Next and Back. It is not metadata: no form or field key sets it, and with no provider nothing changes.
14+
- **`@object-ui/i18n`:** `form.aiBefore`, `form.aiBeforeEmpty` and `form.aiRevert` in all eleven locale packs.

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1752,9 +1752,11 @@ export function ChatPane({
17521752
// copied, shared and logged (objectstack#28104, `recordFormAiDraft.ts`).
17531753
// The form marks each of those fields 「AI 建议」 until the person edits
17541754
// it, and opens unsaved; the form's own defaults fill the rest. An update
1755-
// opens the record's edit form: the card has shown old → new, and the form
1756-
// opens on the stored record. The card cancelled the pending write before
1757-
// calling this, so a record saved here is never written a second time.
1755+
// opens the record's edit form on the stored record with the card's
1756+
// proposed values in the same router state (objectstack#28106): the form
1757+
// applies each as an unsaved change, before → after, marked 「AI 建议」 with
1758+
// a per-field revert. The card cancelled the pending write before calling
1759+
// this, so a record saved here is never written a second time.
17581760
const openRecordForm = useCallback(
17591761
async (write: {
17601762
operation: 'create' | 'update';

‎ui/packages/app-shell/src/layout/ConsoleLayout.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,11 @@ export function ConsoleLayout({
200200
// `context.surface` (cloud#1610's shape): the object of a list, the object
201201
// and record id of a record page, the dashboard, report or page. Read off the
202202
// URL each render, so the next send after a navigation carries the new page.
203+
// objectstack#28106 — the query string too: a record open in a list's
204+
// detail drawer (`?recordId=`) is the record in view.
203205
const dockSurface = useMemo(
204-
() => consoleChatSurface(location.pathname, hostRoutePaths),
205-
[location.pathname, hostRoutePaths],
206+
() => consoleChatSurface(location.pathname, hostRoutePaths, location.search),
207+
[location.pathname, location.search, hostRoutePaths],
206208
);
207209
// The chip's label for an object surface: the object's own translated
208210
// label, the one its page shows: the served label as given, the bundle only

‎ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ import { armChatDockExpanded } from '../chatDockState';
9292
// scope, so no test's send-wait spends its budget on the first cold import and
9393
// the `lazy()` resolves from the module cache.
9494
import '../ChatDockConversation';
95+
// The layout reaches `@objectstack/lint` through a dynamic import (the draft
96+
// preview bar's capability lint): pay that load during collection, not inside
97+
// a clocked case (check:test-source-alias).
98+
import '@objectstack/lint';
9599

96100
const CRM = { name: 'crm_app', label: 'Customer Desk', _packageId: 'app.crm' };
97101
const OBJECTS = [{ name: 'account', label: 'Account' }];
@@ -272,3 +276,16 @@ describe('console dock — the request names the selected app and the page in vi
272276
});
273277
});
274278
});
279+
280+
describe('console dock — a record open in a list drawer is sent as the record in view (objectstack#28106)', () => {
281+
it('the body names the drawer record, and closing the drawer moves the next turn back to the object', async () => {
282+
mount('/apps/crm_app/account?recordId=rec_7');
283+
expect((await send('change its phone to 123')).surface).toEqual({
284+
artifact: { type: 'object', name: 'account' },
285+
selection: { kind: 'record', id: 'rec_7' },
286+
});
287+
288+
act(() => nav.go('/apps/crm_app/account'));
289+
expect((await send('how many accounts?')).surface).toEqual({ artifact: { type: 'object', name: 'account' } });
290+
});
291+
});

‎ui/packages/app-shell/src/layout/__tests__/chatSurfaceContext-30043.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,27 @@ describe('consoleChatSurface — the page in view as cloud#1610 `context.surface
7777
for (const path of Object.keys(APP_ROUTE_SURFACES)) expect(declared.has(path), path).toBe(true);
7878
});
7979
});
80+
81+
describe('consoleChatSurface — a record open in a list drawer is the record in view (objectstack#28106)', () => {
82+
const RECORD = { artifact: { type: 'object', name: 'account' }, selection: { kind: 'record', id: 'rec_1' } };
83+
84+
it('on every list route, `?recordId=` names the object and that record', () => {
85+
expect(consoleChatSurface('/apps/crm/account', [], '?recordId=rec_1')).toEqual(RECORD);
86+
expect(consoleChatSurface('/apps/crm/account/data', [], '?recordId=rec_1&tab=details')).toEqual(RECORD);
87+
// Over a saved view the open record is the finer selection.
88+
expect(consoleChatSurface('/apps/crm/account/view/my_open', [], '?recordId=rec_1')).toEqual(RECORD);
89+
expect(consoleChatSurface('/apps/crm/account', [], '?recordId=a%2Fb%20c')?.selection).toEqual({ kind: 'record', id: 'a/b c' });
90+
});
91+
92+
it('CONTROL: no drawer, an empty param, or a route that is not a list reads as before', () => {
93+
expect(consoleChatSurface('/apps/crm/account', [], '')).toEqual({ artifact: { type: 'object', name: 'account' } });
94+
expect(consoleChatSurface('/apps/crm/account', [], '?recordId=')).toEqual({ artifact: { type: 'object', name: 'account' } });
95+
expect(consoleChatSurface('/apps/crm/account/view/my_open', [], '?tab=x')?.selection).toEqual({ kind: 'view', id: 'my_open' });
96+
// The New page and a record page keep their own reading.
97+
expect(consoleChatSurface('/apps/crm/account/new', [], '?recordId=rec_1')).toEqual({ artifact: { type: 'object', name: 'account' } });
98+
expect(consoleChatSurface('/apps/crm/account/record/rec_2', [], '?recordId=rec_1')?.selection).toEqual({ kind: 'record', id: 'rec_2' });
99+
// A page with no artifact gains none from the param.
100+
expect(consoleChatSurface('/apps/crm/search', [], '?recordId=rec_1')).toBeUndefined();
101+
expect(consoleChatSurface('/apps/crm/billing', ['billing'], '?recordId=rec_1')).toBeUndefined();
102+
});
103+
});

‎ui/packages/app-shell/src/layout/chatSurfaceContext.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import { matchRoutes } from 'react-router-dom';
2626
import { APP_ROUTE_METADATA_READS } from '../console/appRouteMetadataReads.js';
27+
import { RECORD_DRAWER_PARAM } from '../urlParams.js';
2728

2829
/** cloud#1610's `context.surface` — see the module doc. */
2930
export interface ChatSurfaceContext {
@@ -76,16 +77,28 @@ export const APP_ROUTE_SURFACES: Readonly<Record<string, (p: Params) => ChatSurf
7677
'page/:pageName': named('page', 'pageName'),
7778
};
7879

80+
/**
81+
* objectstack#28106 — the list routes that open a record in the detail drawer
82+
* (`?recordId=`, `RECORD_DRAWER_PARAM`) over the list. While the drawer is
83+
* open, the record in it is the one in view, exactly as on its record page:
84+
* the surface names the object and that record, so 「把这条电话改成……」 asked
85+
* beside the drawer reaches the agent as the record-page ask does.
86+
*/
87+
const RECORD_DRAWER_ROUTES: ReadonlySet<string> = new Set([':objectName', ':objectName/data', ':objectName/view/:viewId']);
88+
7989
/**
8090
* The surface the console page at `pathname` shows, or `undefined` when it
8191
* shows no one artifact. `pathname` is the router's (below any basename);
8292
* only `/apps/:appName/…` pages have one. `hostPaths` are the host's extra
8393
* app routes (`AppContent`'s `extraRoutes`): one that matches wins the way it
84-
* wins in `<Routes>`, and names no surface.
94+
* wins in `<Routes>`, and names no surface. `search` is the location's query
95+
* string: on a list route a record open in the drawer (`?recordId=`) is the
96+
* finer selection, over the saved view the list shows.
8597
*/
8698
export function consoleChatSurface(
8799
pathname: string,
88100
hostPaths: readonly string[] = [],
101+
search = '',
89102
): ChatSurfaceContext | undefined {
90103
const segments = pathname.split('/').filter(Boolean);
91104
if (segments[0] !== 'apps' || segments.length < 3) return undefined;
@@ -96,5 +109,10 @@ export function consoleChatSurface(
96109
const matches = matchRoutes(routes, `/${segments.slice(2).join('/')}`);
97110
const hit = matches?.[matches.length - 1];
98111
if (!hit || hit.route.host) return undefined;
99-
return APP_ROUTE_SURFACES[hit.route.path]?.(hit.params);
112+
const surface = APP_ROUTE_SURFACES[hit.route.path]?.(hit.params);
113+
if (surface?.artifact && RECORD_DRAWER_ROUTES.has(hit.route.path)) {
114+
const drawerRecordId = new URLSearchParams(search).get(RECORD_DRAWER_PARAM)?.trim();
115+
if (drawerRecordId) return { artifact: surface.artifact, selection: { kind: 'record', id: drawerRecordId } };
116+
}
117+
return surface;
100118
}

‎ui/packages/app-shell/src/utils/__tests__/recordFormAiDraft-28104.test.ts‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@
1212
* reads back exactly what was sent.
1313
*/
1414
import { describe, expect, it } from 'vitest';
15-
import { readRecordFormAiDraft, recordFormAiDraftState, recordWriteFormTarget } from '../recordFormAiDraft';
15+
import {
16+
readRecordFormAiChanges,
17+
readRecordFormAiDraft,
18+
recordFormAiChangesState,
19+
recordFormAiDraftState,
20+
recordWriteFormTarget,
21+
} from '../recordFormAiDraft';
1622

1723
const CREATE = {
1824
operation: 'create' as const,
@@ -49,12 +55,13 @@ describe('recordWriteFormTarget (objectstack#28104)', () => {
4955
expect(target).toStrictEqual({ to: '/apps/crm/crm_lead/new' });
5056
});
5157

52-
it('an update opens the edit page on the stored record and carries no draft', () => {
58+
it('an update opens the edit page with its proposed values in state, bound to the record (objectstack#28106)', () => {
5359
const target = recordWriteFormTarget(
5460
{ operation: 'update', objectName: 'crm_lead', recordId: 'lead 1', fields: [{ name: 'phone', value: '1' }] },
5561
'crm',
5662
);
57-
expect(target).toStrictEqual({ to: '/apps/crm/crm_lead/record/lead%201/edit' });
63+
expect(target.to).toBe('/apps/crm/crm_lead/record/lead%201/edit');
64+
expect(readRecordFormAiChanges(target.state, 'lead 1')).toStrictEqual(new Map([['phone', '1']]));
5865
});
5966
});
6067

@@ -71,3 +78,48 @@ describe('readRecordFormAiDraft (objectstack#28104)', () => {
7178
expect(recordFormAiDraftState([])).toBeUndefined();
7279
});
7380
});
81+
82+
describe('an update card\'s proposed values reach the edit page (objectstack#28106)', () => {
83+
const UPDATE = {
84+
operation: 'update' as const,
85+
objectName: 'crm_lead',
86+
recordId: 'lead_1',
87+
fields: [
88+
{ name: 'phone', value: '13800000000' },
89+
{ name: 'estimated_amount', value: 90000 },
90+
{ name: 'note', value: '' },
91+
{ name: 'email', value: null },
92+
],
93+
};
94+
95+
it('nothing rides in the URL; every named field rides in state, an empty (clearing) value included', () => {
96+
const target = recordWriteFormTarget(UPDATE, 'crm');
97+
expect(target.to).toBe('/apps/crm/crm_lead/record/lead_1/edit');
98+
expect(target.to).not.toContain('?');
99+
expect(target.to).not.toContain('13800000000');
100+
expect(readRecordFormAiChanges(target.state, 'lead_1')).toStrictEqual(
101+
new Map<string, unknown>([
102+
['phone', '13800000000'],
103+
['estimated_amount', 90000],
104+
['note', ''],
105+
['email', null],
106+
]),
107+
);
108+
});
109+
110+
it('only that record\'s edit page reads it, and a create page never does', () => {
111+
const state = recordWriteFormTarget(UPDATE, 'crm').state;
112+
expect(readRecordFormAiChanges(state, 'lead_2')).toBeUndefined();
113+
expect(readRecordFormAiChanges(state, undefined)).toBeUndefined();
114+
expect(readRecordFormAiDraft(state)).toBeUndefined();
115+
});
116+
117+
it('CONTROL: a create\'s draft, or a state that is not a draft, carries no changes', () => {
118+
expect(readRecordFormAiChanges(recordWriteFormTarget(CREATE, 'crm').state, 'lead_1')).toBeUndefined();
119+
for (const state of [undefined, null, 'x', {}, { recordFormAiDraft: { values: { a: 1 } } }]) {
120+
expect(readRecordFormAiChanges(state, 'lead_1')).toBeUndefined();
121+
}
122+
expect(recordFormAiChangesState('lead_1', [])).toBeUndefined();
123+
expect(recordWriteFormTarget({ ...UPDATE, fields: [] }, 'crm')).toStrictEqual({ to: '/apps/crm/crm_lead/record/lead_1/edit' });
124+
});
125+
});

‎ui/packages/app-shell/src/utils/recordFormAiDraft.ts‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,26 @@
1818
* absent everywhere else: a copied link, a new tab, another device all open
1919
* an empty form. Nothing here saves anything: the page opens unsaved and the
2020
* person presses Save.
21+
*
22+
* objectstack#28106 — the same carrier takes an UPDATE card's proposed values
23+
* to the record's edit page. Such a draft names the record it was proposed
24+
* for (`recordId`), and only that record's edit page reads it: the edit form
25+
* opens on the stored record and applies each proposed value over it as an
26+
* unsaved change, before → after, marked 「AI 建议」 with a per-field revert.
27+
* An update keeps an EMPTY proposed value (clearing a field is a change); a
28+
* create leaves it out (the form's own default fills that field).
2129
*/
2230

2331
/** The key the draft rides under in `location.state`. */
2432
const AI_DRAFT_KEY = 'recordFormAiDraft';
2533

2634
/** The `state` "Open the full form" navigates with. */
2735
export interface RecordFormAiDraftState {
28-
[AI_DRAFT_KEY]: { values: Record<string, unknown> };
36+
[AI_DRAFT_KEY]: {
37+
values: Record<string, unknown>;
38+
/** Present on an update's draft: the record its values are proposed for. */
39+
recordId?: string;
40+
};
2941
}
3042

3143
/** An empty value is left out: the form's own default fills that field. */
@@ -61,6 +73,8 @@ export function readRecordFormAiDraft(state: unknown): Record<string, unknown> |
6173
if (!state || typeof state !== 'object') return undefined;
6274
const draft = (state as Record<string, unknown>)[AI_DRAFT_KEY];
6375
if (!draft || typeof draft !== 'object') return undefined;
76+
// An update's draft (it names a record) is the edit page's, never a create's.
77+
if ((draft as { recordId?: unknown }).recordId !== undefined) return undefined;
6478
const values = (draft as { values?: unknown }).values;
6579
if (!values || typeof values !== 'object' || Array.isArray(values)) return undefined;
6680
const out: Record<string, unknown> = {};
@@ -70,11 +84,51 @@ export function readRecordFormAiDraft(state: unknown): Record<string, unknown> |
7084
return Object.keys(out).length > 0 ? out : undefined;
7185
}
7286

87+
/**
88+
* objectstack#28106 — the router state for an update card's proposed values
89+
* to `recordId`, or `undefined` when the card names no field. Every named
90+
* field is kept, an empty value included: on an update, clearing a field is
91+
* the change the card proposed.
92+
*/
93+
export function recordFormAiChangesState(
94+
recordId: string,
95+
fields: ReadonlyArray<{ name: string; value: unknown }>,
96+
): RecordFormAiDraftState | undefined {
97+
const values: Record<string, unknown> = {};
98+
for (const f of fields) {
99+
if (f.name) values[f.name] = f.value === undefined ? null : f.value;
100+
}
101+
return Object.keys(values).length > 0 ? { [AI_DRAFT_KEY]: { values, recordId } } : undefined;
102+
}
103+
104+
/**
105+
* The proposed changes an edit page of `recordId` was opened with, field name
106+
* → proposed value, or `undefined` when its `location.state` carries none for
107+
* THIS record (a create's draft, another record's, or anything not a draft).
108+
*/
109+
export function readRecordFormAiChanges(
110+
state: unknown,
111+
recordId: string | undefined,
112+
): ReadonlyMap<string, unknown> | undefined {
113+
if (!recordId || !state || typeof state !== 'object') return undefined;
114+
const draft = (state as Record<string, unknown>)[AI_DRAFT_KEY];
115+
if (!draft || typeof draft !== 'object') return undefined;
116+
if ((draft as { recordId?: unknown }).recordId !== recordId) return undefined;
117+
const values = (draft as { values?: unknown }).values;
118+
if (!values || typeof values !== 'object' || Array.isArray(values)) return undefined;
119+
const out = new Map<string, unknown>();
120+
for (const [name, value] of Object.entries(values as Record<string, unknown>)) {
121+
if (name) out.set(name, value);
122+
}
123+
return out.size > 0 ? out : undefined;
124+
}
125+
73126
/**
74127
* Where "Open the full form" on a record-write card goes, given the app the
75128
* object belongs to. A create opens the New page with the card's values in
76129
* `state` and nothing after the path; an update opens the record's edit page
77-
* on the stored record (the card already showed old → new).
130+
* with the card's proposed values in `state` (objectstack#28106), which the
131+
* form applies over the stored record as unsaved changes.
78132
*/
79133
export function recordWriteFormTarget(
80134
write: {
@@ -87,7 +141,9 @@ export function recordWriteFormTarget(
87141
): { to: string; state?: RecordFormAiDraftState } {
88142
const base = `/apps/${encodeURIComponent(app)}/${encodeURIComponent(write.objectName)}`;
89143
if (write.operation === 'update' && write.recordId) {
90-
return { to: `${base}/record/${encodeURIComponent(write.recordId)}/edit` };
144+
const to = `${base}/record/${encodeURIComponent(write.recordId)}/edit`;
145+
const changes = recordFormAiChangesState(write.recordId, write.fields);
146+
return changes ? { to, state: changes } : { to };
91147
}
92148
const state = recordFormAiDraftState(write.fields);
93149
return state ? { to: `${base}/new`, state } : { to: `${base}/new` };

0 commit comments

Comments
 (0)