Skip to content

Commit 58e1a3b

Browse files
fix(auth, console): saving your profile keeps the page on screen and shows its confirmation (#36984)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBDHJBvzScLgkhKgms97sNuU)_ repo:objectstack#3 · os-support-ai · session_01WGufzhoBbwh8URjwQHde8v Fixes #36972 Clause-②: no Metadata-protocol: none Tests (final head `3147c224723`): `@object-ui/auth` full suite (50 files / 523 tests) + `type-check`; `ProfilePage*` suites of `@object-ui/console` (5 files / 47 tests) + `type-check`; derived gate families listed under Verification. Full `Test UI` is CI's. ## 维护者速读 - 用户在个人资料页保存姓名(或更换头像)后,页面不再闪白重载,「个人资料已更新」的提示会留在卡片上;在语言卡片保存后,即使界面语言随之切换,也会弹出「语言偏好已更新」的提示。 - 修的是账户应用的个人资料页,替使用控制台的每一位用户解决「点了保存却毫无反馈」的问题。 - 若出错,最坏情况是保存后页面右上角的姓名或头像要等下次刷新会话才与服务器完全一致;改动只在两个前端包内,可以直接撤回。 - 无。 ## What changes - **Root cause (name card).** `useAuth().updateUser` installed the answer of better-auth's `POST /update-user` as the session user. better-auth 1.7.12 answers that endpoint with `{ status: true }` (its route source returns exactly that, read in this tree's `node_modules`), not the user. For a moment the session user had no `id`, `name` or `email`: the header showed "?" / "User", the console's `/auth/me/permissions` request key (`user.id` + org) went from defined to `undefined`, and `MePermissionsProvider` swapped its children for the loading fallback and mounted them again. That is the blank `main`, the refetch burst the card lists, and the lost `saved` state. `updateUser` now keeps the same user and spreads the written fields over it (`ui/packages/auth/src/AuthProvider.tsx`), which is how better-auth builds the stored row server-side. The identity never changes, so nothing keyed on it remounts. This is candidate (c) from the dispatch: stop the needless remount at its source. **The page no longer blanks** on a name save, and the inline "Profile updated successfully." alert stays. The avatar upload and remove paths call `updateUser` too and get the same fix. - **Language card.** A save that changes the interface language remounts the page by design: the signed-in user's locale reader applies the new `sys_user.locale` and the console shell remounts its metadata subtree under `key={language}`. That shell behaviour is left as it is, since it is how server-resolved labels relabel. The card now also confirms with `toast.success` (sonner, the console's toast, with the existing `profile.language.saved` key and a stable toast id), and the console toaster is mounted above that key. **The page still remounts on a language change** (by design), and the confirmation survives it. A save that does not change the UI language shows the inline alert as before, plus the toast. - One changeset: `@object-ui/auth` and `@object-ui/console`, both published (neither is `private`), both `patch`. ## Tests - `AuthProvider.test.tsx`, new describe "updateUser keeps the signed-in identity": the client double answers `{ status: true }`, the real server's shape. A child keyed on `user?.id` (as the console keys its permissions answer) must not remount, the clicked button must stay in the document, `id`/`email` kept, `name` updated. - `ProfilePage.language.test.tsx`, new describe "the language save confirms after a language remount": a real sonner `Toaster` outside a subtree keyed on the language. (1) A write whose settling switches the key: the old select leaves the document, a new card mounts, and "Language preference updated." is on screen inside `[data-sonner-toaster]`. (2) Control: a save with no language change. The same select stays, and the inline `role=alert` carries the sentence. ## Acceptance notes - Reproduction on main: the dispatch asked for a code-path repro. The chain above was read on `144d368eac1`. The ablation leg of the AuthProvider pin restores main's semantics (installs the client's answer as the user) and fails with `expected 'undefined' to be 'Grace'`, so the remount mechanism (identity lost) is live on main. - `createAuthClient().updateUser` still declares `Promise<AuthUser>` while the server answers `{ status: true }`. Its only consumer, the provider, no longer reads that value, so this PR does not change the exported `AuthClient` type. Changing it is a published-type change. Noted here, not filed: after this PR it has no consumer. - The existing `createAuthClient.test.ts` case "updateUser sends POST to /update-user and returns user" mocks a `{ user }` body the server never sends. Left untouched (outside this card's file surface). - Sibling #36971 edits the same `ProfilePage.tsx` (the Language card's description and the component comment). This PR does not touch those lines. `git merge-tree` against `origin/claude/issue-36971-profile-language-one-setting` is clean. The new test describe sits mid-file so both branches' appended describes do not collide. ## Verification Two-minute check: open Account → Profile, change the name, click **Save changes**. The header keeps the avatar and name, the page does not flash, and "Profile updated successfully." stays under the card title. Then pick a different interface language in the Language card and click **Save**. The page relabels, and a "Language preference updated." toast shows at the top right. Files to read first, by risk: `ui/packages/auth/src/AuthProvider.tsx` (the `updateUser` callback), `ui/apps/console/src/pages/system/ProfilePage.tsx` (the `toast.success` in `LanguageCard`'s `handleSave`). <details><summary>Ablations (fix committed first; restore proven by blob == HEAD and empty git diff HEAD)</summary> - AuthProvider: `setUser((prev) => (prev ? { ...prev, ...data } : prev));` replaced with installing the client's answer. Pin red: `AssertionError: expected 'undefined' to be 'Grace'`, 1 failed. Restored: blob `8ea37fc238ba` == HEAD. - ProfilePage: the `toast.success(...)` call neutralised. Remount pin red: `Unable to find an element with the text: Language preference updated.`. The control stayed green (1 failed / 1 passed). Restored: blob `282c6749015e` == HEAD. </details> <details><summary>Local gates</summary> On head `3147c224723`, exit codes captured before any pipe: - `node scripts/pm/dispatch-gates.mjs --commands` derived 38 families. All 38 ran locally: 37 exited 0 on the first pass. `pnpm check:query-options-erasure` hit my 300 s wrapper timeout (124) and exited 0 on a 580 s re-run ("ratchet holds: … none new"). `pnpm --dir ui exec vitest run scripts/` passed under the verify lock: 172 files passed, 2 skipped; 5129 tests passed. - `--ran` reconciliation: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED". - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0`. `git merge-tree` against the #36971 branch: clean. - CI families (Lint, Type Check UI, Test UI, Build & E2E UI and the rest) are read from this PR's check-runs, not re-run locally. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzhoBbwh8URjwQHde8v --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 84b1e0c commit 58e1a3b

5 files changed

Lines changed: 194 additions & 4 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/auth': patch
3+
'@object-ui/console': patch
4+
---
5+
6+
fix(auth, console): saving your name on the profile page keeps the page on screen and shows "Profile updated successfully."; a language save that changes the interface language still confirms
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
`useAuth().updateUser` (`@object-ui/auth`) installed the answer of better-auth's `POST /update-user` as the session user. That endpoint answers `{ status: true }`, not the user, so for a moment the signed-in user had no `id`, `name` or `email`: the header showed "?" and "User", and every consumer keyed on the identity dropped its children and mounted them again. In the console the page went blank, its data was read again, and the profile card's success alert, which is local state, was lost. `updateUser` now keeps the same user and applies the fields it wrote to it, the way better-auth builds the stored row. The page is not remounted, and the alert stays. The avatar upload and remove, which call `updateUser` too, no longer blank the page either.
12+
13+
The profile page's Language card (`@object-ui/console`) also confirms a save with a toast. A save that changes the interface language remounts the page under the console shell's language key, by design, and that remount took the card's inline alert with it. The console's toaster sits above that key, so the toast stays. A save that does not change the interface language shows the inline alert as before, and the toast beside it.
14+
15+
Nothing to migrate.

‎ui/apps/console/src/pages/system/ProfilePage.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
SelectValue,
3737
} from '@object-ui/components';
3838
import { useUpload } from '@object-ui/fields';
39+
import { toast } from 'sonner';
3940
import { ConsolePageHeader } from '@object-ui/app-shell';
4041
import { resolveBuiltInLanguage, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
4142
import { useAdapter, extractFieldErrors, extractWriteErrorMessage } from '@object-ui/react';
@@ -686,6 +687,15 @@ function LanguageCard({ userId }: LanguageCardProps) {
686687
});
687688
setStored(choice);
688689
setSaved(true);
690+
// The inline alert above is local state, and a save that changes the
691+
// interface language loses it: the signed-in user's locale reader
692+
// applies the new column to the UI language, and the console shell
693+
// remounts every page under `key={language}` (objectstack#36972). The
694+
// console's toaster sits above that key, so the same sentence is also a
695+
// toast, which the remount does not take away.
696+
toast.success(t('profile.language.saved', { defaultValue: 'Language preference updated.' }), {
697+
id: 'profile-language-saved',
698+
});
689699
} catch (err) {
690700
// A malformed tag comes back as `400 VALIDATION_FAILED` carrying
691701
// `{ field: 'locale', code: 'invalid_format' }` and a localized message.

‎ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,10 @@
5454
* assertions are about the WRITE and not merely about something rendering.
5555
*/
5656

57-
import { describe, expect, it, vi, beforeEach } from 'vitest';
58-
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
57+
import React from 'react';
58+
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
59+
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
60+
import { Toaster, toast } from 'sonner';
5961
import { normaliseClientError } from '@object-ui/data-objectstack';
6062

6163
const { user, updateUser, findOne, update, offerable, appContent, writable } = vi.hoisted(() => ({
@@ -275,6 +277,86 @@ describe('ProfilePage — my language (objectui#7501)', () => {
275277
});
276278
});
277279

280+
/**
281+
* The language save's confirmation survives the remount a language change
282+
* causes (objectstack#36972).
283+
*
284+
* Saving `sys_user.locale` reaches the signed-in user's locale reader through
285+
* the data-invalidation bus; when the new value changes the interface
286+
* language, the console shell remounts every page under `key={language}`, and
287+
* the card's inline alert — local state — goes with it. The confirmation is
288+
* also a toast, and the console's toaster sits above that key. The harness
289+
* below draws the same shape: a real sonner `Toaster` outside a subtree keyed
290+
* on the language, and a write whose settling changes that key.
291+
*/
292+
describe('ProfilePage — the language save confirms after a language remount (objectstack#36972)', () => {
293+
const shell = { switchLanguage: (_next: string) => {} };
294+
295+
function Shell() {
296+
const [language, setLanguage] = React.useState('en');
297+
shell.switchLanguage = setLanguage;
298+
return (
299+
<>
300+
<Toaster />
301+
<div key={language} data-testid="keyed-subtree">
302+
<ProfilePage />
303+
</div>
304+
</>
305+
);
306+
}
307+
308+
beforeEach(() => {
309+
vi.clearAllMocks();
310+
user.value = { id: 'usr_1', name: 'Ada', email: 'ada@example.com' };
311+
offerable.value = ['en', 'zh', 'ja'];
312+
appContent.value = null;
313+
writable.value = true;
314+
findOne.mockResolvedValue({ id: 'usr_1' });
315+
update.mockResolvedValue({});
316+
});
317+
318+
afterEach(() => {
319+
cleanup();
320+
toast.dismiss();
321+
});
322+
323+
it('a save that changes the interface language still shows its confirmation, after the remount', async () => {
324+
// The write settles, and THEN the language changes, as the bus orders it.
325+
update.mockImplementation(async () => {
326+
setTimeout(() => shell.switchLanguage('ja'), 0);
327+
return {};
328+
});
329+
render(<Shell />);
330+
const select = await screen.findByTestId('profile-language-select');
331+
332+
await pick(select, '日本語');
333+
fireEvent.submit(select.closest('form')!);
334+
335+
// The remount happened: the select that was used is gone, a new card stands.
336+
await waitFor(() => expect(document.contains(select)).toBe(false));
337+
await screen.findByTestId('profile-language-select');
338+
// The confirmation is still on screen, in the toaster above the key.
339+
const confirmation = await screen.findByText('Language preference updated.');
340+
expect(confirmation.closest('[data-sonner-toaster]')).not.toBeNull();
341+
});
342+
343+
it('control: a save that leaves the interface language alone shows its confirmation too', async () => {
344+
render(<Shell />);
345+
const select = await screen.findByTestId('profile-language-select');
346+
347+
await pick(select, 'English');
348+
fireEvent.submit(select.closest('form')!);
349+
350+
await waitFor(() => expect(update).toHaveBeenCalledWith('sys_user', 'usr_1', { locale: 'en' }));
351+
await waitFor(() =>
352+
expect(screen.getAllByText('Language preference updated.').length).toBeGreaterThan(0),
353+
);
354+
// No remount: the same select, and the card's own inline alert beside the toast.
355+
expect(document.contains(select)).toBe(true);
356+
expect(screen.getByRole('alert')).toHaveTextContent('Language preference updated.');
357+
});
358+
});
359+
278360
describe('ProfilePage — a stored spelling of a table language (objectstack#30514)', () => {
279361
beforeEach(() => {
280362
vi.clearAllMocks();

‎ui/packages/auth/src/AuthProvider.tsx‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -546,8 +546,19 @@ export function AuthProvider({
546546
async (data: Partial<AuthUser>) => {
547547
setError(null);
548548
try {
549-
const updated = await client.updateUser(data);
550-
setUser(updated);
549+
await client.updateUser(data);
550+
// The write's answer is NOT the user: better-auth's `/update-user`
551+
// answers `{ status: true }`. Installed as the session user, it was a
552+
// user with no `id`, `name` or `email` until the rotation re-read below
553+
// landed, and every consumer keyed on the identity (the console's
554+
// `/auth/me/permissions` request key among them) dropped its children
555+
// and remounted them: the page blanked and lost its local state, the
556+
// profile card's "saved" confirmation included (objectstack#36972).
557+
// So the same user keeps its identity and takes the fields it just
558+
// wrote, which is how better-auth itself builds the stored row
559+
// (the session user spread with the written fields). A later
560+
// re-resolution (`loadSession`) replaces it with the server's copy.
561+
setUser((prev) => (prev ? { ...prev, ...data } : prev));
551562
} catch (err) {
552563
const authError = err instanceof Error ? err : new Error(String(err));
553564
setError(authError);

‎ui/packages/auth/src/__tests__/AuthProvider.test.tsx‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,3 +621,75 @@ describe('a 401 on an API call re-checks the session (objectstack#32138)', () =>
621621
expect(screen.getByTestId('authenticated').textContent).toBe('false');
622622
});
623623
});
624+
625+
/**
626+
* `updateUser` keeps the signed-in identity (objectstack#36972).
627+
*
628+
* better-auth's `/update-user` answers `{ status: true }`, not the user. The
629+
* provider used to install that answer as the session user, so for a moment
630+
* the user had no `id`: every consumer keyed on the identity — the console's
631+
* `/auth/me/permissions` request key is one — dropped its children and
632+
* remounted them, and the profile page lost its "saved" confirmation. The
633+
* double below answers exactly what the server answers.
634+
*/
635+
describe('updateUser keeps the signed-in identity (objectstack#36972)', () => {
636+
let mounts = 0;
637+
638+
/** Keyed on the user id, the way the console keys its permissions answer. */
639+
function IdentityKeyed() {
640+
const { user } = useAuth();
641+
return <MountCounter key={user?.id ?? 'no-id'} />;
642+
}
643+
644+
function MountCounter() {
645+
const { user, updateUser } = useAuth();
646+
React.useEffect(() => {
647+
mounts += 1;
648+
}, []);
649+
return (
650+
<div>
651+
<span data-testid="u-id">{String(user?.id)}</span>
652+
<span data-testid="u-name">{String(user?.name)}</span>
653+
<span data-testid="u-email">{String(user?.email)}</span>
654+
<button type="button" onClick={() => void updateUser({ name: 'Grace' })}>
655+
save
656+
</button>
657+
</div>
658+
);
659+
}
660+
661+
beforeEach(() => {
662+
mounts = 0;
663+
});
664+
665+
it('a name save keeps the id and the email, takes the new name, and remounts nothing', async () => {
666+
const client = createMockClient({
667+
getSession: vi.fn().mockResolvedValue({
668+
user: { id: 'usr_1', name: 'Ada', email: 'ada@example.com' },
669+
session: { token: 'tok' },
670+
}),
671+
updateUser: vi.fn().mockResolvedValue({ status: true }),
672+
});
673+
674+
render(
675+
<AuthProvider authUrl="/api/auth" client={client}>
676+
<IdentityKeyed />
677+
</AuthProvider>,
678+
);
679+
await waitFor(() => expect(screen.getByTestId('u-name').textContent).toBe('Ada'));
680+
const mountsBefore = mounts;
681+
const button = screen.getByRole('button', { name: 'save' });
682+
683+
await act(async () => {
684+
button.click();
685+
});
686+
687+
expect(client.updateUser).toHaveBeenCalledWith({ name: 'Grace' });
688+
expect(screen.getByTestId('u-name').textContent).toBe('Grace');
689+
expect(screen.getByTestId('u-id').textContent).toBe('usr_1');
690+
expect(screen.getByTestId('u-email').textContent).toBe('ada@example.com');
691+
// The same node, not a rebuilt one: nothing keyed on the identity remounted.
692+
expect(document.contains(button)).toBe(true);
693+
expect(mounts).toBe(mountsBefore);
694+
});
695+
});

0 commit comments

Comments
 (0)