Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions apps/web/lib/api/controllers/users/userId/updateUserById.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,19 +235,27 @@ export default async function updateUserById(
data: {
name: data.name,
username: data.username,
// Fields a settings section does not send stay as they are
image:
data.image && data.image.startsWith("http")
? data.image
: data.image
? `uploads/avatar/${userId}.jpg`
: "",
data.image === undefined
? undefined
: data.image && data.image.startsWith("http")
? data.image
: data.image
? `uploads/avatar/${userId}.jpg`
: "",
collectionOrder: data.collectionOrder?.filter(
(value, index, self) => self.indexOf(value) === index
),
aiTaggingMethod: data.aiTaggingMethod,
aiPredefinedTags: data.aiPredefinedTags,
aiTagExistingLinks: data.aiTagExistingLinks,
locale: i18n.locales.includes(data.locale || "") ? data.locale : "en",
locale:
data.locale === undefined
? undefined
: i18n.locales.includes(data.locale)
? data.locale
: "en",
archiveAsScreenshot: data.archiveAsScreenshot,
archiveAsMonolith: data.archiveAsMonolith,
archiveAsPDF: data.archiveAsPDF,
Expand Down
124 changes: 124 additions & 0 deletions apps/web/lib/api/updateUserPartial.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import bcrypt from "bcrypt";

// A settings section saves only its own fields (plus id, username, email).
// Fields it leaves out, like the language and the avatar, must stay as they
// are (#1915, #1779). Against a real database (DATABASE_URL).

vi.mock("next-i18next.config", () => ({
i18n: { locales: ["en", "de"] },
}));

vi.mock("@linkwarden/filesystem", () => ({
createFile: vi.fn(),
createFolder: vi.fn(),
removeFile: vi.fn(),
removeFolder: vi.fn(),
}));

let prisma: typeof import("@linkwarden/prisma").prisma;
let updateUserById: typeof import("./controllers/users/userId/updateUserById").default;

const run = `${Date.now().toString(36)}${Math.random()
.toString(36)
.slice(2, 6)}`;
const createdUserIds: number[] = [];

async function createAccount(label: string) {
const user = await prisma.user.create({
data: {
name: label,
username: `${label}-${run}`.toLowerCase(),
password: await bcrypt.hash("Corr3ct-horse", 4),
locale: "de",
image: "uploads/avatar/1.jpg",
},
});
createdUserIds.push(user.id);
return user;
}

// What the preference page sends: the base payload plus the section's fields
const section = (
user: { id: number; username: string | null; email: string | null },
fields: Record<string, unknown>
) =>
({
id: user.id,
username: user.username,
email: user.email,
...fields,
}) as any;

const stored = (id: number) => prisma.user.findUniqueOrThrow({ where: { id } });

describe("saving one settings section, with a real database", () => {
beforeAll(async () => {
vi.stubEnv("EMAIL_FROM", "");
vi.stubEnv("EMAIL_SERVER", "");
({ prisma } = await import("@linkwarden/prisma"));
updateUserById = (await import("./controllers/users/userId/updateUserById"))
.default;
});

afterAll(async () => {
vi.unstubAllEnvs();
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
});

it("keeps the language and the avatar when saving the AI tagging method", async () => {
const user = await createAccount("ai-section");

const result = await updateUserById(
user.id,
section(user, { aiTaggingMethod: "GENERATE", aiTagExistingLinks: false })
);

expect(result.status).toBe(200);
expect((result.response as any).locale).toBe("de");
expect((result.response as any).image).toMatch(/^uploads\/avatar\/1\.jpg\?/);
const after = await stored(user.id);
expect(after.aiTaggingMethod).toBe("GENERATE");
expect(after.locale).toBe("de");
expect(after.image).toBe("uploads/avatar/1.jpg");
});

it("keeps the language and the avatar when saving the archive settings", async () => {
const user = await createAccount("archive-section");

const result = await updateUserById(
user.id,
section(user, { archiveAsPDF: false, archiveAsScreenshot: false })
);

expect(result.status).toBe(200);
const after = await stored(user.id);
expect(after.archiveAsPDF).toBe(false);
expect(after.locale).toBe("de");
expect(after.image).toBe("uploads/avatar/1.jpg");
});

it("still changes the language when the account page sends one", async () => {
const user = await createAccount("account-language");

await updateUserById(user.id, section(user, { locale: "en" }));

expect((await stored(user.id)).locale).toBe("en");
});

it("still falls back to English for an unknown language", async () => {
const user = await createAccount("unknown-language");

await updateUserById(user.id, section(user, { locale: "xx" }));

expect((await stored(user.id)).locale).toBe("en");
});

it("still removes the avatar when the account page sends an empty one", async () => {
const user = await createAccount("remove-avatar");

await updateUserById(user.id, section(user, { image: "" }));

expect((await stored(user.id)).image).toBe("");
});
});
23 changes: 23 additions & 0 deletions factory/evidence/tests/helpers.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect } from '../scripts/sandbox.mjs';

// Seeded by factory/mocks/ollama/seed.sql (sandbox only)
export const USER = { username: 'tester', password: 'factory-local-only' };

// Fast login for regression specs (the proof types it visibly instead)
export async function login(page) {
await page.goto('/login');
await page.getByTestId('username-input').fill(USER.username);
await page.getByTestId('password-input').fill(USER.password);
await page.getByTestId('submit-login-button').click();
await page.waitForURL('**/dashboard');
}

// The account as the server stores it, read with the page's session
export async function storedUser(page) {
const res = await page.request.get('/api/v1/users/me');
expect(res.ok()).toBeTruthy();
return (await res.json()).response;
}

export const radio = (page, label) =>
page.locator('label').filter({ hasText: label }).locator('input[type="radio"]');
86 changes: 86 additions & 0 deletions factory/evidence/tests/proof-flow.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import path from 'node:path';
import fs from 'node:fs/promises';
import { test, expect } from '../scripts/sandbox.mjs';
import { createProofSession, highlightLocator, highlightAndClick, humanType } from '../scripts/proof-helpers.mjs';
import { USER, storedUser, radio } from './helpers.mjs';

// Proof for linkwarden#1915: with the language set to German, saving the AI tagging method
// keeps the UI and the stored language German (before the fix it was reset to English).

const OUT_DIR = process.env.EVIDENCE_OUT || path.resolve('./artifacts');
const SCREENSHOT_DIR = path.join(OUT_DIR, 'screenshots');

test.beforeAll(async () => {
await fs.mkdir(SCREENSHOT_DIR, { recursive: true });
});

test('Level 1 focused proof (#1915): saving AI tagging keeps the language German', async ({ page }) => {
const TOTAL_STEPS = 4;
const session = createProofSession(page, { outDir: OUT_DIR, screenshotDir: SCREENSHOT_DIR });
const aiHeading = page.getByText('KI Einstellungen', { exact: true });
const generate = radio(page, 'Tags automatisch generieren');

await page.goto('/login');
await expect(page.getByTestId('login-form')).toBeVisible();
session.markReady();

// Step 1/4: log in, the account's language is German
await session.beginStep(1, TOTAL_STEPS, 'Log in: account language is German');
await humanType(page, page.getByTestId('username-input'), USER.username);
await humanType(page, page.getByTestId('password-input'), USER.password, { charDelayMs: 20 });
await highlightAndClick(page, page.getByTestId('submit-login-button'));
await page.waitForURL('**/dashboard');
await page.goto('/settings/preference');
await expect(aiHeading).toBeVisible();
await expect(radio(page, 'Deaktiviert')).toBeChecked();
expect((await storedUser(page)).locale).toBe('de');
await highlightLocator(page, aiHeading);
await session.finishStep({
screenshotFile: '01-settings-german.png',
assertion: 'Seeded user (locale "de") sees Settings → Preference in German: "KI Einstellungen", AI tagging "Deaktiviert"',
});

// Step 2/4: change the AI tagging method and save only that section
await session.beginStep(2, TOTAL_STEPS, 'Change AI tagging and save');
await highlightAndClick(page, page.locator('label').filter({ hasText: 'Tags automatisch generieren' }));
await expect(generate).toBeChecked();
const save = page.getByRole('button', { name: 'Änderungen speichern' }).first();
await highlightAndClick(page, save);
await expect(page.getByText('Einstellungen übernommen!')).toBeVisible();
// Nothing left to save in this section once the server took it
await expect(save).toBeDisabled();
await highlightLocator(page, page.locator('label').filter({ hasText: 'Tags automatisch generieren' }));
await session.finishStep({
screenshotFile: '02-ai-tagging-saved.png',
assertion: 'AI tagging set to "Tags automatisch generieren" and saved: the test saw the toast "Einstellungen übernommen!", the section\'s save button is disabled again, the page is still German',
});

// Step 3/4: reload, the page is still German and the server kept both values
await session.beginStep(3, TOTAL_STEPS, 'Reload: still German, AI tagging saved');
await page.reload();
await expect(aiHeading).toBeVisible();
await expect(generate).toBeChecked();
const user = await storedUser(page);
expect(user.locale).toBe('de');
expect(user.aiTaggingMethod).toBe('GENERATE');
await highlightLocator(page, aiHeading);
await highlightLocator(page, page.locator('label').filter({ hasText: 'Tags automatisch generieren' }));
await session.finishStep({
screenshotFile: '03-reload-still-german.png',
assertion: 'After a reload the page is German and the server returns locale "de" with aiTaggingMethod "GENERATE" (before the fix: locale "en", English UI)',
});

// Step 4/4: the account page shows the language unchanged
await session.beginStep(4, TOTAL_STEPS, 'Account settings: language still Deutsch');
await page.goto('/settings/account');
const language = page.locator('select').filter({ has: page.locator('option[value="de"]') });
await expect(language).toHaveValue('de');
await highlightLocator(page, language);
await session.finishStep({
screenshotFile: '04-account-language-de.png',
assertion: 'Settings → Account still has the language "de" selected',
holdEndMs: 2200,
});

await session.saveMetadata();
});
34 changes: 34 additions & 0 deletions factory/evidence/tests/settings-regression.spec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { test, expect } from '../scripts/sandbox.mjs';
import { login, storedUser } from './helpers.mjs';

// #1915 / #1779: a settings section must not reset fields it does not send.

test('archive settings: saving keeps the German UI and stored language (#1779)', async ({ page }) => {
await login(page);
await page.goto('/settings/preference');
await expect(page.getByText('Archiv Einstellungen')).toBeVisible();

const pdf = page.locator('label').filter({ hasText: 'PDF' }).locator('input[type="checkbox"]').first();
await pdf.click();
await page.getByRole('button', { name: 'Änderungen speichern' }).nth(1).click();
await expect(page.getByText('Einstellungen übernommen!')).toBeVisible();

const user = await storedUser(page);
expect(user.locale).toBe('de');
expect(user.archiveAsPDF).toBe(false);
await page.reload();
await expect(page.getByText('Archiv Einstellungen')).toBeVisible();
});

test('account page: changing the language still works', async ({ page }) => {
await login(page);
await page.goto('/settings/account');
const language = page.locator('select').filter({ has: page.locator('option[value="de"]') });
await expect(language).toHaveValue('de');

await language.selectOption('en');
await page.getByRole('button', { name: 'Änderungen speichern' }).click();
await expect.poll(async () => (await storedUser(page)).locale).toBe('en');
await page.reload();
await expect(page.locator('select').filter({ has: page.locator('option[value="de"]') })).toHaveValue('en');
});
Loading