Skip to content

Commit 3e7feed

Browse files
fix(app-shell): AI chat publish seed warning says the pack sentence, not engine text (#35359)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg6v19uPsX6gX42G8tGcvvzb)_ Fixes #35303 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:在 AI 对话页发布草稿时,如果示例数据(seed)载入失败,警告提示的详情行改为语言包里的那句「示例数据未能加载。」,不再显示 seed 载入器的英文内部报错,也不再显示 `[object Object]`。 - 为什么改:用中文发布的搭建者会在警告下看到英文引擎文本,或在只有逐行错误时看到 `[object Object]`;#32984 的裁决是面向用户的文字只用客户句。首页「全部发布」已由 #35301 改好,这是同族的第二个入口。 - 风险与回滚:只改 `onPublishDrafts` 里警告详情取哪句话,另把引擎文本与错误行原样打到浏览器控制台(`console.warn`);不动接口、语言键和导出。回滚即 revert 本 PR。 - 先看:`ui/packages/app-shell/src/console/ai/AiChatPage.tsx`(`onPublishDrafts` 里 `console.ai.seedWarn` 那一处 toast);`ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx`;`.changeset/35303-ai-chat-seed-warn-pack-sentence.md`。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx`,预期 6 个用例全绿(en 与 zh-Hans 两种语言)。 - 需要你做的:无,席位落地。 ## What changes `AiChatPage`'s `onPublishDrafts` warns `console.ai.seedWarn` when the publish answers `seedApplied.success === false`. The warning's description used to be `seedApplied.error` (the seed loader's engine text), else `String(seedApplied.errors[0])`, which reads `[object Object]` for a structured `{ row, reason }` row. The description is now always the pack sentence `chatbot.build.health.seedFailed`: the sentence the chat's publish-health line says for the same failure and the one *Publish all* says since #35301 (objectstack#32984 Q1 ruling: user-facing text is the customer sentence, never developer or engine text). The engine text and the error rows go to `console.warn('[app-shell] Published, but the seed failed to load:', { packageId, error, errors })`, whole, and they still reach the health line's technical details through `publishHealthFromResponse`, which this diff does not touch. The changeset is `patch` on `@object-ui/app-shell`. No locale keys, props or exports change. ## Tests New file `AiChatPage.seedWarnPackSentence-35303.test.tsx`, built on the `publishAdvisoryReachesAuthor` harness (the real handler, `useMetadataClient` and its client; stubbed `sonner`, `fetch` and the chat tree reduced to the button that fires `onPublishDrafts`), plus `I18nProvider` with the shipped `en` and `zh-Hans` packs. Its own file because `I18nProvider` installs a module-level i18next global, which would leak into the sibling pin's default-value reads. - engine-text arm: a batch whose `seedApplied` failed with `error` shows the pack's `seedWarn` title and `seedFailed` description; the engine text is absent from the toast and present in the one `console.warn` line; - structured-row arm: a batch whose `seedApplied` failed with `errors: [{ row, reason }]` and no `error` shows the pack sentence, never `[object Object]`; the row reaches `console.warn` as an object; - CONTROL: a seed that loaded raises no warning, no seed console line, and one `publishOk` success toast. Each case runs in `en` and `zh-Hans` (6 cases). ## Acceptance notes - Family check: the other `seedApplied` readers under `ui/` are `usePublishAllDrafts` (fixed by #35301), `publishHealthFromResponse` (already folds the detail under technical details) and the client's type declaration; no third toast producer was found. ## Verification All readings at head `09500fa40c`. <details><summary>Ablation: the old description restored on disk, 4 red / 2 green, then restored</summary> The fix was committed first (da8a671). `node scripts/ablation-replace.mjs` replaced the new description with the old `seedApplied.error ?? String(seedApplied.errors[0])` expression: anchor 1 to 0, replacement 0 to 1, blob af4e13d to a8bb0a93e9. The subject resolves through source (relative import), so no build sits between the edit and the run. ``` Expected: "Sample data failed to load." Received: "seed apply stopped at the seed for object 'crm_task': Reference not found: owner = "ann"" Expected: "示例数据未能加载。" Received: "[object Object]" Test Files 1 failed (1) Tests 4 failed | 2 passed (6) ablation-replace: ok restored: blob == HEAD (af4e13d) and `git diff HEAD` is empty ``` The 4 failures are the two defect arms in two locales; the 2 passes are the CONTROL cases. </details> <details><summary>Green on the fixed head</summary> ``` pnpm --dir ui exec vitest run --maxWorkers=2 (new file + publishAdvisoryReachesAuthor) Test Files 2 passed (2) Tests 9 passed (9) os-verify-lock: VERDICT command-exit 0 pnpm --dir ui exec vitest run --maxWorkers=2 (console/ai/__tests__/ + the app-shell census and ratchet files that walk sources + the i18n and plugin-chatbot files that read sources) Test Files 105 passed (105) Tests 1182 passed (1182) os-verify-lock: VERDICT command-exit 0 pnpm --filter @object-ui/app-shell run type-check (both tsc programs; the new test is in tsconfig.test.json's file list) os-verify-lock: VERDICT command-exit 0 eslint on the two touched source files: 0 errors (27 pre-existing warnings, none in the edited hunk) ``` </details> <details><summary>Derived gate families (dispatch-gates --commands, 38 families)</summary> All 38 derived families exited 0, including `pnpm --dir ui exec vitest run scripts/` (171 files passed, 2 skipped), `check:nul-bytes`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check-empty-changeset`, `check-adr-0087-registration`. Reconciliation: `dispatch-gates --ran` reports 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN, all with recorded exit codes. `overlap-check`: merges cleanly with origin/main. `check:new-line-citations` (ui): 0 new citations. The full app-shell suite was not run locally; it is left to CI's Test UI. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CbSphdunq2aJq7ktuY --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c05a8a0 commit 3e7feed

3 files changed

Lines changed: 294 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(console): the AI chat page's publish warning about failed sample data shows the pack's sentence, never the seed loader's text
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Publishing from the AI chat page warns "Published, but some sample data failed to load." when a seed fails to load. The detail under that title printed the seed loader's own engine text (for example "seed apply stopped at the seed for object …"), and when the loader reported only per-record rows it printed "[object Object]". It now shows the sentence the chat's publish-health line already shows for the same failure (`chatbot.build.health.seedFailed`, from the locale pack), the same sentence *Publish all* shows. The loader's text and its error rows go to the browser console (`console.warn`), never the toast.
11+
12+
No locale keys, props or exports change.

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3206,17 +3206,23 @@ export function ChatPane({
32063206
}
32073207
// Surface a seed-load problem (reported under `seedApplied`, never
32083208
// thrown) so "Published!" can't hide silently empty tables.
3209+
//
3210+
// The toast says the pack's sentence, the one the chat's
3211+
// publish-health line says for the same failure (objectstack#32984:
3212+
// user-facing text is the customer sentence). The loader's `error`
3213+
// (engine text) and `errors[]` (structured rows) are for whoever
3214+
// repairs the seed: they go to the console whole, never the toast,
3215+
// and stay in the health line's technical details.
32093216
const seedApplied = payload?.seedApplied;
32103217
if (seedApplied && seedApplied.success === false) {
3218+
console.warn('[app-shell] Published, but the seed failed to load:', {
3219+
packageId,
3220+
error: seedApplied.error,
3221+
errors: seedApplied.errors,
3222+
});
32113223
toast.warning(
32123224
t('console.ai.seedWarn', { defaultValue: 'Published, but some sample data failed to load.' }),
3213-
{
3214-
description:
3215-
seedApplied.error ??
3216-
(Array.isArray(seedApplied.errors) && seedApplied.errors.length
3217-
? String(seedApplied.errors[0])
3218-
: undefined),
3219-
},
3225+
{ description: t('chatbot.build.health.seedFailed', { defaultValue: 'Sample data failed to load.' }) },
32203226
);
32213227
} else {
32223228
toast.success(t('console.ai.publishOk', { defaultValue: 'Published — objects are now live.' }));
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#35303 — the AI chat page's publish warns about a failed seed in
11+
* the customer's words, never in the seed loader's.
12+
*
13+
* A failed seed answers `seedApplied.success === false`. Its `error` is the
14+
* loader's own engine text, and an `errors[]` entry is a structured row
15+
* (`{ row, reason }`), both written for whoever repairs the seed. The toast's
16+
* description is the pack sentence `chatbot.build.health.seedFailed` (the
17+
* sentence the chat's publish-health line says for the same failure,
18+
* objectstack#32984); the engine text and the row reach `console.warn`
19+
* whole, never the toast.
20+
*
21+
* Real: `AiChatPage`'s publish handler, `useMetadataClient` and its client,
22+
* the publish-health reader, and `I18nProvider` with the shipped `en` and
23+
* `zh-Hans` packs. Stubbed: `sonner` (the terminal sink), `globalThis.fetch`
24+
* (the server), `console.warn` (observed), and the chat tree, reduced to the
25+
* button that fires `onPublishDrafts`.
26+
*
27+
* Its own file: `I18nProvider` installs a module-level i18next global, which
28+
* would leak into the default-value `t` the sibling publish pin reads.
29+
*/
30+
31+
import '@testing-library/jest-dom/vitest';
32+
import React from 'react';
33+
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
34+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
35+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
36+
37+
const PACKAGE_ID = 'app.k9qk';
38+
39+
vi.mock('sonner', () => ({
40+
toast: {
41+
warning: vi.fn(),
42+
error: vi.fn(),
43+
success: vi.fn(),
44+
info: vi.fn(),
45+
message: vi.fn(),
46+
dismiss: vi.fn(),
47+
},
48+
Toaster: () => null,
49+
}));
50+
51+
/** What the chat card's Publish handed back. */
52+
let publishResult: unknown;
53+
54+
vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
55+
const actual = await importOriginal<Record<string, unknown>>();
56+
return {
57+
...actual,
58+
useAiModels: () => ({ models: [], defaultModelId: undefined }),
59+
useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }),
60+
useObjectChat: () => ({
61+
messages: [],
62+
isLoading: false,
63+
error: undefined,
64+
sendMessage: vi.fn(),
65+
stop: vi.fn(),
66+
reload: vi.fn(),
67+
clear: vi.fn(),
68+
setMessages: vi.fn(),
69+
}),
70+
ChatbotEnhanced: (props: Record<string, unknown>) => {
71+
const onPublishDrafts = props.onPublishDrafts as ((packageId: string) => Promise<unknown>) | undefined;
72+
return (
73+
<button
74+
type="button"
75+
data-testid="card-publish"
76+
onClick={() => {
77+
void (async () => {
78+
publishResult = await onPublishDrafts?.(PACKAGE_ID);
79+
})();
80+
}}
81+
>
82+
publish
83+
</button>
84+
);
85+
},
86+
};
87+
});
88+
vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
89+
...(await importOriginal<typeof import('@object-ui/plugin-chatbot/core')>()),
90+
useAgents: () => ({
91+
agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }],
92+
loading: false,
93+
error: undefined,
94+
refetch: vi.fn(),
95+
}),
96+
}));
97+
98+
vi.mock('@object-ui/auth', async (importOriginal) => {
99+
const actual = await importOriginal<Record<string, unknown>>();
100+
return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) };
101+
});
102+
vi.mock('../../../providers/MetadataProvider', async (importOriginal) => {
103+
const actual = await importOriginal<Record<string, unknown>>();
104+
return { ...actual, useMetadata: () => ({ apps: [] }) };
105+
});
106+
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
107+
const actual = await importOriginal<Record<string, unknown>>();
108+
return { ...actual, useAdapter: () => null };
109+
});
110+
vi.mock('../ConversationsSidebar', () => ({
111+
ConversationsSidebar: () => <div data-testid="sidebar" />,
112+
}));
113+
114+
import { toast } from 'sonner';
115+
import { I18nProvider, useObjectTranslation } from '@object-ui/i18n';
116+
import { en, zh } from '@object-ui/i18n/locales';
117+
import { AiChatPage } from '../AiChatPage';
118+
119+
window.matchMedia = ((query: string) => ({
120+
matches: false,
121+
media: query,
122+
onchange: null,
123+
addEventListener: () => {},
124+
removeEventListener: () => {},
125+
addListener: () => {},
126+
removeListener: () => {},
127+
dispatchEvent: () => false,
128+
})) as unknown as typeof window.matchMedia;
129+
130+
const PACK = { en, 'zh-Hans': zh } as const;
131+
type Locale = keyof typeof PACK;
132+
const LOCALES: Locale[] = ['en', 'zh-Hans'];
133+
134+
/** The seed loader's own text, as the runtime words a stopped seed apply. */
135+
const ENGINE_TEXT = "seed apply stopped at the seed for object 'crm_task': Reference not found: owner = \"ann\"";
136+
/** One per-record failure as the loader reports it: a structured row, no `error`. */
137+
const ROW_ERROR = { row: 3, reason: 'Reference not found: owner = "ann"' };
138+
/** The prefix of the handler's console line, so other warnings never count. */
139+
const SEED_LOG_PREFIX = '[app-shell] Published, but the seed failed to load';
140+
141+
/** A published batch carrying the given `seedApplied`, inside the dispatcher's envelope. */
142+
function batchWithSeed(seedApplied: Record<string, unknown>) {
143+
return {
144+
success: true,
145+
data: {
146+
success: true,
147+
outcome: 'published',
148+
publishedCount: 1,
149+
failedCount: 0,
150+
published: [{ type: 'seed', name: 'crm_sample_rows' }],
151+
failed: [],
152+
seedApplied,
153+
},
154+
};
155+
}
156+
157+
let batchBody: unknown;
158+
let publishPosts = 0;
159+
let warnSpy: MockInstance<typeof console.warn>;
160+
161+
function json(body: unknown) {
162+
return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
163+
}
164+
165+
beforeEach(() => {
166+
vi.clearAllMocks();
167+
batchBody = undefined;
168+
publishPosts = 0;
169+
publishResult = undefined;
170+
window.localStorage.clear();
171+
window.sessionStorage.clear();
172+
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
173+
vi.stubGlobal(
174+
'fetch',
175+
vi.fn(async (input: unknown) => {
176+
const url = String(input);
177+
if (url.includes('/publish-drafts')) {
178+
publishPosts += 1;
179+
return json(batchBody);
180+
}
181+
return json({ success: true, data: [] });
182+
}) as unknown as typeof fetch,
183+
);
184+
});
185+
186+
afterEach(() => {
187+
cleanup();
188+
warnSpy.mockRestore();
189+
vi.unstubAllGlobals();
190+
});
191+
192+
function LanguageProbe() {
193+
const { language } = useObjectTranslation();
194+
return <div data-testid="language">{language}</div>;
195+
}
196+
197+
/** Render the build surface in `locale` and fire a draft card's Publish. */
198+
async function publishFromAChatCardIn(locale: Locale): Promise<void> {
199+
render(
200+
<I18nProvider config={{ defaultLanguage: locale, detectBrowserLanguage: false }}>
201+
<LanguageProbe />
202+
<MemoryRouter initialEntries={['/ai/build']}>
203+
<Routes>
204+
<Route path="/ai/:agent" element={<AiChatPage />} />
205+
</Routes>
206+
</MemoryRouter>
207+
</I18nProvider>,
208+
);
209+
await waitFor(() => expect(screen.getByTestId('language')).toHaveTextContent(locale));
210+
fireEvent.click(await screen.findByTestId('card-publish'));
211+
await waitFor(() => expect(publishPosts).toBe(1));
212+
await waitFor(() => expect(publishResult).toMatchObject({ ok: true }));
213+
}
214+
215+
/** The one warning the publish raised: its title and its detail. */
216+
function seedWarning(): { title: string; description: unknown } {
217+
const warnings = vi.mocked(toast.warning).mock.calls;
218+
expect(warnings).toHaveLength(1);
219+
const [title, opts] = warnings[0] as [string, { description?: unknown }];
220+
return { title, description: opts?.description };
221+
}
222+
223+
/** The handler's console lines for a failed seed, with their payloads. */
224+
function seedLogs(): unknown[][] {
225+
return warnSpy.mock.calls.filter((args) => typeof args[0] === 'string' && args[0].startsWith(SEED_LOG_PREFIX));
226+
}
227+
228+
describe('AI chat publish warns about a failed seed in the pack’s sentence (objectstack#35303)', () => {
229+
it.each(LOCALES)('%s: a seed that failed with engine text shows the pack sentence', async (locale) => {
230+
batchBody = batchWithSeed({ success: false, inserted: 0, updated: 0, error: ENGINE_TEXT });
231+
await publishFromAChatCardIn(locale);
232+
233+
const { title, description } = seedWarning();
234+
expect(title).toBe(PACK[locale].console.ai.seedWarn);
235+
expect(description).toBe(PACK[locale].chatbot.build.health.seedFailed);
236+
expect(String(description)).not.toContain(ENGINE_TEXT);
237+
expect(toast.success).not.toHaveBeenCalled();
238+
239+
const logs = seedLogs();
240+
expect(logs).toHaveLength(1);
241+
expect(logs[0][1]).toMatchObject({ packageId: PACKAGE_ID, error: ENGINE_TEXT });
242+
});
243+
244+
it.each(LOCALES)('%s: a seed that failed with a structured row and no error shows the pack sentence', async (locale) => {
245+
batchBody = batchWithSeed({ success: false, inserted: 0, updated: 0, errors: [ROW_ERROR] });
246+
await publishFromAChatCardIn(locale);
247+
248+
const { title, description } = seedWarning();
249+
expect(title).toBe(PACK[locale].console.ai.seedWarn);
250+
expect(description).toBe(PACK[locale].chatbot.build.health.seedFailed);
251+
expect(String(description)).not.toContain('[object Object]');
252+
253+
const logs = seedLogs();
254+
expect(logs).toHaveLength(1);
255+
expect(logs[0][1]).toMatchObject({ packageId: PACKAGE_ID, errors: [ROW_ERROR] });
256+
});
257+
});
258+
259+
describe('control: a seed that loaded reads as before (objectstack#35303)', () => {
260+
it.each(LOCALES)('%s: a seed that loaded raises no warning and logs nothing', async (locale) => {
261+
batchBody = batchWithSeed({ success: true, inserted: 2, updated: 0 });
262+
await publishFromAChatCardIn(locale);
263+
264+
expect(toast.warning).not.toHaveBeenCalled();
265+
expect(seedLogs()).toEqual([]);
266+
expect(vi.mocked(toast.success).mock.calls).toHaveLength(1);
267+
expect(vi.mocked(toast.success).mock.calls[0][0]).toBe(PACK[locale].console.ai.publishOk);
268+
});
269+
});

0 commit comments

Comments
 (0)