Skip to content

Commit b3c3acd

Browse files
feat(app-shell): send the console UI language as context.uiLocale on the AI chat request (#34845)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBNgJrQDxaUNx2so1ektgf6A)_ Fixes #34639 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:AI 对话请求的 `body.context` 新增 `uiLocale`,值为控制台当前解析出的界面语言(`useObjectTranslation().language`),其余字段不变。 - **为什么改**:服务端此前只看得到浏览器的 `Accept-Language`,中文提问 + 英文控制台时,回复让用户点「开始搭建」,而计划卡按钮显示的是 "Build it";cloud PR #4815 的 `consoleUiLocaleOf` 读这个键来选按钮文案。 - **风险与回滚**:风险低,只是请求体多一个字符串键,服务端自行校验、不认识就丢弃;回滚即 revert 本 PR,服务端退回按回复语言选文案(今天的行为)。 - **先看**:`ui/packages/app-shell/src/console/ai/AiChatPage.tsx`(`useObjectChat` 的 `body.context` 末尾新增的 `uiLocale: language` 一行);`ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx`。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx`,预期 5 个测试全部通过。 - **需要你做的**:无,席位落地。 ## What changes - `ChatPane` (`AiChatPage.tsx`) already read `const { t, language } = useObjectTranslation()`. The `useObjectChat({ body: { context } })` call now adds `uiLocale: language` beside `activeApp`, `agentName`, `autoPublishAiBuilds`, `packageId` and `surface`. The value is sent as is; there is no client-side normalisation, because the consumer (objectstack-ai/cloud PR #4815, `consoleUiLocaleOf`) validates it. - Console dock: read `ui/packages/app-shell/src/layout/ChatDock.tsx` and `ChatDockConversation.tsx`. The dock does not build its own chat request. It mounts the same `ChatPane`, so this one change covers the dock too. No dock file is edited. The only non-test `useObjectChat(` call sites under `ui/packages` are `AiChatPage.tsx` and the SDUI `plugin-chatbot` renderer, which is not the console's AI chat. - Changeset: `.changeset/34639-ai-chat-ui-locale.md`, `@object-ui/app-shell` patch. ## Tests New file `AiChatPage.uiLocale-34639.test.tsx`. It renders `ChatPane` with a real `I18nProvider` and with `useObjectChat` replaced by an options recorder, the same harness as `AiChatPage.surfaceChipLabel-8219.test.tsx`. The expected value is read from a probe under the same provider, so the pin does not depend on how the provider spells a tag. It checks: 1. `en` / `zh` / `de` consoles: `context.uiLocale` equals the resolved UI language (non-empty string). 2. Chinese thread under an English console versus a Chinese console: each sends its own console's language, and the two values differ. 3. The rest of the context is unchanged: keys are exactly `agentName`, `autoPublishAiBuilds`, `uiLocale` for a pane with no app, package or surface. No shared ChatPane harness file exists under `console/ai/__tests__/`, so the pin is its own card-named file. <details><summary>Targeted run on head 82eed1d (after merging origin/main dfbc316)</summary> ``` pnpm --dir ui exec vitest run --maxWorkers=2 \ packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx \ packages/app-shell/src/console/ai/__tests__/AiChatPage.surfaceChipLabel-8219.test.tsx \ packages/app-shell/src/console/ai/__tests__/AiChatPage.planCardLocale.test.tsx Test Files 3 passed (3) Tests 26 passed (26) pnpm --filter @object-ui/app-shell run type-check (tsc --noEmit && tsc -p tsconfig.test.json) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Ablation (fix committed first; mutation through scripts/ablation-replace.mjs)</summary> Deleted the line `uiLocale: language,` (anchor 1 -> 0, blob 6e4da2c -> e6d51027). The test imports `../AiChatPage` from source, so no build step sits between the mutation and the run. ``` × en console: context.uiLocale is the resolved UI language expected undefined to be 'en' × zh console: context.uiLocale is the resolved UI language expected undefined to be 'zh' × de console: context.uiLocale is the resolved UI language expected undefined to be 'de' × the value follows the console, not the conversation ... expected undefined to be 'en' × the rest of the context is unchanged beside it expected [ 'agentName', 'autoPublishAiBuilds' ] to deeply equal [ 'agentName', …(2) ] Tests 5 failed (5) restore: blob after restore 6e4da2c == blob at HEAD; git diff HEAD empty ``` </details> ## Acceptance notes - PR #34713, which rewrote `AiChatPage.tsx`, merged before this PR opened. The branch merged origin/main (dfbc316) cleanly. `overlap-check` on head 82eed1d reported `VERDICT clean exit 0` (origin/main merges cleanly, 0 overlapping PR heads). - The console's own language resolution (browser vs environment default) is out of scope, as the card says. ## Verification <details><summary>Local gate families on head 82eed1d (dispatch-gates --commands, 38 derived)</summary> - All 38 derived commands exited 0. Exit codes were captured before any pipe and are recorded per command. They include `pnpm --dir ui exec vitest run scripts/` (Tests 5077 passed, 2 skipped), `pnpm check:nul-bytes`, `pnpm check:cross-package-test-inputs`, `pnpm check:test-source-alias`, `pnpm check:type-check-coverage`, `pnpm check:type-check-debt`, `node scripts/check-adr-0087-registration.mjs --base origin/main`, `node scripts/check-empty-changeset.mjs --base origin/main` and `node scripts/check-sdui-manifest.mjs`. - `dispatch-gates --ran`: `38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED`. - Extra runs: `pnpm check:changeset-fixed` (its roster sits under `.changeset/`) exit 0. `pnpm check:new-line-citations` (ui) gave `VERDICT new-cross-file-line-citations: 0 new citation(s)`. - Full repo-wide families, the type-check lanes and `test:repo` belong to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfrh8TiPJf1i2kMSoa)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfrh8TiPJf1i2kMSoa --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6e2838c commit b3c3acd

3 files changed

Lines changed: 164 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
feat(app-shell): the AI chat request carries the console's UI language as `context.uiLocale`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The AI chat pane, on the AI page and in the console dock, now sends the language the console renders in as `context.uiLocale` on every chat request, beside the existing `agentName`, `activeApp`, `packageId` and `surface` keys. Before, the server saw only the browser's `Accept-Language`, so a reply could name a card control (such as the plan card's approve button) in a language the card did not use. The value is the console's resolved language tag, sent as is; the server decides whether to use it. Nothing else in the request changes.

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2050,6 +2050,10 @@ export function ChatPane({
20502050
// transport reads the body per send, so this stays fresh per turn).
20512051
// The console dock sends the page in view too (objectstack#30043).
20522052
...(surfaceContext ? { surface: surfaceContext } : {}),
2053+
// The language this console renders in, so a reply that names a card
2054+
// control names it as the card draws it. Only `Accept-Language` reaches
2055+
// the server otherwise; the server validates the value itself.
2056+
uiLocale: language,
20532057
},
20542058
},
20552059
initialMessages: hydrated,
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#34639 — the AI chat request carries the console's resolved UI
5+
* language as `context.uiLocale`.
6+
*
7+
* The server picks the words a reply uses for a card control (the plan card's
8+
* approve button) from this value; without it the server only sees the
9+
* browser's `Accept-Language`, so a Chinese reply under an English console
10+
* named a button the card never drew.
11+
*
12+
* The value is the language the pane's own translation hook resolves, sent as
13+
* is: the consumer validates it, so no normalisation happens here. The
14+
* expected value is read from a probe under the same provider rather than
15+
* written down, so the pin holds whatever tag the provider resolves.
16+
*
17+
* The pane is rendered for real with `ChatbotEnhanced` and `useObjectChat`
18+
* replaced by recorders, because the options ChatPane hands the chat hook ARE
19+
* the request body under assertion. The console dock mounts this same
20+
* `ChatPane`, so it is covered by the same seam.
21+
*/
22+
23+
import '@testing-library/jest-dom/vitest';
24+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
25+
import { cleanup, render } from '@testing-library/react';
26+
import { MemoryRouter } from 'react-router-dom';
27+
import React from 'react';
28+
29+
/** Options of the last `useObjectChat` call — carries the request `body`. */
30+
let chatOptions: Record<string, unknown> = {};
31+
32+
vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
33+
const actual = await importOriginal<Record<string, unknown>>();
34+
return {
35+
...actual,
36+
ChatbotEnhanced: () => null,
37+
useObjectChat: (options: Record<string, unknown>) => {
38+
chatOptions = options;
39+
return {
40+
messages: [],
41+
isLoading: false,
42+
error: undefined,
43+
sendMessage: vi.fn(),
44+
stop: vi.fn(),
45+
reload: vi.fn(),
46+
clear: vi.fn(),
47+
setMessages: vi.fn(),
48+
};
49+
},
50+
useAiModels: () => ({ models: [], defaultModelId: undefined }),
51+
};
52+
});
53+
54+
vi.mock('../../../providers/MetadataProvider', async (importOriginal) => {
55+
const actual = await importOriginal<Record<string, unknown>>();
56+
return { ...actual, useMetadata: () => ({ apps: [] }) };
57+
});
58+
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
59+
const actual = await importOriginal<Record<string, unknown>>();
60+
return { ...actual, useAdapter: () => null };
61+
});
62+
63+
import { I18nProvider, useObjectTranslation } from '@object-ui/i18n';
64+
import type { AgentDescriptor } from '@object-ui/plugin-chatbot';
65+
import { ChatPane } from '../AiChatPage';
66+
import type { HydratedUIMessage } from '../../../hooks/useChatConversation';
67+
68+
window.matchMedia = ((query: string) => ({
69+
matches: false,
70+
media: query,
71+
onchange: null,
72+
addEventListener: () => {},
73+
removeEventListener: () => {},
74+
addListener: () => {},
75+
removeListener: () => {},
76+
dispatchEvent: () => false,
77+
})) as unknown as typeof window.matchMedia;
78+
79+
/**
80+
* The language the provider resolved, read the way ChatPane reads it, and
81+
* reported from an effect: the lint rule forbids writing an outer variable
82+
* during render, and `render()` flushes effects before it returns.
83+
*/
84+
function LanguageProbe({ onLanguage }: { onLanguage: (language: string | undefined) => void }) {
85+
const { language } = useObjectTranslation();
86+
React.useEffect(() => onLanguage(language), [language, onLanguage]);
87+
return null;
88+
}
89+
90+
const ZH_THREAD = [
91+
{ id: 'm1', role: 'user', parts: [{ type: 'text', text: '帮我做一个客户管理应用' }] },
92+
] as HydratedUIMessage[];
93+
94+
function renderPane(uiLocale: string, initialMessages: HydratedUIMessage[] = []) {
95+
cleanup();
96+
chatOptions = {};
97+
let probedLanguage: string | undefined;
98+
const onLanguage = (language: string | undefined) => {
99+
probedLanguage = language;
100+
};
101+
render(
102+
<I18nProvider config={{ defaultLanguage: uiLocale, detectBrowserLanguage: false }}>
103+
<LanguageProbe onLanguage={onLanguage} />
104+
<MemoryRouter initialEntries={['/ai/build/conv-1']}>
105+
<ChatPane
106+
agents={[{ name: 'build', label: 'Builder' } as unknown as AgentDescriptor]}
107+
agentsLoading={false}
108+
agentsError={undefined}
109+
activeAgent="build"
110+
chatApi="/api/v1/ai/agents/build/chat"
111+
apiBase="/api/v1/ai"
112+
conversationId="conv-1"
113+
initialMessages={initialMessages}
114+
pendingFirstMessageRef={{ current: null }}
115+
onSent={vi.fn()}
116+
onShare={vi.fn()}
117+
/>
118+
</MemoryRouter>
119+
</I18nProvider>,
120+
);
121+
const body = chatOptions.body as { context: Record<string, unknown> };
122+
return { context: body.context, language: probedLanguage };
123+
}
124+
125+
beforeEach(() => window.localStorage.clear());
126+
afterEach(() => cleanup());
127+
128+
describe('AI chat request carries the console UI language as context.uiLocale (objectstack#34639)', () => {
129+
it.each(['en', 'zh', 'de'])('%s console: context.uiLocale is the resolved UI language', (uiLocale) => {
130+
const { context, language } = renderPane(uiLocale);
131+
expect(typeof language).toBe('string');
132+
expect(language).not.toBe('');
133+
expect(context.uiLocale).toBe(language);
134+
});
135+
136+
it('the value follows the console, not the conversation: a Chinese thread under an English console sends the English tag', () => {
137+
const english = renderPane('en', ZH_THREAD);
138+
const chinese = renderPane('zh', ZH_THREAD);
139+
expect(english.context.uiLocale).toBe(english.language);
140+
expect(chinese.context.uiLocale).toBe(chinese.language);
141+
// Discriminating half: the same thread, two consoles, two values.
142+
expect(english.context.uiLocale).not.toBe(chinese.context.uiLocale);
143+
});
144+
145+
it('the rest of the context is unchanged beside it', () => {
146+
const { context } = renderPane('en');
147+
expect(context.agentName).toBe('build');
148+
expect(Object.keys(context).sort()).toEqual(['agentName', 'autoPublishAiBuilds', 'uiLocale']);
149+
});
150+
});

0 commit comments

Comments
 (0)