From e34760763db3b984ec101a980425bdae3abe474e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 14:36:04 +0000 Subject: [PATCH 1/6] wip: list layout in the browser only; os migrate list-preferences Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- content/docs/ui/views.mdx | 8 +- .../list-preferences.integration.test.ts | 231 ++++++ .../list-preferences.no-auto-run.test.ts | 82 +++ .../src/commands/migrate/list-preferences.ts | 393 ++++++++++ ...igrate.one-shot-family.integration.test.ts | 8 + .../app-shell/src/console/ConsoleShell.tsx | 23 +- .../src/context/ListPreferencesProvider.tsx | 677 ------------------ .../src/context/RecordPreferencesProvider.tsx | 9 +- .../src/context/UserStateAdapters.tsx | 34 +- .../app-shell/src/views/ObjectView.tsx | 27 +- .../app-shell/src/views/listDraftStore.ts | 67 +- .../app-shell/src/views/listFilterStorage.ts | 133 ---- .../app-shell/src/views/listLayoutStore.ts | 321 +++++++++ .../src/views/objectViewListRenderer.tsx | 69 +- .../src/views/objectViewListUrlState.ts | 23 +- .../src/views/objectViewViewCrud.tsx | 31 +- .../app-shell/src/views/personalViews.ts | 4 +- ui/packages/data-objectstack/README.md | 12 +- ui/packages/data-objectstack/src/userState.ts | 10 +- 19 files changed, 1176 insertions(+), 986 deletions(-) create mode 100644 packages/cli/src/commands/migrate/list-preferences.integration.test.ts create mode 100644 packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts create mode 100644 packages/cli/src/commands/migrate/list-preferences.ts delete mode 100644 ui/packages/app-shell/src/context/ListPreferencesProvider.tsx delete mode 100644 ui/packages/app-shell/src/views/listFilterStorage.ts create mode 100644 ui/packages/app-shell/src/views/listLayoutStore.ts diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index e94a8160c38..51f39eb660a 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -634,8 +634,12 @@ whose menu also holds Discard on a narrow list or a phone). - The draft survives opening a record and coming back. Opening another view or object, or reloading the list's page, drops it, so that reload opens the view as it is declared. - Column widths, the row height (density) and the views' order are not a draft: they are - remembered for the user (`sys_user_preference`, key `ui.list.`). A sort, filter, - column order or hidden column an earlier Console stored there no longer applies. + remembered in this browser only, per user and object (localStorage + `list-layout::`). Nothing is sent to the server, another browser or device + opens the view's own layout, and signing out clears them with the rest of this browser's + Console state. Earlier Consoles kept them, with a stored sort and filters, in the user's + `sys_user_preference` row `ui.list.`; nothing reads that row now, and + `os migrate list-preferences` removes such rows. - A link carrying list state (`uf_*` parameters) applies it as a draft, whether it opens in a new tab or in-app (an AI answer's list link, after a reload of the chat page too). - When a session ends, the sign-in page's return link keeps the list's path but never its diff --git a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts new file mode 100644 index 00000000000..a62e003efe4 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts @@ -0,0 +1,231 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import Database from 'better-sqlite3'; +import { isExitSignal } from '../../utils/format.js'; +import MigrateApply from './apply.js'; +import MigrateListPreferences from './list-preferences.js'; + +// Pay the first transform of the dist-resolved workspace deps the commands +// reach through dynamic `import()`s at MODULE LOAD, not inside a case. +import '@objectstack/runtime'; +import '@objectstack/objectql'; + +/** + * `os migrate list-preferences` against a real SQLite database: the step that + * removes the `sys_user_preference` rows keyed `ui.list.`, which no + * Console reads any more (objectstack#35955). + * + * ## The database + * + * The schema this version creates (`os migrate apply --yes` over an empty + * file), with the rows an earlier Console left: three `ui.list.*` rows for two + * users, and two CONTROLS that are never touched — another family's row + * (`ui.record.account`) and a key that only looks alike (`ui.lists`). + * + * ## The cases run in order over ONE database, as an operator runs the steps + * + * 1. a dry run reports the rows and deletes nothing; + * 2. `--apply` without `--export` is refused, and so is an export path that + * already exists — both with nothing deleted; + * 3. `--apply --export` writes the export (owner-only, every row as stored), + * deletes exactly the `ui.list.*` rows, and keeps the controls; + * 4. a re-run finds nothing and writes no export. + */ + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 240_000; + +const RETIRED = [ + { id: 'pref_l1', user_id: 'u1', key: 'ui.list.account', value: '{"viewOrder":["account.all"]}' }, + { id: 'pref_l2', user_id: 'u1', key: 'ui.list.contact', value: '{"perView":{"contact.all":{"rowHeight":"compact"}}}' }, + { id: 'pref_l3', user_id: 'u2', key: 'ui.list.account', value: '{"perView":{"account.all":{"sort":[{"field":"name","order":"desc"}]}}}' }, +]; +const CONTROLS = [ + { id: 'pref_r1', user_id: 'u1', key: 'ui.record.account', value: '{"showEmptyFields":true}' }, + { id: 'pref_x1', user_id: 'u2', key: 'ui.lists', value: '{}' }, +]; + +type Invoke = (argv: string[]) => Promise; +const invoke = (command: { run: (argv: string[], opts: { root: string }) => Promise }): Invoke => + (argv) => command.run(argv, { root: CLI_ROOT }); + +/** Env that would point a command's boot somewhere other than the fixture. */ +const OVERRIDING_ENV = [ + 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', + 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ARTIFACT_PATH', +] as const; + +/** Run one command and capture its JSON document and exit status. */ +async function runJson(command: Invoke, argv: string[]): Promise<{ payload: any; exitCode: number }> { + const savedExit = process.exitCode; + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + let processExit: number | undefined; + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + processExit = code ?? 0; + throw new Error(`__PROCESS_EXIT__:${processExit}`); + }) as never); + let thrownExit: number | undefined; + try { + try { + await command(argv); + } catch (error) { + const trapped = error instanceof Error && error.message.startsWith('__PROCESS_EXIT__'); + if (!trapped && !isExitSignal(error)) throw error; + if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; + } + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); + let payload: any; + try { + payload = JSON.parse(out); + } catch { + payload = { unparsed: out.slice(-400) }; + } + return { payload, exitCode: processExit ?? thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; + } finally { + process.exitCode = savedExit; + vi.restoreAllMocks(); + } +} + +let dir: string; +let dbFile: string; +const savedEnv: Record = {}; +const savedCwd = process.cwd(); + +function withDb(fn: (db: Database.Database) => T, readonly = true): T { + const db = new Database(dbFile, { readonly }); + try { + return fn(db); + } finally { + db.close(); + } +} + +/** Insert a row, filling every other NOT NULL column without a default with a placeholder of its type. */ +function plant(db: Database.Database, table: string, values: Record): void { + const columns = db.prepare(`PRAGMA table_info('${table}')`).all() as Array< + { name: string; type: string; notnull: number; dflt_value: unknown; pk: number } + >; + const row: Record = { ...values }; + for (const c of columns) { + if (c.name in row || !c.notnull || c.dflt_value !== null) continue; + row[c.name] = /INT|BOOL|REAL|NUM/i.test(c.type) ? 0 : `${c.name}-placeholder`; + } + const names = Object.keys(row); + db.prepare(`INSERT INTO "${table}" (${names.map((n) => `"${n}"`).join(', ')}) VALUES (${names.map(() => '?').join(', ')})`) + .run(...names.map((n) => row[n] as never)); +} + +const storedIds = (): string[] => + withDb((db) => (db.prepare("SELECT id FROM sys_user_preference WHERE id LIKE 'pref_%' ORDER BY id").all() as + Array<{ id: string }>).map((r) => r.id)); + +beforeAll(async () => { + for (const key of [...OVERRIDING_ENV, 'NODE_ENV'] as const) savedEnv[key] = process.env[key]; + for (const key of OVERRIDING_ENV) delete process.env[key]; + dir = mkdtempSync(join(tmpdir(), 'os-35955-list-prefs-')); + mkdirSync(join(dir, 'dist'), { recursive: true }); + writeFileSync( + join(dir, 'objectstack.config.ts'), + [ + 'export default {', + " manifest: { id: 'com.example.os35955listprefs', name: 'list prefs', version: '0.0.0', type: 'app' },", + " objects: [{ name: 'os35955_thing', fields: { title: { type: 'text' } } }],", + '};', + '', + ].join('\n'), + ); + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + process.env.NODE_ENV = 'production'; + process.env.OS_TELEMETRY_DB = '0'; + dbFile = join(dir, 'upgraded.db'); + process.chdir(dir); + try { + const created = await runJson(invoke(MigrateApply), ['--database-url', `file:${dbFile}`, '--yes', '--json']); + expect(created.exitCode, JSON.stringify(created.payload).slice(0, 400)).toBe(0); + } finally { + process.chdir(savedCwd); + } + withDb((db) => { + for (const row of [...RETIRED, ...CONTROLS]) plant(db, 'sys_user_preference', row); + }, false); + expect(storedIds()).toEqual([...RETIRED, ...CONTROLS].map((r) => r.id).sort()); +}, CASE_TIMEOUT_MS); + +afterAll(() => { + process.chdir(savedCwd); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } +}); + +beforeEach(() => { process.chdir(dir); }); +afterEach(() => { process.chdir(savedCwd); }); + +describe('os migrate list-preferences removes the ui.list.* preference rows (objectstack#35955)', () => { + const db = () => `file:${dbFile}`; + const run = (argv: string[]) => runJson(invoke(MigrateListPreferences), ['--database-url', db(), ...argv, '--json']); + const all = [...RETIRED, ...CONTROLS].map((r) => r.id).sort(); + + it('1. a dry run reports the rows, users and objects, and deletes nothing', async () => { + const { payload, exitCode } = await run([]); + expect(exitCode).toBe(0); + expect(payload).toMatchObject({ apply: false, rows: 3, users: 2, objects: ['account', 'contact'], deleted: 0, remaining: 3 }); + expect(storedIds()).toEqual(all); + }, CASE_TIMEOUT_MS); + + it('2. --apply is refused without --export, and over an existing export, with nothing deleted', async () => { + const bare = await run(['--apply', '--yes']); + expect(bare.exitCode).toBe(1); + expect(bare.payload.error).toBe('export_required'); + + const taken = join(dir, 'taken.json'); + writeFileSync(taken, 'keep me\n'); + const over = await run(['--apply', '--yes', '--export', taken]); + expect(over.exitCode).toBe(1); + expect(over.payload.error).toBe('export_exists'); + expect(readFileSync(taken, 'utf8')).toBe('keep me\n'); + expect(storedIds()).toEqual(all); + }, CASE_TIMEOUT_MS); + + it('3. --apply --export writes every retired row to an owner-only export, then deletes exactly those rows', async () => { + const exportPath = join(dir, 'list-preferences-export.json'); + const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); + expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0); + expect(payload).toMatchObject({ apply: true, rows: 3, users: 2, deleted: 3, remaining: 0, failures: [] }); + + const doc = JSON.parse(readFileSync(exportPath, 'utf8')); + expect(doc.keyPrefix).toBe('ui.list.'); + expect(doc.rows.map((r: { id: string }) => r.id).sort()).toEqual(RETIRED.map((r) => r.id)); + expect(doc.rows.find((r: { id: string }) => r.id === 'pref_l3')).toMatchObject({ user_id: 'u2', key: 'ui.list.account' }); + if (process.platform !== 'win32') expect(statSync(exportPath).mode & 0o077).toBe(0); + + expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); + }, CASE_TIMEOUT_MS); + + it('4. a re-run finds nothing, writes no export, and keeps the controls', async () => { + const exportPath = join(dir, 'second-export.json'); + const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); + expect(exitCode).toBe(0); + expect(payload).toMatchObject({ rows: 0, deleted: 0, remaining: 0 }); + expect(existsSync(exportPath)).toBe(false); + expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts b/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts new file mode 100644 index 00000000000..4ec27eea355 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts @@ -0,0 +1,82 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Nothing runs `os migrate list-preferences` for you: it deletes stored rows, + * so it stays an operator's command, and no boot, upgrade, migrate or + * lifecycle path may import it. + * + * Every absence below is preceded by the SAME scanner finding a call site that + * really exists (a dynamic import on the boot path), so an empty answer is + * not a broken scanner. The shape is `../db/orphans.no-auto-run.test.ts`'s. + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** `packages/cli/src` — this package only; the scan never leaves it. */ +const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url)); + +function everyTsFile(dir: string, out: string[] = []): string[] { + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) everyTsFile(full, out); + else if (entry.endsWith('.ts')) out.push(full); + } + return out; +} + +const ALL_FILES = everyTsFile(SRC_ROOT); +const relative = (file: string) => file.slice(SRC_ROOT.length).replaceAll('\\', '/'); +const isTestFile = (path: string) => /\.test\.ts$/.test(path); + +/** A static `from '…'` or a dynamic `import('…')` specifier. */ +const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g; + +/** Files whose relative import RESOLVES to `target` (a path under `src/`), whatever the specifier's spelling. */ +function importersOf(target: string): string[] { + const wanted = join(SRC_ROOT, target); + return ALL_FILES.filter((file) => { + for (const m of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) { + const spec = m[1]!; + if (!spec.startsWith('.')) continue; + if (resolve(dirname(file), spec).replace(/\.js$/, '.ts') === wanted) return true; + } + return false; + }).map(relative); +} + +const COMMAND = 'commands/migrate/list-preferences.ts'; +/** The one-shot boot family's enumeration pin RUNS every bootSchemaStack caller's modes; a test, never a boot path. */ +const FAMILY_PIN = 'utils/schema-migrate.one-shot-family.integration.test.ts'; + +describe('the scanner works (positive controls)', () => { + it('finds the CLI’s own boot path reaching the kernel:ready migration gate — a DYNAMIC import', () => { + expect(importersOf('utils/artifact-boot-migration.ts').filter((p) => !isTestFile(p))).toContain('commands/serve.ts'); + }); + + it('finds the family pin importing this command', () => { + expect(importersOf(COMMAND)).toContain(FAMILY_PIN); + }); + + it('the file population itself is real', () => { + expect(ALL_FILES.length).toBeGreaterThan(100); + expect(ALL_FILES.map(relative)).toContain(COMMAND); + }); +}); + +describe('nothing on a boot, upgrade, migrate or lifecycle path invokes os migrate list-preferences', () => { + it('no source file imports the command — its own tests and the family pin are the only readers', () => { + const importers = importersOf(COMMAND); + expect(importers.filter((p) => !isTestFile(p))).toEqual([]); + expect( + importers.every((p) => p.startsWith('commands/migrate/list-preferences.') || p === FAMILY_PIN), + importers.join(', '), + ).toBe(true); + }); + + it('the CLI barrel does not export it', () => { + expect(readFileSync(join(SRC_ROOT, 'index.ts'), 'utf8')).not.toContain('list-preferences'); + }); +}); diff --git a/packages/cli/src/commands/migrate/list-preferences.ts b/packages/cli/src/commands/migrate/list-preferences.ts new file mode 100644 index 00000000000..10e7a0ddcf2 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.ts @@ -0,0 +1,393 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Command, Flags } from '@oclif/core'; +import chalk from 'chalk'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { createInterface } from 'node:readline'; +import { resolve as resolvePath } from 'node:path'; +import type { IObjectQLEngine } from '@objectstack/spec/contracts'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + createTimer, + emitJson, + isExitSignal, + errorCodeFields, +} from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; +import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; +import { absentTableReads } from '../../utils/absent-table-reads.js'; + +async function confirm(question: string): Promise { + if (!process.stdin.isTTY) return false; // non-interactive → require --yes + const rl = createInterface({ input: process.stdin, output: process.stdout }); + try { + const answer: string = await new Promise((resolve) => rl.question(question, resolve)); + return /^y(es)?$/i.test(answer.trim()); + } finally { + rl.close(); + } +} + +/** The object the retired rows are stored in. */ +export const USER_PREFERENCE_OBJECT = 'sys_user_preference'; + +/** + * The key prefix of the retired rows: one per user and object, written by + * Consoles before the list layout moved to the browser. + */ +export const RETIRED_LIST_PREFERENCE_PREFIX = 'ui.list.'; + +const SYSTEM = { isSystem: true } as const; +const PAGE_SIZE = 500; + +/** One retired row, as stored. */ +export interface RetiredListPreferenceRow { + id: string; + user_id: unknown; + key: string; + value: unknown; + [column: string]: unknown; +} + +/** The pre-delete export: every row the run deletes, as stored. */ +export interface RetiredListPreferenceExport { + producedBy: string; + object: typeof USER_PREFERENCE_OBJECT; + keyPrefix: typeof RETIRED_LIST_PREFERENCE_PREFIX; + rows: RetiredListPreferenceRow[]; +} + +type ReadEngine = Pick; + +/** + * Every stored `ui.list.*` row, walked in id order a page at a time, so a row + * written mid-walk cannot shift another out of the walk. + */ +export async function listRetiredListPreferenceRows( + engine: ReadEngine, + read: (run: () => Promise) => Promise = (run) => run(), +): Promise { + const out: RetiredListPreferenceRow[] = []; + let after: string | undefined; + for (;;) { + const page = await read(async () => (await engine.find(USER_PREFERENCE_OBJECT, { + where: { + key: { $startsWith: RETIRED_LIST_PREFERENCE_PREFIX }, + ...(after !== undefined ? { id: { $gt: after } } : {}), + }, + orderBy: [{ field: 'id', order: 'asc' }], + limit: PAGE_SIZE, + context: { ...SYSTEM }, + } as never)) as RetiredListPreferenceRow[]); + for (const row of page) { + if (row && typeof row.key === 'string' && row.key.startsWith(RETIRED_LIST_PREFERENCE_PREFIX)) out.push(row); + } + if (page.length < PAGE_SIZE) break; + after = String(page[page.length - 1].id); + } + return out; +} + +/** What a dry run reports, and what `--apply` deletes. */ +export interface RetiredListPreferenceSummary { + rows: number; + users: number; + objects: string[]; +} + +export function summarizeRetiredListPreferences(rows: readonly RetiredListPreferenceRow[]): RetiredListPreferenceSummary { + const users = new Set(rows.map((row) => String(row.user_id))); + const objects = new Set(rows.map((row) => row.key.slice(RETIRED_LIST_PREFERENCE_PREFIX.length))); + return { rows: rows.length, users: users.size, objects: [...objects].sort() }; +} + +/** + * `os migrate list-preferences` — remove the per-user list preference rows a + * Console no longer reads: every `sys_user_preference` row whose key starts + * with `ui.list.` (objectstack#35955). + * + * Such a row held one user's state for one object's lists — the view tab + * order, and per view a sort, filters, a column layout, a row height, hidden + * and added columns. The Console keeps none of that on the server any more: + * a change on a list is a draft, and the column widths, the row height and + * the tab order are kept in the reader's browser. Nothing reads these rows, + * so leaving them is harmless; this step clears them, as the upgrade notes + * ask. What they held is not carried anywhere: every reader's lists open on + * their views' own layout. + * + * ## The family's conventions, and the delete's own + * + * - Dry run by default: it boots read-only and reports how many rows, for how + * many users and which objects. It writes nothing. + * - `--apply` deletes, and only with `--export `: every row it deletes + * is first written to that file as stored (owner-only, never over an + * existing file) and read back. A failed or incomplete export refuses the + * run with nothing deleted. The export is the only copy that survives. + * - Only the exported rows are deleted, by id, under the system context, and + * none of them enters the recycle bin. The step then reads the prefix again: + * a row left (or written since) is reported and the run exits non-zero; a + * re-run finishes it. + * - Confirmed with `[y/N]` or `--yes`; `--force` past a busy SQLite file; + * `--json` for one document; `--database-url` / `$OS_DATABASE_URL`. + * - ⛔ Nothing on any boot, upgrade or lifecycle path runs it + * (`list-preferences.no-auto-run.test.ts`). No `sys_migration` verdict is + * recorded: nothing reads one. + * + * Exit status: 0 when nothing is stored, when a dry run lists rows (they are + * inert), or when every listed row was deleted; 1 when a delete failed, a row + * remains, the export could not be written, or the database could not be read. + */ +export default class MigrateListPreferences extends Command { + // The tracker id stays in the comment above: a command description reaches + // operators, who have no tracker to resolve it against. + static override description = + 'Remove the per-user list preference rows (sys_user_preference keys starting with "ui.list.") that the Console ' + + 'no longer reads. Dry run by default; --apply --export writes every row it deletes to the file first, ' + + 'then deletes them.'; + + static override examples = [ + '$ os migrate list-preferences', + '$ os migrate list-preferences --json', + '$ os migrate list-preferences --apply --export ./list-preferences-backup.json', + '$ os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json', + ]; + + static override flags = { + 'database-url': Flags.string({ + description: 'Database URL to migrate (defaults to $OS_DATABASE_URL / the project DB)', + env: 'OS_DATABASE_URL', + }), + apply: Flags.boolean({ + description: 'Delete the listed rows (default is a read-only dry run). Requires --export.', + default: false, + }), + export: Flags.string({ + description: 'Path for the MANDATORY pre-delete export: every row --apply deletes, as stored, written owner-only ' + + 'and read back before the first delete. Must not exist yet.', + }), + yes: Flags.boolean({ char: 'y', description: 'Skip the --apply confirmation prompt', default: false }), + force: Flags.boolean({ + description: 'Apply even when another process is using the database (SQLite occupancy check)', + default: false, + }), + json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + }; + + async run(): Promise { + const { flags } = await this.parse(MigrateListPreferences); + const timer = createTimer(); + const apply = flags.apply; + const json = flags.json === true; + + if (!json) printHeader('Migrate · list-preferences'); + + const refuse = async (error: string, message: string, extra: Record = {}): Promise => { + if (json) await emitJson({ error, message, ...extra }, 0, { compact: true }); + else printError(message); + this.exit(1); + }; + + const exportPath = flags.export ? resolvePath(flags.export) : undefined; + if (apply && !exportPath) { + await refuse( + 'export_required', + 'Refusing to delete without --export . The pre-delete export is mandatory: it is the only copy of ' + + 'the rows this run deletes.', + ); + return; + } + if (apply && exportPath && existsSync(exportPath)) { + await refuse('export_exists', `Refusing to overwrite an existing export at ${exportPath}. Name a new path.`, { + path: exportPath, + }); + return; + } + + const occupancy = await probeMigrationTarget(flags['database-url']); + if (occupancy.status === 'busy' && apply && !flags.force) { + if (json) { + await emitJson( + { error: 'database_busy', database: occupancy.filename, signal: occupancy.signal, detail: occupancy.detail, hint: OCCUPANCY_HINT }, + 0, + { compact: true }, + ); + this.exit(1); + return; + } + printError(describeOccupancy(occupancy)); + printWarning(OCCUPANCY_HINT); + this.exit(1); + return; + } + if (occupancy.status === 'busy' && !json) { + printWarning(apply + ? `--force: ${describeOccupancy(occupancy)} Deleting anyway — an old Console still open may write a row mid-run; a re-run removes it.` + : `${describeOccupancy(occupancy)} The dry run below writes no row or table. ${JOURNAL_MODE_SWITCH_NOTE}`); + } + if (occupancy.status === 'unknown' && !json) { + printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); + } + + if (apply && !flags.yes) { + if (json || !process.stdin.isTTY) { + if (json) { + await emitJson({ error: 'confirmation_required', hint: 'pass --yes' }, 0, { compact: true }); + this.exit(1); + return; + } + printWarning('Apply mode deletes sys_user_preference rows. Re-run with --yes to confirm, or run without --apply to preview.'); + this.exit(1); + return; + } + const ok = await confirm(chalk.bold('\nDelete every "ui.list." preference row on this database, after writing the export? [y/N] ')); + if (!ok) { + printInfo('Aborted — no export was written and no row was deleted.'); + return; + } + } + + if (!json) printStep(apply ? 'Booting data stack (APPLY mode)…' : 'Booting data stack (dry run)…'); + + let stack; + try { + // The dry run boots READ-ONLY, the boot `os migrate plan` takes: no + // schema DDL, no artifact seed, no sqlite file brought into existence. + stack = await bootSchemaStack({ + jsonOutput: json, + databaseUrl: flags['database-url'], + ...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), + }); + } catch (error: any) { + await refuse('boot_failed', error?.message ?? String(error), errorCodeFields(error)); + return; + } + + let exitCode = 0; + try { + const engine = stack.kernel.getService('objectql') as IObjectQLEngine | undefined; + if (typeof engine?.find !== 'function' || typeof engine?.delete !== 'function') { + throw new Error(`No ObjectQL engine on this stack — cannot read ${USER_PREFERENCE_OBJECT}.`); + } + // A table the read-only boot measured absent stores no row. + const reads = absentTableReads(stack, (object) => engine.getObject(object)); + const read = (run: () => Promise) => reads.rows(USER_PREFERENCE_OBJECT, run); + + const rows = await listRetiredListPreferenceRows(engine, read); + const summary = summarizeRetiredListPreferences(rows); + + if (!apply || rows.length === 0) { + if (json) { + reads.notice(true); + await emitJson({ database: stack.dbLabel, apply, ...summary, deleted: 0, remaining: summary.rows, duration: timer.elapsed() }); + return; + } + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + reads.notice(false); + console.log(''); + if (rows.length === 0) { + printSuccess(`No "ui.list." preference row is stored — nothing to remove ${chalk.dim(`(${timer.display()})`)}`); + } else { + console.log(` ${chalk.white(USER_PREFERENCE_OBJECT)}: ${summary.rows} "ui.list." row(s) for ${summary.users} user(s)`); + console.log(` objects: ${summary.objects.join(', ')}`); + console.log(''); + printInfo( + 'Dry run only — nothing reads these rows, so they are harmless where they are. Re-run with ' + + '--apply --export to remove them.', + ); + } + return; + } + + // ── The export, written and READ BACK before anything is deleted ────── + const doc: RetiredListPreferenceExport = { + producedBy: `${this.config.bin} migrate list-preferences --apply`, + object: USER_PREFERENCE_OBJECT, + keyPrefix: RETIRED_LIST_PREFERENCE_PREFIX, + rows, + }; + let exported: Set; + try { + writeFileSync(exportPath!, `${JSON.stringify(doc, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); + const back = JSON.parse(readFileSync(exportPath!, 'utf8')) as RetiredListPreferenceExport; + exported = new Set((back.rows ?? []).map((row) => String(row.id))); + } catch (error) { + exitCode = 1; + const message = `Refusing to delete: the pre-delete export could not be written and read back at ${exportPath} — ` + + `${error instanceof Error ? error.message : String(error)}. No row was deleted.`; + if (json) await emitJson({ error: 'export_failed', message }, 0, { compact: true }); + else printError(message); + return; + } + const missing = rows.filter((row) => !exported.has(String(row.id))); + if (missing.length > 0) { + exitCode = 1; + const message = `Refusing to delete: the export at ${exportPath} does not hold ${missing.length} of the ` + + `${rows.length} row(s). No row was deleted.`; + if (json) await emitJson({ error: 'export_incomplete', message }, 0, { compact: true }); + else printError(message); + return; + } + if (!json) printSuccess(`Pre-delete export written (owner-only): ${exportPath}`); + + // ── The delete: the exported rows, by id, and nothing else ──────────── + const failed: Array<{ ids: string[]; message: string }> = []; + const ids = rows.map((row) => String(row.id)); + for (let i = 0; i < ids.length; i += PAGE_SIZE) { + const batch = ids.slice(i, i + PAGE_SIZE); + try { + await engine.delete(USER_PREFERENCE_OBJECT, { + where: { id: { $in: batch } }, + multi: true, + context: { ...SYSTEM }, + } as never); + } catch (error) { + failed.push({ ids: batch, message: error instanceof Error ? error.message : String(error) }); + } + } + // Judged by what is gone, never by what the delete returned. + const left = await listRetiredListPreferenceRows(engine); + const leftIds = new Set(left.map((row) => String(row.id))); + const deleted = ids.filter((id) => !leftIds.has(id)).length; + if (failed.length > 0 || left.length > 0) exitCode = 1; + + if (json) { + await emitJson({ + database: stack.dbLabel, + apply, + export: exportPath, + ...summary, + deleted, + remaining: left.length, + failures: failed.map((f) => f.message), + duration: timer.elapsed(), + }); + return; + } + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + console.log(''); + console.log(` ${chalk.white(USER_PREFERENCE_OBJECT)}: ${deleted} of ${summary.rows} "ui.list." row(s) deleted, for ${summary.users} user(s)`); + for (const f of failed) printWarning(`A delete of ${f.ids.length} row(s) failed: ${f.message}`); + console.log(''); + if (left.length > 0) { + printError(`${left.length} "ui.list." row(s) are still stored — re-run with a new --export path to remove them.`); + } else { + printSuccess(`Removed every "ui.list." preference row ${chalk.dim(`(${timer.display()})`)}`); + printInfo(`Keep ${exportPath} until you are certain — it is the only copy of the deleted rows.`); + } + } catch (error: any) { + if (isExitSignal(error)) throw error; + exitCode = 1; + if (json) await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); + else printError(error.message || String(error)); + } finally { + await stack.shutdown(); + } + if (exitCode !== 0) this.exit(exitCode); + } +} diff --git a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts index d8538606d64..abcaa09487d 100644 --- a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts +++ b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts @@ -87,6 +87,7 @@ import MigrateTextScalars from '../commands/migrate/text-scalars.js'; import MigrateCommentReactions from '../commands/migrate/comment-reactions.js'; import MigrateDuplicates from '../commands/migrate/duplicates.js'; import MigrateFilesToReferences from '../commands/migrate/files-to-references.js'; +import MigrateListPreferences from '../commands/migrate/list-preferences.js'; import MigrateMeta from '../commands/migrate/meta.js'; import MigrateMultiValueColumns from '../commands/migrate/multi-value-columns.js'; import MigrateOrganizationOwnership from '../commands/migrate/organization-ownership.js'; @@ -240,6 +241,13 @@ const CALLERS: Record = { noWrite: [{ label: 'migrate text-scalars', argv: ['--database-url', '@DB@', '--json'] }], write: [{ label: 'migrate text-scalars --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], }, + 'commands/migrate/list-preferences.ts': { + run: invoke(MigrateListPreferences), + noWrite: [{ label: 'migrate list-preferences', argv: ['--database-url', '@DB@', '--json'] }], + // The fixture stores no `ui.list.` row, so the run deletes nothing and + // writes no export: the plain boot a delete takes is what this case is about. + write: [{ label: 'migrate list-preferences --apply', argv: ['--apply', '--export', '@DIR@/list-preferences-export.json', '--yes', '--database-url', '@DB@', '--json'] }], + }, 'commands/migrate/comment-parent-pair.ts': { run: invoke(MigrateCommentParentPair), noWrite: [{ label: 'migrate comment-parent-pair', argv: ['--database-url', '@DB@', '--json'] }], diff --git a/ui/packages/app-shell/src/console/ConsoleShell.tsx b/ui/packages/app-shell/src/console/ConsoleShell.tsx index abe7433388a..e87583504db 100644 --- a/ui/packages/app-shell/src/console/ConsoleShell.tsx +++ b/ui/packages/app-shell/src/console/ConsoleShell.tsx @@ -41,14 +41,9 @@ import { FlowPaletteRecentsProvider } from '../context/FlowPaletteRecentsProvide import { LastAppProvider, LAST_APP_PREFERENCE_KEY } from '../context/LastAppProvider.js'; import { UserStateAdaptersProvider, - useAttachListStateFamily, useAttachRecordStateFamily, useAttachUserStateAdapters, } from '../context/UserStateAdapters.js'; -import { - LIST_PREFERENCE_PREFIX, - ListPreferencesProvider, -} from '../context/ListPreferencesProvider.js'; import { RECORD_PREFERENCE_PREFIX, RecordPreferencesProvider, @@ -202,7 +197,6 @@ function ConsoleShellProviders({ children }: { children: ReactNode }) { - {/* objectui#4467 — the impersonation indicator. Above the routes, so it is chrome for EVERY console page (home has @@ -235,7 +229,6 @@ function ConsoleShellProviders({ children }: { children: ReactNode }) { - @@ -382,7 +375,6 @@ function UserStateBridge() { const { user } = useAuth(); const dataSource = useAdapter(); const attach = useAttachUserStateAdapters(); - const attachListState = useAttachListStateFamily(); const attachRecordState = useAttachRecordStateFamily(); useEffect(() => { @@ -391,7 +383,6 @@ function UserStateBridge() { attach('recent', null); attach('flowPaletteRecents', null); attach('lastApp', null); - attachListState(null); attachRecordState(null); return; } @@ -416,35 +407,27 @@ function UserStateBridge() { userId: user.id, key: LAST_APP_PREFERENCE_KEY, }); - // objectui#12418 — every object's list state, `ui.list.`: a key - // family, loaded by prefix in the same one read as the three slots above. - const listState = createObjectStackUserPreferenceFamily({ - dataSource, - userId: user.id, - prefix: LIST_PREFERENCE_PREFIX, - }); attach('favorites', favorites); attach('recent', recent); attach('flowPaletteRecents', flowPaletteRecents); attach('lastApp', lastApp); // objectstack#25883 — every object's record-page state, `ui.record.` - // ("show empty fields"): a second key family in the same one read. + // ("show empty fields"): a key family loaded by prefix in the same one + // read as the slots above. const recordState = createObjectStackUserPreferenceFamily({ dataSource, userId: user.id, prefix: RECORD_PREFERENCE_PREFIX, }); - attachListState(listState); attachRecordState(recordState); return () => { attach('favorites', null); attach('recent', null); attach('flowPaletteRecents', null); attach('lastApp', null); - attachListState(null); attachRecordState(null); }; - }, [user?.id, dataSource, attach, attachListState, attachRecordState]); + }, [user?.id, dataSource, attach, attachRecordState]); return null; } diff --git a/ui/packages/app-shell/src/context/ListPreferencesProvider.tsx b/ui/packages/app-shell/src/context/ListPreferencesProvider.tsx deleted file mode 100644 index 4feeb6a8551..00000000000 --- a/ui/packages/app-shell/src/context/ListPreferencesProvider.tsx +++ /dev/null @@ -1,677 +0,0 @@ -/** - * ListPreferencesProvider — a console user's own list state, per object - * (objectui#12418). - * - * What a user does to a list for themselves — the order of the view tabs, and - * per view the sort, the Filter panel's conditions, the column order and - * widths, the row density, the hidden fields (objectui#12474) and the fields - * they added as columns (objectstack#30077) — is THEIR preference: it follows them to another browser, and it - * never changes the view for anyone else. It used to live in two wrong places: - * the tab order and the filters in this browser's localStorage only, and the - * sort and the column layout written INTO the shared view (`/meta/view`), so - * one user's header click re-sorted the list for every user, and under a - * walled posture the write was refused. - * - * ## Where it is kept - * - * One `sys_user_preference` row per object, key `ui.list.`: - * - * ```json - * { "viewOrder": ["", …], - * "perView": { "": { "sort": […], "filters": {…}, "columnState": {…}, - * "rowHeight": "medium", "hiddenFields": ["", …], - * "addedFields": ["", …] } } } - * ``` - * - * The rows are loaded by prefix in the console's ONE preference read per load - * (objectui#12187: `ConsoleShell`'s bridge attaches the family beside the - * favorites / recents / palette slots, and `@object-ui/data-objectstack`'s - * shared read carries the prefix). Writes are per object, debounced. - * - * localStorage is the write-through cache and the no-adapter fallback, under - * `list-state::`. With no adapter attached — a host without the - * bridge, an anonymous session, a backend without the object — the state is - * this browser's, as the tab order and the filters were before. The first - * read of an object with no cached entry folds that object's older keys into - * it once: `viewOrder:` and the Filter panel's group from - * `list-filters:::` (the search term stays there). - * - * ## What it is not - * - * Not a saved view, and not a change to one: the view's authored `sort`, tab - * order, filter, columns, `rowHeight` and `hiddenFields` stay the default for - * every user with no preference. The view editor's explicit save still writes `/meta/view`. - * - * @module - */ - -import { - createContext, - useCallback, - useContext, - useEffect, - useMemo, - useRef, - useState, - type ReactNode, -} from 'react'; -import { registerBeforeSignOut, useAuth } from '@object-ui/auth'; -import { ROW_HEIGHT_TO_DENSITY_MODE, type RowHeight } from '@object-ui/core'; -import type { UserPreferenceFamily } from '@object-ui/data-objectstack'; -import { useListStateFamily } from './UserStateAdapters.js'; -import { discardPendingListFilterWrites } from '../views/listFilterStorage.js'; - -// --------------------------------------------------------------------------- -// The slot's shape -// --------------------------------------------------------------------------- - -/** One sort level, as the list emits it (the builder's row `id` is not kept). */ -export interface ListSortPreference { - field: string; - order: 'asc' | 'desc'; -} - -/** The Filter panel's group, kept verbatim so the panel can rehydrate it. */ -export interface ListFilterGroupPreference { - id?: string; - logic?: string; - conditions?: unknown[]; -} - -/** The grid's column layout: the order and widths a user dragged. */ -export interface ListColumnStatePreference { - order?: string[]; - widths?: Record; -} - -/** A user's state for one view of one object. */ -export interface ListViewPreference { - sort?: ListSortPreference[]; - filters?: ListFilterGroupPreference; - columnState?: ListColumnStatePreference; - /** - * objectui#12474 — the toolbar density this user chose, in the spec's - * `rowHeight` vocabulary (the value the density toggle maps its mode to). - * The view's authored `rowHeight` is the default while this is absent. - */ - rowHeight?: RowHeight; - /** - * objectui#12474 — the columns this user hid with the Hide Fields popover: - * a SUBTRACTION from the columns the view declares, never an addition (the - * list draws `columns` minus these). The whole list the popover emits, so - * an empty list is kept: it is "show every column", which is not the view's - * authored `hiddenFields`. The view's own list is the default while this is - * absent. - */ - hiddenFields?: string[]; - /** - * objectstack#30077 — the object's fields this user added to their list as - * columns with the Hide Fields popover: an ADDITION to the columns the view - * declares (the list draws `columns` plus these, then minus - * `hiddenFields`). Only a field the reader may read is offered; a stored - * name they can no longer read is kept and draws nothing. An empty list is - * "nothing added", the same as absent, so it is not kept. - */ - addedFields?: string[]; -} - -/** A user's state for one object: the `ui.list.` row's value. */ -export interface ObjectListPreference { - viewOrder?: string[]; - perView?: Record; -} - -/** The family's key prefix; an object's row is `ui.list.`. */ -export const LIST_PREFERENCE_PREFIX = 'ui.list.'; - -/** The row key of one object's list state. */ -export function listPreferenceKey(objectName: string): string { - return `${LIST_PREFERENCE_PREFIX}${objectName}`; -} - -const LOCAL_PREFIX = 'list-state'; -const EMPTY: ObjectListPreference = Object.freeze({}) as ObjectListPreference; - -// --------------------------------------------------------------------------- -// Pure helpers (exported for the pins) -// --------------------------------------------------------------------------- - -const isRecord = (v: unknown): v is Record => - !!v && typeof v === 'object' && !Array.isArray(v); - -const isStringArray = (v: unknown): v is string[] => - Array.isArray(v) && v.every((x) => typeof x === 'string'); - -function sanitizeSort(v: unknown): ListSortPreference[] | undefined { - if (!Array.isArray(v)) return undefined; - const out: ListSortPreference[] = []; - for (const item of v) { - if (!isRecord(item) || typeof item.field !== 'string' || !item.field) continue; - out.push({ field: item.field, order: item.order === 'desc' ? 'desc' : 'asc' }); - } - return out; -} - -function sanitizeFilters(v: unknown): ListFilterGroupPreference | undefined { - if (!isRecord(v) || !Array.isArray(v.conditions) || v.conditions.length === 0) return undefined; - return v as ListFilterGroupPreference; -} - -function sanitizeColumnState(v: unknown): ListColumnStatePreference | undefined { - if (!isRecord(v)) return undefined; - const out: ListColumnStatePreference = {}; - if (isStringArray(v.order) && v.order.length > 0) out.order = [...v.order]; - if (isRecord(v.widths)) { - const widths: Record = {}; - for (const [k, w] of Object.entries(v.widths)) { - if (typeof w === 'number' && Number.isFinite(w)) widths[k] = w; - } - if (Object.keys(widths).length > 0) out.widths = widths; - } - return out.order || out.widths ? out : undefined; -} - -/** One of the spec's five row heights, or nothing. */ -function sanitizeRowHeight(v: unknown): RowHeight | undefined { - return typeof v === 'string' && Object.prototype.hasOwnProperty.call(ROW_HEIGHT_TO_DENSITY_MODE, v) - ? (v as RowHeight) - : undefined; -} - -function sanitizeHiddenFields(v: unknown): string[] | undefined { - if (!Array.isArray(v)) return undefined; - return [...new Set(v.filter((x): x is string => typeof x === 'string' && x.length > 0))]; -} - -/** The added fields, de-duplicated; an empty list is no part at all. */ -function sanitizeAddedFields(v: unknown): string[] | undefined { - const names = sanitizeHiddenFields(v); - return names && names.length > 0 ? names : undefined; -} - -function sanitizeView(v: unknown): ListViewPreference | undefined { - if (!isRecord(v)) return undefined; - const out: ListViewPreference = {}; - const sort = sanitizeSort(v.sort); - if (sort) out.sort = sort; - const filters = sanitizeFilters(v.filters); - if (filters) out.filters = filters; - const columnState = sanitizeColumnState(v.columnState); - if (columnState) out.columnState = columnState; - const rowHeight = sanitizeRowHeight(v.rowHeight); - if (rowHeight) out.rowHeight = rowHeight; - const hiddenFields = sanitizeHiddenFields(v.hiddenFields); - if (hiddenFields) out.hiddenFields = hiddenFields; - const addedFields = sanitizeAddedFields(v.addedFields); - if (addedFields) out.addedFields = addedFields; - return Object.keys(out).length > 0 ? out : undefined; -} - -/** Keep only the parts of a stored value this slot declares, well formed. */ -export function sanitizeObjectListPreference(v: unknown): ObjectListPreference { - if (!isRecord(v)) return {}; - const out: ObjectListPreference = {}; - if (isStringArray(v.viewOrder) && v.viewOrder.length > 0) out.viewOrder = [...v.viewOrder]; - if (isRecord(v.perView)) { - const perView: Record = {}; - for (const [viewId, view] of Object.entries(v.perView)) { - const clean = sanitizeView(view); - if (clean) perView[viewId] = clean; - } - if (Object.keys(perView).length > 0) out.perView = perView; - } - return out; -} - -/** - * A patch to one view's entry. A key present with `undefined` or `null` CLEARS - * that part, and so does a filter group with no condition or a column state - * with no order and no width. An empty sort is NOT a clear: `sort: []` is kept, - * because a user who removed every sort level (the Sort builder emits `[]`) - * chose "no sort", which is not the view's authored sort. The same holds for - * `hiddenFields: []` ("show every column"); `addedFields: []` is a clear, since - * nothing added is the view's own. The ways back to the view's own - * are "Reset view" (the whole entry, `resetViewPreference`) and the list's - * "Reset to view default" for one part, which patches that part to `null` - * (objectstack#28948) instead of storing the view's value as a choice. A view - * left with nothing is removed. - */ -export type ListViewPreferencePatch = { - sort?: ReadonlyArray<{ field: string; order?: string }> | null; - filters?: ListFilterGroupPreference | null; - columnState?: ListColumnStatePreference | null; - rowHeight?: RowHeight | null; - hiddenFields?: readonly string[] | null; - addedFields?: readonly string[] | null; -}; - -const VIEW_PREFERENCE_PARTS = ['sort', 'filters', 'columnState', 'rowHeight', 'hiddenFields', 'addedFields'] as const; - -/** Apply a patch to one view's entry of an object's state. Pure. */ -export function patchViewPreference( - state: ObjectListPreference, - viewId: string, - patch: ListViewPreferencePatch, -): ObjectListPreference { - const current: Record = { ...(state.perView?.[viewId] ?? {}) }; - for (const key of VIEW_PREFERENCE_PARTS) { - if (!(key in patch)) continue; - const value = patch[key]; - if (value === undefined || value === null) delete current[key]; - else current[key] = value; - } - const clean = sanitizeView(current); - const perView = { ...(state.perView ?? {}) }; - if (clean) perView[viewId] = clean; - else delete perView[viewId]; - const next: ObjectListPreference = { ...state }; - if (Object.keys(perView).length > 0) next.perView = perView; - else delete next.perView; - return next; -} - -/** - * Remove one view's entry — every part of it: the sort, filters, column state, - * density, hidden fields (objectui#12474) and added fields (objectstack#30077). - * Pure. - */ -export function resetViewPreference(state: ObjectListPreference, viewId: string): ObjectListPreference { - if (!state.perView || !(viewId in state.perView)) return state; - const perView = { ...state.perView }; - delete perView[viewId]; - const next: ObjectListPreference = { ...state }; - if (Object.keys(perView).length > 0) next.perView = perView; - else delete next.perView; - return next; -} - -/** Set (or, with an empty list, clear) the object's tab order. Pure. */ -export function setViewOrderPreference(state: ObjectListPreference, ids: readonly string[]): ObjectListPreference { - const next: ObjectListPreference = { ...state }; - if (ids.length > 0) next.viewOrder = [...ids]; - else delete next.viewOrder; - return next; -} - -// --------------------------------------------------------------------------- -// localStorage: the write-through cache and the no-adapter fallback -// --------------------------------------------------------------------------- - -/** The cache key of one user's state for one object. */ -export function localListStateKey(userId: string | null | undefined, objectName: string): string { - return `${LOCAL_PREFIX}:${userId || 'anon'}:${objectName}`; -} - -/** - * The object's older keys, folded into one state: the tab order the reorder - * used to write (`viewOrder:`, per browser) and each view's Filter - * panel group (`list-filters:::`, `listFilterStorage`). - */ -function foldLegacy(userId: string | null | undefined, objectName: string): ObjectListPreference { - let state: ObjectListPreference = {}; - try { - const rawOrder = localStorage.getItem(`viewOrder:${objectName}`); - const order = rawOrder ? JSON.parse(rawOrder) : undefined; - if (isStringArray(order)) state = setViewOrderPreference(state, order); - } catch { - /* unreadable — nothing to fold */ - } - try { - const prefix = `list-filters:${userId || 'anon'}:${objectName}:`; - for (let i = 0; i < localStorage.length; i++) { - const key = localStorage.key(i); - if (!key || !key.startsWith(prefix)) continue; - const viewId = key.slice(prefix.length); - const raw = localStorage.getItem(key); - const parsed = raw ? JSON.parse(raw) : undefined; - if (viewId && isRecord(parsed)) { - state = patchViewPreference(state, viewId, { filters: parsed.filters as ListFilterGroupPreference }); - } - } - } catch { - /* unreadable — nothing to fold */ - } - return state; -} - -/** - * This browser's cached state for the object. With no cached entry yet, the - * object's older keys are folded instead (read only: the fold is written the - * first time the state changes, so it stays the fold until then). - */ -export function readLocalListState(userId: string | null | undefined, objectName: string): ObjectListPreference { - if (!objectName || typeof localStorage === 'undefined') return {}; - try { - const raw = localStorage.getItem(localListStateKey(userId, objectName)); - if (raw != null) return sanitizeObjectListPreference(JSON.parse(raw)); - } catch { - return {}; - } - return foldLegacy(userId, objectName); -} - -/** Write the object's state to this browser's cache. Never throws. */ -export function writeLocalListState( - userId: string | null | undefined, - objectName: string, - state: ObjectListPreference, -): void { - if (!objectName || typeof localStorage === 'undefined') return; - try { - localStorage.setItem(localListStateKey(userId, objectName), JSON.stringify(state)); - } catch { - /* quota / private mode — the cache is best-effort */ - } -} - -// --------------------------------------------------------------------------- -// Context + provider -// --------------------------------------------------------------------------- - -interface ListPreferencesContextValue { - /** Objects whose state this session holds (remote rows and local writes). */ - states: Record; - /** - * The signed-in user's state has been read: the attached family's first load - * has settled, or the wait for it ran out. Always true with no user. - */ - ready: boolean; - update(objectName: string, fn: (prev: ObjectListPreference) => ObjectListPreference): void; -} - -const ListPreferencesContext = createContext(null); - -/** - * How long a list waits for the preference read before it opens on this - * browser's cache. The read is the console's one load-time read, sent at boot - * beside the metadata reads, so it has normally answered before a list can - * render; this only bounds a stalled request. - */ -export const LIST_PREFERENCES_WAIT_MS = 2500; - -const SAVE_DEBOUNCE_MS = 500; - -type ListFamily = UserPreferenceFamily; - -/** - * One spelling per VALUE of an object's state: object keys sorted at every - * depth, so two states that differ only in the order their parts were set - * compare equal. Arrays keep their order: a tab order or a sort is ordered. - */ -export function listPreferenceFingerprint(state: ObjectListPreference): string { - const canonical = (v: unknown): unknown => { - if (Array.isArray(v)) return v.map(canonical); - if (!isRecord(v)) return v; - const out: Record = {}; - for (const key of Object.keys(v).sort()) { - if (v[key] !== undefined) out[key] = canonical(v[key]); - } - return out; - }; - return JSON.stringify(canonical(state)); -} - -/** The fingerprint of an object the user has stored nothing for. */ -const NO_ROW_FINGERPRINT = listPreferenceFingerprint({}); - -export function ListPreferencesProvider({ children }: { children: ReactNode }) { - const { user } = useAuth(); - const userId = user?.id ?? null; - const family = useListStateFamily(); - - const [states, setStates] = useState>({}); - const statesRef = useRef(states); - statesRef.current = states; - // The family whose first load has settled (or whose wait ran out). - const [settledFor, setSettledFor] = useState(null); - // What the attached family's store holds, per object, as a fingerprint: the - // rows its load answered, then every save it accepted. `null` until that - // load answers: what is stored is unknown then, so every change is written. - const persistedRef = useRef<{ family: ListFamily; byObject: Map } | null>(null); - - // Hydrate when a family attaches (a sign-in, a user switch): the remote rows - // are the user's state on every device, written through to this browser's - // cache. What the previous user's session held is dropped first. - useEffect(() => { - statesRef.current = {}; - setStates({}); - persistedRef.current = null; - if (!family) return; - let cancelled = false; - const wait = setTimeout(() => { - if (!cancelled) setSettledFor((prev) => (prev === family ? prev : family)); - }, LIST_PREFERENCES_WAIT_MS); - void family.load().then((rows) => { - if (cancelled) return; - const remote: Record = {}; - const byObject = new Map(); - for (const [key, value] of Object.entries(rows)) { - if (!key.startsWith(LIST_PREFERENCE_PREFIX)) continue; - const objectName = key.slice(LIST_PREFERENCE_PREFIX.length); - const clean = sanitizeObjectListPreference(value); - remote[objectName] = clean; - byObject.set(objectName, listPreferenceFingerprint(clean)); - writeLocalListState(userId, objectName, clean); - } - persistedRef.current = { family, byObject }; - statesRef.current = { ...statesRef.current, ...remote }; - setStates((prev) => ({ ...prev, ...remote })); - setSettledFor(family); - }); - return () => { - cancelled = true; - clearTimeout(wait); - }; - }, [family, userId]); - - // A session that ends without `signOut()` (a session read the server answers - // with "no session") drops them as soon as the user is gone. - const signedInUserRef = useRef(userId); - useEffect(() => { - const previous = signedInUserRef.current; - signedInUserRef.current = userId; - if (previous !== null && userId === null) discardPendingListFilterWrites(); - }, [userId]); - - // Debounced remote writes, one per object, each bound to the family that - // was attached when it was made (a user switch flushes to the right user). - const pendingRef = useRef( - new Map; value: ObjectListPreference; family: ListFamily }>(), - ); - // Saves sent and not yet answered, so a sign-out can wait for them. - const inFlightRef = useRef(new Set>()); - // Saves on the wire per object: while one is, what the store holds is about - // to change, so no change is judged against it. - const sendingRef = useRef(new Map()); - const flushOne = useCallback((objectName: string) => { - const pending = pendingRef.current.get(objectName); - if (!pending) return; - clearTimeout(pending.timer); - pendingRef.current.delete(objectName); - const inFlight = inFlightRef.current; - const sent = pending.family.save(listPreferenceKey(objectName), pending.value); - inFlight.add(sent); - const sending = sendingRef.current; - sending.set(objectName, (sending.get(objectName) ?? 0) + 1); - const settle = () => { - inFlight.delete(sent); - const left = (sending.get(objectName) ?? 1) - 1; - if (left > 0) sending.set(objectName, left); - else sending.delete(objectName); - }; - const fingerprint = listPreferenceFingerprint(pending.value); - sent.then(() => { - // Accepted: this is what the store now holds for the object. - settle(); - const persisted = persistedRef.current; - if (persisted?.family === pending.family) persisted.byObject.set(objectName, fingerprint); - }, settle); - }, []); - - // Before `signOut()` ends the session (objectstack#32298): a list change - // still waiting on its debounce is saved now, and every save already sent - // is waited for, because the server refuses a write that arrives after the - // session has ended and the user's last change would be lost on every - // device. `runBeforeSignOut` bounds the wait. A list-filter write still - // waiting on its debounce is dropped, so none lands after the sign-out sweep. - useEffect( - () => - registerBeforeSignOut(async () => { - discardPendingListFilterWrites(); - for (const objectName of [...pendingRef.current.keys()]) flushOne(objectName); - await Promise.allSettled([...inFlightRef.current]); - }), - [flushOne], - ); - useEffect(() => { - const pending = pendingRef.current; - return () => { - for (const objectName of [...pending.keys()]) flushOne(objectName); - }; - }, [family, flushOne]); - - const update = useCallback( - (objectName: string, fn: (prev: ObjectListPreference) => ObjectListPreference) => { - if (!objectName) return; - const prev = statesRef.current[objectName] ?? readLocalListState(userId, objectName); - const next = fn(prev); - if (next === prev) return; - // A patch that re-states what the user already has (a re-emitted sort, - // a "Clear all" over no filters) changes no preference: nothing to hold - // and nothing to write. - const fingerprint = listPreferenceFingerprint(next); - if (fingerprint === listPreferenceFingerprint(prev)) return; - statesRef.current = { ...statesRef.current, [objectName]: next }; - setStates((s) => ({ ...s, [objectName]: next })); - writeLocalListState(userId, objectName, next); - if (!family) return; - const existing = pendingRef.current.get(objectName); - if (existing) clearTimeout(existing.timer); - // Back to what the store already holds (a change undone inside the - // debounce): the write still waiting is dropped and none is sent. - const persisted = persistedRef.current; - if ( - persisted?.family === family && - !sendingRef.current.has(objectName) && - fingerprint === (persisted.byObject.get(objectName) ?? NO_ROW_FINGERPRINT) - ) { - pendingRef.current.delete(objectName); - return; - } - pendingRef.current.set(objectName, { - value: next, - family, - timer: setTimeout(() => flushOne(objectName), SAVE_DEBOUNCE_MS), - }); - }, - [userId, family, flushOne], - ); - - // A signed-in user's family is attached by the console's bridge in the - // first commit's effects, so the page's first render runs before it: until - // it attaches (or the same wait runs out, for a host with no bridge), there - // is no state to open a list on yet. With no user there is none to wait for. - const [noFamilyWaitOverFor, setNoFamilyWaitOverFor] = useState(null); - useEffect(() => { - if (family || !userId) return; - const wait = setTimeout(() => setNoFamilyWaitOverFor(userId), LIST_PREFERENCES_WAIT_MS); - return () => clearTimeout(wait); - }, [family, userId]); - - const ready = !userId - ? true - : family - ? settledFor === family - : noFamilyWaitOverFor === userId; - const value = useMemo( - () => ({ states, ready, update }), - [states, ready, update], - ); - - return {children}; -} - -// --------------------------------------------------------------------------- -// Hook -// --------------------------------------------------------------------------- - -export interface ObjectListPreferences { - /** - * The user's stored state for this object has been read (or there is none - * to wait for). A list opens on its stored state, so it waits for this. - */ - ready: boolean; - /** The user's state for this object; `{}` when they have none. */ - preference: ObjectListPreference; - /** Store the user's tab order. */ - setViewOrder(ids: readonly string[]): void; - /** Store (or clear, see {@link ListViewPreferencePatch}) part of one view's state. */ - patchView(viewId: string, patch: ListViewPreferencePatch): void; - /** Drop one view's whole entry (sort, filters, columns, density, hidden and added fields): back to the view's own. */ - resetView(viewId: string): void; -} - -/** - * The signed-in user's list state for one object. - * - * Inside {@link ListPreferencesProvider} it is the cloud-synced state. Outside - * one (a host without the console shell, unit tests) it is this browser's - * cache alone, the same localStorage the provider writes through. - */ -export function useObjectListPreferences(objectName: string | undefined): ObjectListPreferences { - const ctx = useContext(ListPreferencesContext); - const { user } = useAuth(); - const userId = user?.id ?? null; - const name = objectName ?? ''; - - // What the session holds for the object, else this browser's cache. The - // cache read is keyed on what it reads, and re-read after a fallback write. - const held = ctx?.states[name]; - const [localWrites, setLocalWrites] = useState(0); - const cached = useMemo( - () => (held ? EMPTY : readLocalListState(userId, name)), - // eslint-disable-next-line react-hooks/exhaustive-deps -- `localWrites` re-reads after a fallback write - [held, userId, name, localWrites], - ); - const preference = held ?? cached; - - const update = useCallback( - (fn: (prev: ObjectListPreference) => ObjectListPreference) => { - if (!name) return; - if (ctx) { - ctx.update(name, fn); - return; - } - const prev = readLocalListState(userId, name); - const next = fn(prev); - if (next === prev) return; - writeLocalListState(userId, name, next); - setLocalWrites((n) => n + 1); - }, - [ctx, name, userId], - ); - - const setViewOrder = useCallback( - (ids: readonly string[]) => update((prev) => setViewOrderPreference(prev, ids)), - [update], - ); - const patchView = useCallback( - (viewId: string, patch: ListViewPreferencePatch) => { - if (!viewId) return; - update((prev) => patchViewPreference(prev, viewId, patch)); - }, - [update], - ); - const resetView = useCallback( - (viewId: string) => update((prev) => resetViewPreference(prev, viewId)), - [update], - ); - - return { - ready: ctx ? ctx.ready : true, - preference, - setViewOrder, - patchView, - resetView, - }; -} diff --git a/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx b/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx index ec936a6f871..f8b30073f95 100644 --- a/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx +++ b/ui/packages/app-shell/src/context/RecordPreferencesProvider.tsx @@ -11,11 +11,10 @@ * * ## Where it is kept * - * One `sys_user_preference` row per object, key `ui.record.`, beside - * the list page's `ui.list.` (objectui#12418) and through the same - * mechanism: a key family the console's `UserStateBridge` attaches, loaded by - * prefix in the console's ONE preference read per load, each object's row - * written on its own. + * One `sys_user_preference` row per object, key `ui.record.`: a key + * family the console's `UserStateBridge` attaches, loaded by prefix in the + * console's ONE preference read per load, each object's row written on its + * own. * * ```json * { "showEmptyFields": true, diff --git a/ui/packages/app-shell/src/context/UserStateAdapters.tsx b/ui/packages/app-shell/src/context/UserStateAdapters.tsx index 5c307b8852d..b7e33e3d2a3 100644 --- a/ui/packages/app-shell/src/context/UserStateAdapters.tsx +++ b/ui/packages/app-shell/src/context/UserStateAdapters.tsx @@ -44,24 +44,17 @@ interface UserStateAdaptersValue { flowPaletteRecents: UserDataAdapter | null; /** objectstack#35881 — the person's last app (`ui.app.last`, `LastAppProvider`). */ lastApp: UserDataAdapter | null; - /** - * objectui#12418 — the per-object list state (`ui.list.`), a key - * FAMILY rather than one list: one row per object, loaded together by prefix - * in the same shared read as the three slots above. Console-internal, so it - * is not one of the public {@link UserStateKind}s. - */ - listState: UserPreferenceFamily | null; /** * objectstack#25883 — the per-object record-page state (`ui.record.`), - * a key family loaded by prefix in the same shared read as `listState`. - * Console-internal, like `listState`. + * a key FAMILY rather than one list: one row per object, loaded together by + * prefix in the same shared read as the slots above. Console-internal, so it + * is not one of the public {@link UserStateKind}s. */ recordState: UserPreferenceFamily | null; } interface AttachApi { attach(kind: UserStateKind, adapter: UserDataAdapter | null): void; - attachListState(family: UserPreferenceFamily | null): void; attachRecordState(family: UserPreferenceFamily | null): void; } @@ -74,7 +67,6 @@ const ReadCtx = createContext({ recent: null, flowPaletteRecents: null, lastApp: null, - listState: null, recordState: null, }); const WriteCtx = createContext(null); @@ -89,7 +81,6 @@ export function UserStateAdaptersProvider({ children }: { children: ReactNode }) recent: null, flowPaletteRecents: null, lastApp: null, - listState: null, recordState: null, }); @@ -98,9 +89,6 @@ export function UserStateAdaptersProvider({ children }: { children: ReactNode }) attach: (kind, adapter) => { setAdapters(prev => (prev[kind] === adapter ? prev : { ...prev, [kind]: adapter })); }, - attachListState: (family) => { - setAdapters(prev => (prev.listState === family ? prev : { ...prev, listState: family })); - }, attachRecordState: (family) => { setAdapters(prev => (prev.recordState === family ? prev : { ...prev, recordState: family })); }, @@ -136,22 +124,6 @@ export function useAttachUserStateAdapters() { ); } -/** The attached per-object list-state family (objectui#12418), or null. */ -export function useListStateFamily(): UserPreferenceFamily | null { - return useContext(ReadCtx).listState as UserPreferenceFamily | null; -} - -/** Plug the list-state family in/out. Stable across re-renders. */ -export function useAttachListStateFamily() { - const ctx = useContext(WriteCtx); - return useCallback( - (family: UserPreferenceFamily | null) => { - ctx?.attachListState(family); - }, - [ctx], - ); -} - /** The attached per-object record-page family (objectstack#25883), or null. */ export function useRecordStateFamily(): UserPreferenceFamily | null { return useContext(ReadCtx).recordState as UserPreferenceFamily | null; diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 9f809b4453c..31568ae0d5e 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -15,7 +15,7 @@ import { columnsWithSummary, declaredColumnFields } from './columnSummaryWrite.j import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense, type ReactNode } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; -import { useObjectListPreferences } from '../context/ListPreferencesProvider.js'; +import { useObjectListLayout } from './listLayoutStore.js'; const ImportWizard = lazy(() => import('@object-ui/plugin-grid').then((m) => ({ default: m.ImportWizard })), ); @@ -453,16 +453,14 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co [personalViews.views], ); - // objectui#12418 — the signed-in user's OWN list state for this object: - // the tab order, and per view the sort, the Filter panel's conditions and - // the column layout. A toolbar change writes here (`sys_user_preference` - // `ui.list.`, localStorage as the cache), never into the shared - // view: the view's authored values stay the default for every user with - // no preference. See `ListPreferencesProvider`. - const listPrefs = useObjectListPreferences(objectName); + // objectstack#35955 — the reader's list LAYOUT for this object, in this + // browser only (`./listLayoutStore.ts`): the tab order, and per view the + // column widths and the row height. Never written to the server or into + // the shared view: the view's authored values stay every other reader's. + const listLayout = useObjectListLayout(objectName); // Content keys, not identities (AGENTS.md #10): the views memo and the list - // relay re-run when what the user stored changes, and on nothing else. - const prefViewOrderKey = JSON.stringify(listPrefs.preference.viewOrder ?? []); + // relay re-run when the reader's tab order changes, and on nothing else. + const prefViewOrderKey = JSON.stringify(listLayout.layout.viewOrder ?? []); useEffect(() => { let cancelled = false; if (!objectName) { @@ -605,7 +603,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co } // Stable sort: respect the user's own view-order preference (for both - // metadata and saved views; objectui#12418, `listPrefs`). Falls back + // metadata and saved views; `listLayout`). Falls back // to: metadata views first in declared order, then saved views by // `sortOrder` / created_at — the authored order, every user's default. const indexOf = new Map(viewList.map((v, i) => [v.id, i])); @@ -732,7 +730,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co const listDraft = useListDraft(listDraftScope(user?.id, objectName ?? '', activeView?.id ? String(activeView.id) : '')); /** The list on screen in the reader-state shape the view builders read (draft + kept widths and row height). */ const draftPreferenceOf = (id: string | undefined) => - id ? listDraftPreference(listDraft.draft, listPrefs.preference.perView?.[id]) : undefined; + id ? listDraftPreference(listDraft.draft, listLayout.layout.perView?.[id]) : undefined; // objectstack#25992 slice 8: the list's toolbar state in the URL (seed, write-back, // "Reset view") moved to `./objectViewListUrlState.ts`. const { @@ -751,7 +749,6 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co objectDef, activeView, viewResolving: awaitingPersonalViews, - listPrefs, listDraft: listDraft.draft, perms, user, @@ -851,7 +848,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co setRefreshKey, confirmHandler, savedViews, - listPrefs, + listLayout, views, activeViewId, baseView, @@ -1169,7 +1166,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co managedUsers, managedUserMarker, savedViews, - listPrefs, + listLayout, listDraft, derivedColumnViewIds, baseView, diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index a9439cf1e2d..c67ca92dce1 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -9,8 +9,8 @@ * What a draft holds: the sort, the Filter panel's group, the grouping, the * search term, the columns shown (hidden ones, added ones), the column order * and (from PR 2) the Display panel's layout and row colour. What it never holds: the - * column widths and the row height, which are remembered for the reader - * (`ListPreferencesProvider`), and the view tab order. + * column widths, the row height and the view tab order, which are the reader's + * layout in this browser (`./listLayoutStore.ts`). * * ## How long it lives * @@ -36,11 +36,49 @@ import { useCallback, useSyncExternalStore } from 'react'; import type { GroupingConfig } from '@objectstack/spec/ui'; -import type { - ListFilterGroupPreference, - ListSortPreference, - ListViewPreference, -} from '../context/ListPreferencesProvider.js'; +import type { RowHeight } from '@object-ui/core'; +import type { ListViewLayout } from './listLayoutStore.js'; + +/** One sort level, as the list emits it (the builder's row `id` is not kept). */ +export interface ListSortPreference { + field: string; + order: 'asc' | 'desc'; +} + +/** The Filter panel's group, kept verbatim so the panel can rehydrate it. */ +export interface ListFilterGroupPreference { + id?: string; + logic?: string; + conditions?: unknown[]; +} + +/** The grid's column layout: the order (a draft) and the widths (the reader's layout). */ +export interface ListColumnStatePreference { + order?: string[]; + widths?: Record; +} + +/** + * The list on screen beyond its view's own body, in the shape the list relay + * and the view builders read: the draft's parts, with the column widths and + * the row height from the reader's layout (`./listLayoutStore.ts`). Built by + * {@link listDraftPreference}; stored nowhere in this shape. + */ +export interface ListViewPreference { + sort?: ListSortPreference[]; + filters?: ListFilterGroupPreference; + columnState?: ListColumnStatePreference; + /** The reader's row height, in the spec's `rowHeight` vocabulary. */ + rowHeight?: RowHeight; + /** + * The columns the reader hid: a SUBTRACTION from the columns the view + * declares. An empty list is "show every column", which is not the view's + * authored `hiddenFields`. + */ + hiddenFields?: string[]; + /** The object's fields the reader added as columns: an ADDITION to the view's. */ + addedFields?: string[]; +} /** A list's unsaved changes. An absent part is the view's own. */ export interface ListDraft { @@ -216,18 +254,15 @@ function sameAddress(a: string, b: string): boolean { } /** - * The list's state in the reader-state shape the list relay and the view - * builders read (`ListViewPreference`): the draft's columns, their order and - * its sort and filters, with the two parts kept for the reader — the column - * widths and the row height — from what they stored. Nothing else they - * stored is read: a sort, filter, column order or hidden column stored - * before objectstack#35955 no longer applies. + * The list's state in the shape the list relay and the view builders read + * ({@link ListViewPreference}): the draft's sort, filters and columns, with the + * reader's layout in this browser — the column widths and the row height. */ export function listDraftPreference( draft: ListDraft, - stored: ListViewPreference | undefined, + layout: ListViewLayout | undefined, ): ListViewPreference | undefined { - const widths = stored?.columnState?.widths; + const widths = layout?.widths; const out: ListViewPreference = {}; if (draft.sort) out.sort = draft.sort; if (draft.filters) out.filters = draft.filters; @@ -239,7 +274,7 @@ export function listDraftPreference( ...(widths ? { widths } : {}), }; } - if (stored?.rowHeight) out.rowHeight = stored.rowHeight; + if (layout?.rowHeight) out.rowHeight = layout.rowHeight; return Object.keys(out).length > 0 ? out : undefined; } diff --git a/ui/packages/app-shell/src/views/listFilterStorage.ts b/ui/packages/app-shell/src/views/listFilterStorage.ts deleted file mode 100644 index 5fccdaede9a..00000000000 --- a/ui/packages/app-shell/src/views/listFilterStorage.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * Per-user, per-view persistence for a list's transient runtime filters — - * the advanced FilterBuilder group and the search term. - * - * Unlike `userFilterUrlState` (which mirrors end-user quick-filter selections - * into `uf_*` URL params so a filtered list is shareable), this cache lives in - * `localStorage`. URL params only survive a reload or the browser Back button; - * they are lost the moment the user leaves via an in-app nav link (that link - * carries no query string) and returns. Mirroring the runtime filter into - * `localStorage` makes it survive full SPA navigation too — the user's own - * "remember what I was filtering" state, NOT a change to the shared view. - * - * The key embeds the user id so two accounts on the same browser never read - * each other's filters (a filter value can be sensitive). Column state - * (`grid-columns-*`) predates this and is deliberately NOT user-scoped — - * column widths are cosmetic; filter values are not. - * - * Sign-out removes every key (`@object-ui/auth`'s signed-out sweep), and a - * write still waiting on the debounce below is dropped before the session ends - * ({@link discardPendingListFilterWrites}), so none lands after that sweep. - */ - -const PREFIX = 'list-filters'; - -/** Loose shape of a FilterBuilder group — `{ id, logic, conditions[] }`. */ -export interface ListFilterState { - filters?: { id?: string; logic?: string; conditions?: unknown[] } | null; - search?: string; -} - -/** - * Build the storage key for a given user + object + view. Returns undefined - * when the caller can't scope it (no object/view yet) so we never write a key - * that would collide across views. `userId` falls back to `anon` — a signed-out - * or still-loading session gets its own bucket rather than leaking into a real - * user's key. - */ -export function buildListFilterKey( - userId: string | undefined, - objectName: string | undefined, - viewId: string | undefined, -): string | undefined { - if (!objectName || !viewId) return undefined; - return `${PREFIX}:${userId || 'anon'}:${objectName}:${viewId}`; -} - -/** True when a filter group carries no active conditions. */ -function isEmptyFilters(f: ListFilterState['filters']): boolean { - return !f || !Array.isArray(f.conditions) || f.conditions.length === 0; -} - -/** True when a whole state is effectively empty (nothing worth persisting). */ -function isEmptyState(s: ListFilterState): boolean { - return isEmptyFilters(s.filters) && !(s.search && s.search.length > 0); -} - -/** Read the cached filter state for a key. Returns undefined when absent or unparsable. */ -export function readListFilterState(key: string | undefined): ListFilterState | undefined { - if (!key || typeof localStorage === 'undefined') return undefined; - try { - const raw = localStorage.getItem(key); - if (!raw) return undefined; - const parsed = JSON.parse(raw); - if (!parsed || typeof parsed !== 'object') return undefined; - return parsed as ListFilterState; - } catch { - return undefined; - } -} - -// Debounce writes so a burst of FilterBuilder edits / search keystrokes hits -// localStorage once, not on every character. Pending patches merge per key so -// a filter change and a search change in the same window both land. -const pending: Record = {}; -const timers: Record> = {}; - -/** - * Merge a patch into the cached state for a key and flush (debounced). Only the - * keys present in `patch` are touched, so callers can persist `filters` and - * `search` independently. When the merged result is empty the key is removed to - * keep storage from filling with dead buckets. - */ -export function writeListFilterState(key: string | undefined, patch: ListFilterState): void { - if (!key || typeof localStorage === 'undefined') return; - const base = pending[key] ?? readListFilterState(key) ?? {}; - pending[key] = { ...base, ...patch }; - if (timers[key]) clearTimeout(timers[key]); - timers[key] = setTimeout(() => { - const next = pending[key] ?? {}; - delete pending[key]; - delete timers[key]; - try { - if (isEmptyState(next)) localStorage.removeItem(key); - else localStorage.setItem(key, JSON.stringify(next)); - } catch { - /* quota / private-mode — restoring filters is best-effort, never fatal */ - } - }, 300); -} - -/** - * Drop every write still waiting on the debounce, for every key. - * `ListPreferencesProvider` runs it before each `signOut()` and when a session - * ends any other way, so no write queued under the signed-out user's key lands - * after the sign-out sweep. - */ -export function discardPendingListFilterWrites(): void { - for (const key of Object.keys(timers)) { - clearTimeout(timers[key]); - delete timers[key]; - } - for (const key of Object.keys(pending)) delete pending[key]; -} - -/** Drop any cached (and pending) state for a key. */ -export function clearListFilterState(key: string | undefined): void { - if (!key) return; - if (timers[key]) { clearTimeout(timers[key]); delete timers[key]; } - delete pending[key]; - try { - if (typeof localStorage !== 'undefined') localStorage.removeItem(key); - } catch { - /* ignore */ - } -} diff --git a/ui/packages/app-shell/src/views/listLayoutStore.ts b/ui/packages/app-shell/src/views/listLayoutStore.ts new file mode 100644 index 00000000000..bb7a23262e9 --- /dev/null +++ b/ui/packages/app-shell/src/views/listLayoutStore.ts @@ -0,0 +1,321 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The list LAYOUT a reader keeps in this browser: per object, the order of the + * view tabs, and per view the column widths and the row height. + * + * These three only arrange what the list shows; they never change which + * records it shows. So they are this browser's alone (objectstack#35955): + * dragging a width, picking a row height or reordering the tabs writes + * nothing to the server, lights no Discard / Save, and never reaches another + * user, device or browser. Everything else a reader changes on a list is the + * list's draft (`./listDraftStore.ts`). + * + * ## Where it is kept + * + * One localStorage entry per reader and object, `list-layout::`: + * + * ```json + * { "viewOrder": ["", …], + * "perView": { "": { "widths": { "": 180 }, "rowHeight": "compact" } } } + * ``` + * + * The keys an earlier Console wrote for list state (`list-state:*`, the cache + * of the retired server row `ui.list.`; `list-filters:*`; + * `viewOrder:*`) are removed once per page load and never read: what they + * held is not carried over, so every list opens on its view's own layout + * until the reader changes it again. + * + * A sign-out clears this browser's storage, these entries with it + * (`@object-ui/auth`'s signed-out purge). + * + * @module + */ + +import { useCallback, useSyncExternalStore } from 'react'; +import { useAuth } from '@object-ui/auth'; +import { ROW_HEIGHT_TO_DENSITY_MODE, type RowHeight } from '@object-ui/core'; + +// --------------------------------------------------------------------------- +// The entry's shape +// --------------------------------------------------------------------------- + +/** One view's layout: the widths the reader dragged and the row height they picked. */ +export interface ListViewLayout { + /** Column width in pixels, by field name. */ + widths?: Record; + /** One of the spec's row heights; the view's own `rowHeight` while absent. */ + rowHeight?: RowHeight; +} + +/** One object's layout: the tab order and each view's layout. */ +export interface ObjectListLayout { + viewOrder?: string[]; + perView?: Record; +} + +/** + * A patch to one view's layout. A part present as `null` (or, for `widths`, + * an empty map) goes back to the view's own; an absent part is left as it is. + */ +export interface ListViewLayoutPatch { + widths?: Record | null; + rowHeight?: RowHeight | null; +} + +/** The localStorage key family this module owns. */ +export const LIST_LAYOUT_STORAGE_PREFIX = 'list-layout'; + +/** The localStorage key of one reader's layout for one object. */ +export function listLayoutStorageKey(userId: string | null | undefined, objectName: string): string { + return `${LIST_LAYOUT_STORAGE_PREFIX}:${userId || 'anon'}:${objectName}`; +} + +/** + * The key prefixes an earlier Console wrote list state under. Removed, never + * read ({@link clearRetiredListStateKeys}). + */ +export const RETIRED_LIST_STATE_KEY_PREFIXES: readonly string[] = Object.freeze([ + 'list-state:', + 'list-filters:', + 'viewOrder:', +]); + +const EMPTY: ObjectListLayout = Object.freeze({}) as ObjectListLayout; + +// --------------------------------------------------------------------------- +// Pure helpers +// --------------------------------------------------------------------------- + +const isRecord = (v: unknown): v is Record => + !!v && typeof v === 'object' && !Array.isArray(v); + +function sanitizeWidths(v: unknown): Record | undefined { + if (!isRecord(v)) return undefined; + const out: Record = {}; + for (const [field, width] of Object.entries(v)) { + if (field && typeof width === 'number' && Number.isFinite(width) && width > 0) out[field] = width; + } + return Object.keys(out).length > 0 ? out : undefined; +} + +function sanitizeRowHeight(v: unknown): RowHeight | undefined { + return typeof v === 'string' && Object.prototype.hasOwnProperty.call(ROW_HEIGHT_TO_DENSITY_MODE, v) + ? (v as RowHeight) + : undefined; +} + +function sanitizeViewLayout(v: unknown): ListViewLayout | undefined { + if (!isRecord(v)) return undefined; + const out: ListViewLayout = {}; + const widths = sanitizeWidths(v.widths); + if (widths) out.widths = widths; + const rowHeight = sanitizeRowHeight(v.rowHeight); + if (rowHeight) out.rowHeight = rowHeight; + return out.widths || out.rowHeight ? out : undefined; +} + +/** Keep only the parts of a stored value this entry declares, well formed. */ +export function sanitizeObjectListLayout(v: unknown): ObjectListLayout { + if (!isRecord(v)) return {}; + const out: ObjectListLayout = {}; + if (Array.isArray(v.viewOrder)) { + const ids = v.viewOrder.filter((id): id is string => typeof id === 'string' && id.length > 0); + if (ids.length > 0) out.viewOrder = ids; + } + if (isRecord(v.perView)) { + const perView: Record = {}; + for (const [viewId, view] of Object.entries(v.perView)) { + const clean = sanitizeViewLayout(view); + if (viewId && clean) perView[viewId] = clean; + } + if (Object.keys(perView).length > 0) out.perView = perView; + } + return out; +} + +/** Apply a patch to one view's layout. Pure; a view left with nothing is removed. */ +export function patchViewLayout( + state: ObjectListLayout, + viewId: string, + patch: ListViewLayoutPatch, +): ObjectListLayout { + const current: Record = { ...(state.perView?.[viewId] ?? {}) }; + for (const key of ['widths', 'rowHeight'] as const) { + if (!(key in patch)) continue; + const value = patch[key]; + if (value === undefined || value === null) delete current[key]; + else current[key] = value; + } + const clean = sanitizeViewLayout(current); + const perView = { ...(state.perView ?? {}) }; + if (clean) perView[viewId] = clean; + else delete perView[viewId]; + const next: ObjectListLayout = { ...state }; + if (Object.keys(perView).length > 0) next.perView = perView; + else delete next.perView; + return next; +} + +/** Set (or, with an empty list, clear) the object's tab order. Pure. */ +export function setViewOrderLayout(state: ObjectListLayout, ids: readonly string[]): ObjectListLayout { + const next: ObjectListLayout = { ...state }; + if (ids.length > 0) next.viewOrder = [...ids]; + else delete next.viewOrder; + return next; +} + +// --------------------------------------------------------------------------- +// localStorage +// --------------------------------------------------------------------------- + +function storage(): Storage | undefined { + try { + return typeof localStorage === 'undefined' ? undefined : localStorage; + } catch { + return undefined; + } +} + +/** + * Remove every key an earlier Console wrote list state under + * ({@link RETIRED_LIST_STATE_KEY_PREFIXES}). Never throws. + */ +export function clearRetiredListStateKeys(): void { + const store = storage(); + if (!store) return; + try { + const retired: string[] = []; + for (let i = 0; i < store.length; i++) { + const key = store.key(i); + if (key && RETIRED_LIST_STATE_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) retired.push(key); + } + for (const key of retired) store.removeItem(key); + } catch { + /* storage unavailable: nothing to clear */ + } +} + +let retiredKeysCleared = false; +function clearRetiredListStateKeysOnce(): void { + if (retiredKeysCleared) return; + retiredKeysCleared = true; + clearRetiredListStateKeys(); +} + +/** This browser's layout for the reader and object; `{}` when there is none. */ +export function readListLayout(userId: string | null | undefined, objectName: string): ObjectListLayout { + const store = storage(); + if (!objectName || !store) return {}; + try { + const raw = store.getItem(listLayoutStorageKey(userId, objectName)); + return raw == null ? {} : sanitizeObjectListLayout(JSON.parse(raw)); + } catch { + return {}; + } +} + +// One snapshot per key and stored text, so `useSyncExternalStore` sees the +// same object until the entry changes. +const snapshots = new Map(); +const listeners = new Set<() => void>(); + +function snapshotOf(key: string): ObjectListLayout { + let raw: string | null = null; + try { + raw = storage()?.getItem(key) ?? null; + } catch { + raw = null; + } + const held = snapshots.get(key); + if (held && held.raw === raw) return held.value; + let value: ObjectListLayout = EMPTY; + if (raw != null) { + try { + value = sanitizeObjectListLayout(JSON.parse(raw)); + } catch { + value = EMPTY; + } + } + snapshots.set(key, { raw, value }); + return value; +} + +/** Write the reader's layout for the object to this browser. Never throws. */ +export function writeListLayout( + userId: string | null | undefined, + objectName: string, + state: ObjectListLayout, +): void { + const store = storage(); + if (!objectName || !store) return; + const key = listLayoutStorageKey(userId, objectName); + try { + if (!state.viewOrder && !state.perView) store.removeItem(key); + else store.setItem(key, JSON.stringify(state)); + } catch { + /* quota / private mode: the layout is best-effort */ + } + for (const listener of [...listeners]) listener(); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Test seam: forget the held snapshots and let the retired-key sweep run again. */ +export function resetListLayoutStoreForTests(): void { + snapshots.clear(); + retiredKeysCleared = false; +} + +// --------------------------------------------------------------------------- +// Hook +// --------------------------------------------------------------------------- + +export interface ObjectListLayoutHandle { + /** The reader's layout for this object in this browser; `{}` when there is none. */ + layout: ObjectListLayout; + /** Keep the reader's tab order. */ + setViewOrder(ids: readonly string[]): void; + /** Keep (or clear, see {@link ListViewLayoutPatch}) part of one view's layout. */ + patchView(viewId: string, patch: ListViewLayoutPatch): void; +} + +/** The signed-in reader's list layout for one object, in this browser. */ +export function useObjectListLayout(objectName: string | undefined): ObjectListLayoutHandle { + clearRetiredListStateKeysOnce(); + const { user } = useAuth(); + const userId = user?.id ?? null; + const name = objectName ?? ''; + const key = listLayoutStorageKey(userId, name); + const layout = useSyncExternalStore( + subscribe, + () => (name ? snapshotOf(key) : EMPTY), + () => EMPTY, + ); + + const update = useCallback( + (fn: (prev: ObjectListLayout) => ObjectListLayout) => { + if (!name) return; + const prev = readListLayout(userId, name); + const next = fn(prev); + if (JSON.stringify(next) === JSON.stringify(prev)) return; + writeListLayout(userId, name, next); + }, + [name, userId], + ); + const setViewOrder = useCallback( + (ids: readonly string[]) => update((prev) => setViewOrderLayout(prev, ids)), + [update], + ); + const patchView = useCallback( + (viewId: string, patch: ListViewLayoutPatch) => { + if (!viewId) return; + update((prev) => patchViewLayout(prev, viewId, patch)); + }, + [update], + ); + return { layout, setViewOrder, patchView }; +} diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index dd0fa7f6e13..ab5edf065ab 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -12,7 +12,8 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, lazy, Suspense, type ReactNode } from 'react'; import { DENSITY_MODE_TO_ROW_HEIGHT, columnIdentity, normalizeListViewSchema, servedPackageId, type FilterTokenScope } from '@object-ui/core'; import { listDraftPreference, type useListDraft } from './listDraftStore.js'; -import type { useObjectListPreferences, ListViewPreference, ListViewPreferencePatch } from '../context/ListPreferencesProvider.js'; +import type { useObjectListLayout } from './listLayoutStore.js'; +import type { ListViewPreference } from './listDraftStore.js'; const ObjectChart = lazy(() => import('@object-ui/plugin-charts').then((m) => ({ default: m.ObjectChart })), ); @@ -86,7 +87,7 @@ export function useObjectViewListRenderer({ managedUsers, managedUserMarker, savedViews, - listPrefs, + listLayout, listDraft, derivedColumnViewIds, baseView, @@ -125,7 +126,7 @@ export function useObjectViewListRenderer({ managedUsers: ReturnType['managedUsers']; managedUserMarker: ReturnType['managedUserMarker']; savedViews: Parameters[0]['savedViews']; - listPrefs: ReturnType; + listLayout: ReturnType; /** objectstack#35955 — the open list's unsaved changes, and their writer. */ listDraft: ReturnType; derivedColumnViewIds: Set; @@ -328,23 +329,23 @@ export function useObjectViewListRenderer({ // objectstack#35955 — the list's DRAFT (`./listDraftStore.ts`): its // sort, filters, grouping and search arrive through the seed below, // its columns and their order here. The column widths and the row - // height are the reader's own (`listPrefs`), never a draft: they are - // laid in from what the reader stored, and nothing else stored is. + // height are the reader's layout in this browser (`listLayout`), never + // a draft. const viewPref: ListViewPreference | undefined = listDraftPreference( listDraft.draft, - listPrefs.preference.perView?.[viewDef.id], + listLayout.layout.perView?.[viewDef.id], ); const persistListSort = (sort: Array<{ field: string; order?: string }>) => { listDraft.patch({ sort: sort as ListViewPreference['sort'] }); }; // One report carries the order and the widths: the order is a draft, - // the widths are kept for the reader (a drag that changed only a width + // the widths are the reader's layout (a drag that changed only a width // hands back the order the draft already holds). const persistListColumnState = (state: { order?: string[]; widths?: Record }) => { listDraft.patch({ columnOrder: state.order && state.order.length > 0 ? state.order : undefined }); - const storedWidths = listPrefs.preference.perView?.[viewDef.id]?.columnState?.widths; - if (JSON.stringify(state.widths ?? {}) !== JSON.stringify(storedWidths ?? {})) { - listPrefs.patchView(viewDef.id, { columnState: state.widths ? { widths: state.widths } : null }); + const keptWidths = listLayout.layout.perView?.[viewDef.id]?.widths; + if (JSON.stringify(state.widths ?? {}) !== JSON.stringify(keptWidths ?? {})) { + listLayout.patchView(viewDef.id, { widths: state.widths ?? null }); } }; // objectui#11860 — what the list opens with: the URL's state, else this @@ -484,13 +485,6 @@ export function useObjectViewListRenderer({ ); } - // objectui#12418 — the list opens on the user's stored sort and - // filters, which are read in the console's one preference read; until - // that read has answered, there is nothing to open on yet. - if (!listPrefs.ready) { - return
; - } - // ADR-0053 wrong-context authoring: userFilters/quickFilters on an // object list view are suppressed below — say so instead of letting // the author stare at a toolbar with nothing where their filter @@ -580,22 +574,18 @@ export function useObjectViewListRenderer({ * objectstack#28948 — a reset to the view's own is not a choice. The * list's "Reset to view default" (the Display control's, the sort * popover's) names the parts it put back, and they are CLEARED from - * this user's stored state rather than stored as the view's values, so - * a later change to the view reaches them. A view left with nothing is - * removed (`patchViewPreference`). + * the draft and the reader's layout rather than kept as the view's + * values, so a later change to the view reaches them. * The sort leaves the URL too, which would otherwise seed it again. * A deliberate `sort: []` or `hiddenFields: []` still arrives through - * `persistListSort` / `persistHiddenFields` and stays stored. + * `persistListSort` / `persistHiddenFields` and stays in the draft. */ const restoreViewDefaults = (parts: ReadonlyArray<'sort' | 'hiddenFields' | 'rowHeight'>) => { // objectstack#35955 — the sort and the hidden fields leave the - // draft; the row height is the reader's stored choice. + // draft; the row height leaves the reader's layout. if (parts.includes('sort')) listDraft.patch({ sort: undefined }); if (parts.includes('hiddenFields')) listDraft.patch({ hiddenFields: undefined }); - if (parts.includes('rowHeight')) { - const patch: ListViewPreferencePatch = { rowHeight: null }; - listPrefs.patchView(viewDef.id, patch); - } + if (parts.includes('rowHeight')) listLayout.patchView(viewDef.id, { rowHeight: null }); if (parts.includes('sort')) writeListUrlState({ sort: null }); }; @@ -682,12 +672,11 @@ export function useObjectViewListRenderer({ viewPref?.rowHeight ?? (normalizeListViewSchema(viewDef ?? {}) as Pick).rowHeight ?? listSchema.rowHeight, - // Hydrate the persisted settings so they survive reload. The sort - // and the column layout (objectui#12418), the density and the - // hidden fields (objectui#12474) are the USER's: they are read - // from and written to `listPrefs`, never `/meta/view`. No list - // toolbar control writes the shared view; the view editor's - // explicit save does. + // The sort, the column order and the hidden fields are the list's + // draft; the widths and the density are the reader's layout in + // this browser (`listLayout`). Neither writes `/meta/view`: no list + // toolbar control writes the shared view; Save and the view + // editor's explicit save do. // // objectui#11860 — a sort the URL carries is applied over the // view's: an opened link sorts as it was sorted. Without a link, @@ -767,16 +756,16 @@ export function useObjectViewListRenderer({ fieldOrder: activeViewDeclaresColumns ? (viewDef.fieldOrder ?? listSchema.fieldOrder) : undefined, - // objectui#12418 — the user's column layout over the view's. `{}` - // when neither has one: this host persists the layout, so the + // The draft's column order and the reader's widths over the view's. + // `{}` when neither has one: this host keeps the layout, so the // grid's own per-browser fallback must not stand in for it (and a - // "Reset view" must reach the grid). + // Discard must reach the grid). columnState: viewPref?.columnState ?? (viewDef as any).columnState ?? (listSchema as any).columnState ?? {}, onDensityChange: (mode) => { - // objectui#12474 — the USER's density, on their own list state, - // never the shared view. Stored as the spec-canonical - // `rowHeight` (#2890), the vocabulary the rung above reads. - listPrefs.patchView(viewDef.id, { + // objectui#12474 — the reader's density, on their layout in + // this browser, never the shared view. Kept as the + // spec-canonical `rowHeight`, the vocabulary the rung above reads. + listLayout.patchView(viewDef.id, { rowHeight: DENSITY_MODE_TO_ROW_HEIGHT[mode], }); }, @@ -1202,7 +1191,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); + }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listLayout.layout, listLayout.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index 4708e60e451..fd3e9620955 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -27,11 +27,6 @@ import { type ListUrlState, type ListSortRule, } from './userFilterUrlState.js'; -import type { - useObjectListPreferences, - ListFilterGroupPreference, - ListSortPreference, -} from '../context/ListPreferencesProvider.js'; import { claimListDraft, discardListDraft, @@ -39,6 +34,8 @@ import { readListDraft, takeDocumentReload, type ListDraft, + type ListFilterGroupPreference, + type ListSortPreference, } from './listDraftStore.js'; import { parseUrlEqualityFilterTriples } from './drillUrlFilters.js'; import { selectFilterParams } from './objectViewHelpers.js'; @@ -140,7 +137,6 @@ export function useObjectViewListUrlState({ objectDef, activeView, viewResolving, - listPrefs, listDraft, perms, user, @@ -156,7 +152,6 @@ export function useObjectViewListUrlState({ * `activeView` is only the view the page falls back to meanwhile. */ viewResolving: boolean; - listPrefs: ReturnType; /** objectstack#35955 — the open list's unsaved changes (`./listDraftStore.ts`). */ listDraft: ListDraft; perms: ReturnType; @@ -183,10 +178,7 @@ export function useObjectViewListUrlState({ * the Filter panel's conditions, the search term, the sort and the * grouping the reader changed and has not saved, kept while they open * a record and come back; the view's own for every part the draft - * lacks. Nothing the reader stored earlier is read: their stored sort - * and filters (objectui#12418) no longer apply. The seed still waits - * for the stored state to be read (`listPrefs.ready`): the column - * widths and the row height are kept there. + * lacks. Nothing the reader stored earlier is read. * * A RELOAD is neither (objectstack#35955): the first list a reloaded page * seeds opens as its view declares it, and the write-back strips the @@ -262,7 +254,7 @@ export function useObjectViewListUrlState({ // (just dropped) draft, never from the `uf_*` params, whoever wrote them, // and its write-back strips them all. const resetPendingRef = useRef(false); - if (listIdentityKey && listPrefs.ready && !viewResolving && listSeedRef.current?.key !== listIdentityKey) { + if (listIdentityKey && !viewResolving && listSeedRef.current?.key !== listIdentityKey) { // objectstack#35955 — this list is the one on screen: a draft held // for another view or object goes. const draftScope = listDraftScope(user?.id, objectName ?? '', String(activeView.id)); @@ -324,12 +316,11 @@ export function useObjectViewListUrlState({ toast.warning(t('console.objectView.linkFilterRefused')); } // Once per list identity, by design: later URL writes are the list's - // own changes, already on screen. (`listPrefs.ready` and - // `viewResolving` because the seed is taken only once the user's own - // state has been read and the view the address names is resolved; a + // own changes, already on screen. (`viewResolving` because the seed is + // taken only once the view the address names is resolved; a // resolution that ends on the fall-back keeps the identity unchanged.) // eslint-disable-next-line react-hooks/exhaustive-deps -- see above - }, [listIdentityKey, listPrefs.ready, viewResolving]); + }, [listIdentityKey, viewResolving]); /** * objectstack#30073 — the Filter panel's group as the list last reported * it, held with the list identity it came from. The address cannot say diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index bac5e656520..86d94a861cf 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -13,7 +13,7 @@ import { useParams, type useNavigate } from 'react-router-dom'; import { formatMetadataError } from '@object-ui/data-objectstack'; import { toast } from 'sonner'; import type { useObjectTranslation } from '@object-ui/i18n'; -import type { useObjectListPreferences } from '../context/ListPreferencesProvider.js'; +import type { useObjectListLayout } from './listLayoutStore.js'; import { PREVIEW_QUERY_FLAG, PREVIEW_QUERY_VALUE } from '../preview/PreviewModeContext.js'; import type { usePreviewDrafts } from '../preview/PreviewModeContext.js'; import { isSavedViewId } from '../utils/viewIdentity.js'; @@ -73,7 +73,7 @@ export function useObjectViewViewCrud({ setRefreshKey, confirmHandler, savedViews, - listPrefs, + listLayout, views, activeViewId, baseView, @@ -93,15 +93,15 @@ export function useObjectViewViewCrud({ setRefreshKey: Dispatch>; confirmHandler: ReturnType['confirmHandler']; savedViews: Parameters[0]['savedViews']; - listPrefs: ReturnType; + listLayout: ReturnType; views: ReturnType; activeViewId: string | undefined; baseView: ReturnType[number]; }) { const createApp = useRuntimeCreateApp(t); // objectui#12504 — no toolbar control writes the shared view. The sort and - // the column layout (objectui#12418), the density and the Hide Fields - // popover (objectui#12474) are the user's own list state (`listPrefs`), and + // the columns are the list's draft (`./listDraftStore.ts`), the widths and + // the density the reader's layout in this browser (`listLayout`), and // the shared view is written only by an explicit save // (`handleViewConfigSave`, below). The toolbar-to-view writer that lived // here, `persistViewPatch`, retired with the adapter method it was the last @@ -112,7 +112,7 @@ export function useObjectViewViewCrud({ * There is deliberately NO `persistViewFilter` here (objectui#4155). * * The list toolbar's filter panel is the USER's state — it belongs to the - * session and to that user's own list state (`listPrefs`, objectui#12418), + * session and to the list's draft (`./listDraftStore.ts`), * not to the view's stored body. It used to persist: every `onFilterChange` the panel * emitted was folded and written to the view overlay, so merely opening the * panel and clicking `Add filter` wrote an incomplete `field equals ''` @@ -431,20 +431,15 @@ export function useObjectViewViewCrud({ }, [dataSource, objectName, savedViews, isSavedView, t]); /** - * A drag in Manage Views reorders the tabs FOR THIS USER (objectui#12418). - * - * It used to write `viewOrder:` to this browser and then PATCH a - * `sortOrder` onto every saved view's shared row, "so other sessions / - * users can pick up the order": one user's drag reordered the tabs for - * everyone, and under a walled posture the metadata write was refused. The - * order is now the user's preference (the `ui.list.` row, through - * `listPrefs`), and nothing here writes `/meta/view`. The authored order — - * the declared sequence, then a stored `sortOrder` — stays every user's - * default, and the view editor is where an author changes it. + * A drag in Manage Views reorders the tabs FOR THIS READER, in this + * browser (`listLayout`, `./listLayoutStore.ts`). Nothing here writes + * `/meta/view` or any other server row: the authored order — the declared + * sequence, then a stored `sortOrder` — stays every user's default, and + * the view editor is where an author changes it. */ const handleReorderViews = useCallback((orderedIds: string[]) => { - listPrefs.setViewOrder(orderedIds); - }, [listPrefs.setViewOrder]); + listLayout.setViewOrder(orderedIds); + }, [listLayout.setViewOrder]); const handleConfigView = useCallback((vid: string) => { // System (metadata-defined) views are read-only — opening the diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index 31f28e5901a..0e96e66a9a8 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -38,7 +38,7 @@ import type { DataSource } from '@object-ui/types'; import { foldFilterGroupToSpecRules, type FilterFoldRefusal } from './viewFilterFold.js'; import { buildViewConfigSaveBody } from './objectViewTabs.js'; import type { ListSortRule, ListUrlState } from './userFilterUrlState.js'; -import type { ListViewPreference } from '../context/ListPreferencesProvider.js'; +import type { ListViewPreference } from './listDraftStore.js'; /** The object a personal view is a row of. */ export const PERSONAL_VIEW_OBJECT = 'sys_personal_view'; @@ -163,7 +163,7 @@ export function personalViewPanelFilters( export interface PersonalViewListState { /** The toolbar state the address carries (`uf_*`); an absent part is the view's own. */ url: Pick; - /** The reader's stored state for the view (`ui.list.`), if any. */ + /** The list's draft with the reader's layout (`listDraftPreference`), if any. */ preference?: ListViewPreference; /** * The open view's own conditions when the Filter panel holds them as rows diff --git a/ui/packages/data-objectstack/README.md b/ui/packages/data-objectstack/README.md index ea4400c82a8..117c57362b2 100644 --- a/ui/packages/data-objectstack/README.md +++ b/ui/packages/data-objectstack/README.md @@ -1070,8 +1070,8 @@ for the full design. ### Key families Some state is one row per subject, and which subjects exist is only known -from the rows: the console keeps each object's list state under -`ui.list.`. `createObjectStackUserPreferenceFamily` loads every row +from the rows: the console keeps each object's record-page state under +`ui.record.`. `createObjectStackUserPreferenceFamily` loads every row whose key starts with a prefix, and writes one key's row at a time: ```typescript @@ -1080,14 +1080,14 @@ import { createObjectStackUserPreferenceFamily, type ObjectStackAdapter } from ' declare const dataSource: ObjectStackAdapter; declare const user: { id: string }; -const lists = createObjectStackUserPreferenceFamily<{ viewOrder?: string[] }>({ +const records = createObjectStackUserPreferenceFamily<{ showEmptyFields?: boolean }>({ dataSource, userId: user.id, - prefix: 'ui.list.', + prefix: 'ui.record.', }); -const rows = await lists.load(); // { 'ui.list.account': { viewOrder: [...] }, ... } -await lists.save('ui.list.account', { viewOrder: ['account.mine', 'account.all'] }); +const rows = await records.load(); // { 'ui.record.account': { showEmptyFields: true }, ... } +await records.save('ui.record.account', { showEmptyFields: false }); ``` A family's `load()` joins the same shared read as the per-key adapters' loads diff --git a/ui/packages/data-objectstack/src/userState.ts b/ui/packages/data-objectstack/src/userState.ts index 9954a10163d..cc83ff8dd31 100644 --- a/ui/packages/data-objectstack/src/userState.ts +++ b/ui/packages/data-objectstack/src/userState.ts @@ -62,9 +62,9 @@ * ## A family of keys in the same read (objectui#12418) * * Some state is one row per subject the console cannot name at load time: the - * list state of every object a user has opened is a row per object, - * `ui.list.`, and which objects those are is only known from the rows - * themselves. {@link createObjectStackUserPreferenceFamily} loads such a family + * record-page state of every object a user has opened is a row per object, + * `ui.record.`, and which objects those are is only known from the + * rows themselves. {@link createObjectStackUserPreferenceFamily} loads such a family * by its key PREFIX, and joins the same shared read: the read then asks for its * keys OR any key starting with the prefix, still one request. A prefix bounds * nothing the way the unique index bounds a key, so the read asks for at most @@ -467,9 +467,9 @@ export interface ObjectStackUserPreferenceFamilyOptions { /** Authenticated user id. */ userId: string; /** - * The family's key prefix, dotted and ending in a dot, e.g. `ui.list.`: the + * The family's key prefix, dotted and ending in a dot, e.g. `ui.record.`: the * family is every key that starts with it, one row per subject - * (`ui.list.account`, `ui.list.contact`, …). + * (`ui.record.account`, `ui.record.contact`, …). */ prefix: string; /** Override the storage object name. Defaults to `"sys_user_preference"`. */ From bb6ae86a7fed259f94f20aa822e7e514fed46605 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:03:58 +0000 Subject: [PATCH 2/6] wip: list layout tests rewritten; os migrate list-preferences boots identity objects Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- .changeset/35955-list-layout-in-browser.md | 22 + content/docs/deployment/cli.mdx | 38 +- content/docs/ui/views.mdx | 7 +- content/docs/upgrading.mdx | 2 + .../areas/records-forms.json | 36 +- .../list-preferences.integration.test.ts | 11 +- .../src/commands/migrate/list-preferences.ts | 12 +- .../cli/test/json-stdout-purity.e2e.test.ts | 4 + .../migrate-confirmation-exit.pin.test.ts | 2 + .../src/pages/sys-user.page.ts | 2 +- .../consoleUserPreferenceBudget.test.tsx | 74 +-- ...ListPreferencesProvider.slot-12418.test.ts | 186 ------- .../context/__tests__/signOutPurge.test.tsx | 228 ++------- ...ew.emptyColumnsNoProjection-10694.test.tsx | 10 +- ...ObjectView.listPersonalized-28950.test.tsx | 88 ++-- .../ObjectView.listUrlState-11860.test.tsx | 6 +- .../views/ObjectView.overlayPatchOnly.test.ts | 2 +- .../ObjectView.personalViews-29635.test.tsx | 84 ++- ...ctView.toolbarWritesCompose-11642.test.tsx | 13 +- .../ObjectView.ufViewSwitch-11992.test.tsx | 3 +- .../ObjectView.userListState-12418.test.tsx | 481 +++++++++--------- .../views/listLayoutStore.slot-35955.test.tsx | 170 +++++++ .../app-shell/src/views/listLayoutStore.ts | 31 +- ...ViewViewCrud.draftBarChange-35932.test.tsx | 2 +- .../src/views/objectViewViewCrud.tsx | 5 +- .../views/view-filter-fold.ratchet.test.ts | 2 +- .../context/RecordPagePreferencesContext.tsx | 5 +- 27 files changed, 705 insertions(+), 821 deletions(-) create mode 100644 .changeset/35955-list-layout-in-browser.md delete mode 100644 ui/packages/app-shell/src/context/__tests__/ListPreferencesProvider.slot-12418.test.ts create mode 100644 ui/packages/app-shell/src/views/listLayoutStore.slot-35955.test.tsx diff --git a/.changeset/35955-list-layout-in-browser.md b/.changeset/35955-list-layout-in-browser.md new file mode 100644 index 00000000000..71d25f08123 --- /dev/null +++ b/.changeset/35955-list-layout-in-browser.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/data-objectstack': patch +'@object-ui/react': patch +'@objectstack/platform-objects': patch +--- + +feat(console): a list's column widths, row height and tab order are kept in this browser only + +Clause-②: no +Metadata-protocol: none + +On a Console object list, the column widths a reader drags, the row height they pick and the order they give the view tabs are now kept in their own browser only, per signed-in user and object (localStorage `list-layout::`). Nothing is sent to the server: the Console no longer reads or writes the per-user list preference row `sys_user_preference` `ui.list.`, and its boot read of the reader's preferences no longer asks for that key family. A list opens at once, without waiting for that read. + +- Another browser or device opens the list on its view's own widths, row height and tab order until the reader changes them there. +- Signing out clears these entries with the rest of this browser's Console state, as before. +- With nobody signed in, nothing is kept. +- The record page's "show empty fields" choice (`ui.record.`) is unchanged and still follows the reader. + +Upgrade note: what an earlier Console kept for a reader's lists is not carried over. The `ui.list.` rows are no longer read, so every reader's lists open on their views' own widths, row height and tab order until they change them again. This browser's old copies (`list-state:*`, `list-filters:*` and `viewOrder:*` in localStorage) are removed on the first list the Console opens. The server rows stay where they are, unread; leaving them does no harm. + +`@object-ui/data-objectstack`, `@object-ui/react` and `@objectstack/platform-objects` change only comments and a README example that named the retired key. No metadata key, value or default changes. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 3a5e2f5979d..fff2df462a4 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1541,6 +1541,7 @@ where the data lives. | `os migrate record-currency-codes` | Write the currency code you give into the rows of a record-mode currency field that hold an amount and no code, the rows stored before the field was switched to `currencyMode: 'record'`. The code is never derived. No flag; idempotent. See [below](#os-migrate-record-currency-codes) | | `os migrate recompute-home-amounts` | Recompute the home-currency amounts a record-mode currency field stores, at the exchange rates in force now, after a rate is corrected or added. Reports the rows that change and lists, without writing, the rows it cannot convert. No flag; idempotent. See [below](#os-migrate-recompute-home-amounts) | | `os migrate comment-reactions` | Carry the emoji reactions a 17.x deployment stored in the retired `sys_comment.reactions` column into `sys_comment_reaction` records, list every stored value that does not read, and record the verified run that lets `os migrate apply --allow-destructive` drop the column | +| `os migrate list-preferences` | Remove the per-user list preference rows (`sys_user_preference` keys starting with `ui.list.`) that the Console no longer reads. Dry run by default; `--apply` deletes only with `--export`, which writes every row it deletes to a file first. No flag. See [below](#os-migrate-list-preferences) | | `os migrate organization-ownership` | The v18 ownership ceremony (ADR-0131 D10): write a plan of what each table's rows will become, then `--apply` that reviewed plan. It upgrades a database 17.x or an 18.0 pre-release (`18.0.0-next.*`) created; a v18 server refuses to start on one until it has run. See [below](#os-migrate-organization-ownership) | | `os migrate activity-changed-fields` | Stamp the two read-rule columns (`changed_fields`, `milestone_key`) on the `sys_activity` rows written before they existed. Until it runs, those rows are withheld from every reader but the system, so run it at once after upgrading. No flag; idempotent | | `os migrate audit-mail-bodies` | Mask the mail bodies (`body_text`, `body_html`) that `sys_audit_log` and `sys_activity` copies of `sys_email` / `sys_identity_email` rows still hold in clear, written before the audit writer masked them. Covers the `archive` datasource `sys_audit_log` archives to as well. Reports counts only. No flag; idempotent. See [below](#os-migrate-audit-mail-bodies) | @@ -1565,7 +1566,7 @@ A read-only data command does not read a table it found missing, since that tabl holds nothing, and answers with empty work and exit 0. `os migrate value-shapes` is clean over zero records and names the objects it did not read. `os migrate recorded-by` has nothing to convert and `os migrate resume` no interrupted runs. -`os migrate meta --stored` has no stored metadata to examine, `os migrate +`os migrate meta --stored` has no stored metadata to examine, `os migrate list-preferences` no preference row to report, `os migrate audit-metadata-bodies`, `os migrate audit-mail-bodies`, `os migrate audit-key-material` and `os migrate audit-side-copies` no audit copy to rewrite, and `os migrate account-issuer` no account to collide. `os secret orphans`, `os secret rewrap` and `os storage orphans` report no secret and no file. A read the command cannot avoid and that fails for any @@ -2063,6 +2064,41 @@ A run that lists an unreadable value or fails a write exits `1`, and so does an A database created on v18 never had the column: the run finds nothing, and there is no drop to wait for. +#### `os migrate list-preferences` + +The Console used to keep one `sys_user_preference` row per user and object, keyed +`ui.list.`, holding that user's state for the object's lists: the order of +the view tabs and, per view, a sort, filters, a column layout, a row height and +hidden or added columns. It keeps none of that on the server any more. A change a +reader makes on a list is a draft that they save into a view or discard, and the +column widths, the row height and the tab order are kept in the reader's own +browser. Nothing reads the old rows, so leaving them does no harm. This command +removes them. What they held is not carried over: every list opens on its view's +own layout until the reader changes it again. + +```bash +os migrate list-preferences # Dry run: how many rows, for how many users and which objects +os migrate list-preferences --apply --export ./list-preferences-backup.json +os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json # CI / scripts +``` + +**Options:** +- `--apply` — delete the listed rows (default off: a read-only dry run that writes nothing) +- `--export ` — **mandatory with `--apply`**: every row the run deletes, as stored, written + owner-only and read back before the first delete; refuses to overwrite an existing file +- `-y, --yes` — skip the confirmation prompt +- `--force` — apply even when another process is using the SQLite file +- `--database-url `, `--json` + +Only keys that start with `ui.list.` are touched. Every other preference row, +`ui.record.` included, stays as it is. The rows are deleted by id, the ones +the export holds and no others, and none of them enters the recycle bin. The run then +reads the prefix again. If a row remains, or was written since by a Console that has +not been upgraded, it is reported and the run exits `1`; run it again once every +Console is upgraded. A run that finds nothing writes no export and exits `0`. It is +never run for you: nothing on any boot, upgrade, migrate or lifecycle path invokes it, +and it records no `sys_migration` verdict, because nothing waits for one. + #### `os migrate activity-changed-fields` An activity row is served to a reader only when the platform can judge it for diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 51f39eb660a..cc697b620f0 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -634,12 +634,11 @@ whose menu also holds Discard on a narrow list or a phone). - The draft survives opening a record and coming back. Opening another view or object, or reloading the list's page, drops it, so that reload opens the view as it is declared. - Column widths, the row height (density) and the views' order are not a draft: they are - remembered in this browser only, per user and object (localStorage - `list-layout::`). Nothing is sent to the server, another browser or device + remembered in this browser only, per signed-in user and object (localStorage + `list-layout::`). Nothing is sent to the server, another browser or device opens the view's own layout, and signing out clears them with the rest of this browser's Console state. Earlier Consoles kept them, with a stored sort and filters, in the user's - `sys_user_preference` row `ui.list.`; nothing reads that row now, and - `os migrate list-preferences` removes such rows. + `sys_user_preference` row `ui.list.`; nothing reads that row now. - A link carrying list state (`uf_*` parameters) applies it as a draft, whether it opens in a new tab or in-app (an AI answer's list link, after a reload of the chat page too). - When a session ends, the sign-in page's return link keeps the list's path but never its diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index 5f48d0b1765..035474a49cf 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -493,6 +493,8 @@ the protocol-18 step, which `os migrate meta --from 17` lists for your sources **Upgrading from 18.5.0 or earlier:** the first [`os migrate plan`](/docs/deployment/cli#schema-migrations) after the move lists a safe `create_index` for each `(created_at, id)` and `(owner_id)` index schema sync now builds without a declaration, and on SQLite a `normalize_boolean_storage` step for boolean cells stored as text; the next sync or `os migrate apply` builds them, and neither is destructive. Where an app declares `lifecycle.seal`, an `os migrate audit-* --apply` run on SQLite or Turso now needs every sealing server stopped and `--sealer-stopped` ([18.6.0 checklist](/docs/releases/v18/18-6#upgrade-checklist)). +**Upgrading from 18.6.0 or earlier:** the Console no longer reads the per-user list preference rows (`sys_user_preference` keys `ui.list.`). A reader's column widths, row height and view tab order are kept in their own browser from now on, so each list opens on its view's own layout until the reader changes it again. To clear the old rows, run [`os migrate list-preferences`](/docs/deployment/cli#os-migrate-list-preferences) once all your Consoles are upgraded, a dry run first and then `--apply --export `. Leaving them does no harm: nothing reads them. + The v17 and v18 lines are broken out per release. Each v17 minor shipped breaking changes under the repo's launch-window convention — which ships a breaking change as `minor` rather than `major`, so the version number is not the diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 72796054f19..8f862e4dcd0 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -2932,7 +2932,7 @@ "title": "User-built FilterBuilder/SortBuilder toolbar merges with the view filter, restores across nav, and reproduces rows from the URL", "since": "v16", "status": "active", - "revision": 13, + "revision": 14, "priority": "P1", "surface": "browser", "personas": [ @@ -2954,8 +2954,8 @@ "open Filter in the condition row under the view bar (since objectstack#35878 the bar has no Filter or Sort button: the row is always there, with a dashed 「Filter」 button while no filter of the reader's own is set and a 「+」 after the filter chips once one is, both data-testid condition-add-filter; Sort is the row's first control, the dashed 「Sort」 button or, once sorted, the one sort chip 「Sorted by X +N」, data-testid condition-sort, ui/packages/plugin-list/src/conditions/ListConditionControls.tsx). Since objectstack#35549 / #35550 each opens the shared field list (the fields the view shows first, a search box, a type icon per row): Filter → a field → its values applies at once, with no Apply, and each condition shows as a chip in the condition row under the view bar; Sort → the direction on top → a field adds a level, the sort chip before the filter chips counting it as 「+N」. The full builders are one click further, behind the field list's footer: 「Advanced filter」 opens the FilterBuilder (no 「Where」 label any more) and 「All sort levels」 the SortBuilder. Add 2 conditions that leave at least TWO rows, so the sort clause has an order to read — on the stock seed priority = high AND estimate_hours > 4 leaves ONE row on in_progress, a single-datapoint for acceptance[1] (QA run #24616): check the count first and pick a pair that keeps ≥ 2; open the SortBuilder and add a sort (due_date desc); type a term into the list's quick search that keeps rows (acceptance[2] reads it back; QA run #29890 used 'pipeline'); capture the data request", "assert the request's `filter` param is the MERGE of the view's stored rule AND the two toolbar conditions (buildEffectiveFilter/mergeFilterNodes), and `sort` carries the toolbar sort (e.g. sort=-due_date) — the console spells its list params without a `$`; the returned rows satisfy view-filter AND toolbar conditions", "navigate away via an in-app nav link to another object (the link carries no query string, so the URL state is dropped), then navigate back to showcase_task in_progress through the Tasks nav entry and the view switcher (it lands on /view/showcase_task.in_progress). ⛔ Not the sidebar's 'In-Progress Tasks' Data Slices link: it opens /showcase_task/data?filter[status]=in_progress, a different surface from the saved view; screenshot; confirm the list opens as the view declares it: no toolbar filter chip, the view's own sort, an empty search, and no 「Discard」/「Save」 at the condition row's end (objectstack#35955: opening another object drops the draft). Then build the two conditions, the sort and the search again, open a record from the list and come back with the browser's Back: confirm the conditions, the sort and the search are all still there, with 「Discard」 and 「Save」 at the condition row's end", - "read where the toolbar filter and sort are kept: nowhere durable. Since objectstack#35955 they are the list's DRAFT, held in this tab's memory (ui/packages/app-shell/src/views/listDraftStore.ts): the signed-in user's sys_user_preference row keyed ui.list.showcase_task (GET /api/v1/data/sys_user_preference filtered to that key) gains no filters, sort or search from the change — it holds only what is remembered for the reader (perView..columnState.widths, rowHeight, viewOrder) — and localStorage gains no list-filters::showcase_task: key. Reload the page: the list opens as the view declares it", - "sign out through the account menu (the avatar menu's Log out, user.logout in ui/packages/app-shell/src/layout/AppHeader.tsx; never by clearing storage). That Log out itself removes the signed-out user's list-state:* and list-filters:* keys from localStorage (purgeSignedOutUserClientState, ui/packages/auth/src/ActiveOrganizationStorage.ts, run by AuthProvider's sign-out), so the first account's keys are gone by the time the second signs in; the clause holds by that wipe AND by the user-keyed row. Sign in as the SECOND account; open the same object+view; confirm the first account's cached toolbar filter does NOT appear", + "read where the toolbar filter and sort are kept: nowhere durable. Since objectstack#35955 they are the list's DRAFT, held in this tab's memory (ui/packages/app-shell/src/views/listDraftStore.ts): no sys_user_preference row is written — no Console writes a ui.list. row any more (GET /api/v1/data/sys_user_preference shows no ui.list.showcase_task row changed) — and localStorage gains no filter, sort or search: the one list key it holds for the reader is list-layout::showcase_task, which carries only the column widths, the row height and the tab order (ui/packages/app-shell/src/views/listLayoutStore.ts). Reload the page: the list opens as the view declares it", + "sign out through the account menu (the avatar menu's Log out, user.logout in ui/packages/app-shell/src/layout/AppHeader.tsx; never by clearing storage). That Log out itself removes the signed-out user's list-layout:* keys (and any list-state:* or list-filters:* key an earlier Console left) from localStorage (purgeSignedOutUserClientState, ui/packages/auth/src/ActiveOrganizationStorage.ts, run by AuthProvider's sign-out), so the first account's keys are gone by the time the second signs in; the clause holds by that wipe AND because no filter is stored anywhere. Sign in as the SECOND account; open the same object+view; confirm the first account's cached toolbar filter does NOT appear", "userFilters/URL: where UserFilters are hosted (an interface page or the userFilters surface — NOT a bare object list, ADR-0053), apply a quick-filter; copy the URL; open it in a fresh tab; confirm the uf_ params (comma-joined, URI-encoded) reproduce the same rows and uf__tab carries the active preset (ADR-0047)", "negative sweep: confirm tabs-element userFilters (preset chips, uf__tab) do NOT leak onto the bare object list view — dropdown chips the object view itself declares are allowed there (ADR-0047 amendment) and their uf_ params are not a leak" ], @@ -2981,7 +2981,7 @@ { "clause": "the list state is never shared across accounts — the draft is never written to the user's sys_user_preference row or to browser storage, so a second account on the same browser never reads the first account's filters (a filter value can be sensitive)", "oracle": "dom", - "verify": "with account A's toolbar filter on screen, read A's ui.list.showcase_task preference row (no filters or sort in it) and localStorage (no list-filters:* key for the view), then sign A out through the account menu's Log out and sign in as account B on the same browser and confirm B's view opens with no A-authored toolbar filter", + "verify": "with account A's toolbar filter on screen, read A's sys_user_preference rows (no ui.list.* row written) and localStorage (no filter, sort or search in any key; list-layout::showcase_task holds the widths, row height and tab order only), then sign A out through the account menu's Log out and sign in as account B on the same browser and confirm B's view opens with no A-authored toolbar filter", "evidence": "A's preference row + localStorage keys + B's clean toolbar" }, { @@ -3008,7 +3008,7 @@ }, "source": [ "objectui: packages/plugin-list/src/ListView.tsx (buildEffectiveFilter, convertFilterGroupToAST, mergeFilterNodes; $filter + $orderby assembly)", - "objectui: packages/app-shell/src/views/listDraftStore.ts (objectstack#35955 — the list's draft: filters, sort, grouping, search and columns, held in the tab's memory for one reader, object and view); packages/app-shell/src/context/ListPreferencesProvider.tsx (the per-user ui.list. sys_user_preference row, which since objectstack#35955 a list change writes only column widths, row height and the view order to)", + "objectui: packages/app-shell/src/views/listDraftStore.ts (objectstack#35955 — the list's draft: filters, sort, grouping, search and columns, held in the tab's memory for one reader, object and view); packages/app-shell/src/views/listLayoutStore.ts (objectstack#35955 — the reader's column widths, row height and tab order, kept in this browser only under list-layout::; the ui.list. sys_user_preference row is retired)", "objectui: packages/app-shell/src/views/userFilterUrlState.ts (uf_* params, ADR-0047)", "ADR-0053 (userFilters belong to interface pages, suppressed on object list views); examples/app-showcase/src/ui/views/task.view.ts", "cross-ref: records-forms.list-view-capabilities (saved-view-filter / userFilters negative)" @@ -3091,6 +3091,12 @@ "date": "2026-11-21", "change": "steps[3], steps[4], acceptance[2] (clause, verify, evidence), acceptance[3] (clause, verify, evidence) and source[1] re-pointed to the list draft (objectstack#35955): a toolbar filter, sort and search are a draft held in the tab's memory, kept on opening a record and coming back and dropped on opening another object or view or on a reload; they are no longer stored in the user's ui.list. row. The in-app-navigation restore of revision 3 is replaced by the record round trip, and the user-scope clause now reads that nothing is stored at all. Not loosened: a second account must still see none of the first account's filters", "ref": "#35955" + }, + { + "revision": 14, + "date": "2026-11-21", + "change": "steps[4], steps[5], acceptance[3] (verify) and source[1] re-pointed (objectstack#35955 PR3): the ui.list. sys_user_preference row is retired, so no Console writes it; the one list key the reader keeps is list-layout:: in this browser, with the widths, row height and tab order only, and sign-out removes it with any list-state:* / list-filters:* key an earlier Console left. Not loosened: nothing of a toolbar filter, sort or search is stored anywhere, and a second account still sees none of the first account's", + "ref": "#35955" } ] }, @@ -3589,7 +3595,7 @@ "title": "Grid personalization persists across reload: column resize/reorder/pin, row-height, group-by (with API-true totals), row-color", "since": "v16", "status": "active", - "revision": 9, + "revision": 10, "priority": "P2", "surface": "browser", "personas": [ @@ -3615,7 +3621,7 @@ "steps": [ "open showcase_task grid; screenshot", "resize a column (reorder two columns only on a grid that sets reorderableColumns; there is no runtime pin control — acceptance[0]), and set a row height on the Row height level of the list's options menu (the toolbar's options trigger, then 行高 / Row height: three choices, 紧凑 / 标准 / 宽松 — Compact / Standard / Spacious, ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx; a gallery's Row height level picks its card size the same way) — three modes, stored as rowHeight compact / medium / tall (the spec's five row heights compact/short/medium/tall/extra_tall narrow onto these three: objectui core normalize-list-view.ts DENSITY_MODE_TO_ROW_HEIGHT / ROW_HEIGHT_TO_DENSITY_MODE)", - "reload; confirm the column widths and row-height restored — they persist in the signed-in user's own list preference, sys_user_preference ui.list.showcase_task (perView..columnState.widths / rowHeight, objectui#12418). A column ORDER is not: since objectstack#35955 it is the list's unsaved draft, so a reload reopens on the view's own order unless it was saved into a view, with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also reload in a FRESH browser context as the same user: the layout follows the user", + "reload; confirm the column widths and row-height restored — they are kept in this browser for the signed-in user, localStorage list-layout::showcase_task (perView..widths / rowHeight, objectstack#35955; before it the user's sys_user_preference ui.list.showcase_task row, objectui#12418). A column ORDER is not: since objectstack#35955 it is the list's unsaved draft, so a reload reopens on the view's own order unless it was saved into a view, with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also open the list in a FRESH browser context as the same user: the layout does NOT follow the user there — it opens on the view's own widths and row height, by design (objectstack#35955)", "group-by status ('Add group field' pre-selects the first field, Title, and groups at once, so switch it to Status). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", "cross-check each group's count against a direct per-group server count (GET /api/v1/data/showcase_task filtered to that status, read its total)", "read the row-color rule the stock Grid view declares — rowColor on priority with the colors map low slate / medium blue / high amber / urgent red (examples/app-showcase/src/ui/views/task.view.ts); there is no runtime row-color authoring control — and confirm rows paint by it (useRowColor, the -100 tint of each name)", @@ -3631,7 +3637,7 @@ { "clause": "the toolbar row height persists across reload (Compact / Standard / Spacious — the runtime control offers three modes over the spec's five rowHeight values)", "oracle": "dom", - "verify": "the reloaded grid renders at the chosen density (ObjectGrid rowHeightMode), and the preference row's rowHeight reads compact / medium / tall for the three modes", + "verify": "the reloaded grid renders at the chosen density (ObjectGrid rowHeightMode), and the list-layout entry's rowHeight reads compact / medium / tall for the three modes", "evidence": "before/after screenshots" }, { @@ -3647,10 +3653,10 @@ "evidence": "post-reload screenshot" }, { - "clause": "the column state follows the USER, not the browser: since objectui#12418 widths and row height persist in the user's own sys_user_preference row (ui.list., perView..columnState / rowHeight), so they restore for that user in a fresh browser and never for another account; the component's localStorage key grid-columns-[-] carries no user id and is only a cache under that row", + "clause": "the column state is the reader's in THIS browser: since objectstack#35955 widths and row height are kept in localStorage list-layout:: (perView..widths / rowHeight), keyed by the signed-in user's id, so they restore for that user in this browser, never for another account here, and do not follow the user to a fresh browser; no sys_user_preference row is written. The component's own localStorage key grid-columns-[-] carries no user id and is only its cache: the page hands the grid the reader's layout, or none", "oracle": "dom", - "verify": "the sys_user_preference ui.list.showcase_task row carries the widths / row height under the signed-in user's user_id, and the same user in a fresh browser context sees them restored; a second account on the same browser does not (objectui app-shell/src/context/ListPreferencesProvider.tsx). The localStorage grid-columns-[-] key carries no user id and is only the cache", - "evidence": "the preference row + the fresh-context restore + the second account's default layout" + "verify": "localStorage list-layout::showcase_task carries the widths / row height under the signed-in user's id, and GET /api/v1/data/sys_user_preference shows no ui.list.showcase_task row written; the same user in a fresh browser context opens on the view's own widths and row height; a second account on the same browser does not see the first account's (ui/packages/app-shell/src/views/listLayoutStore.ts)", + "evidence": "the list-layout entry + no preference row + the fresh-context default + the second account's default layout" } ], "negative": [ @@ -3664,7 +3670,7 @@ "source": [ "objectui: packages/plugin-grid/src/ObjectGrid.tsx (columnState + saveColumnState localStorage grid-columns-*, rowHeightMode, schema.grouping, useRowColor, useColumnSummary)", "objectui: packages/components/src/renderers/complex/data-table.tsx (the underlying table)", - "objectui: packages/app-shell/src/views/listFilterStorage.ts (documents grid-columns-* is NOT user-scoped by design)", + "objectui: packages/app-shell/src/views/listLayoutStore.ts (list-layout::, the reader's widths, row height and tab order in this browser, objectstack#35955); packages/plugin-grid/src/objectGridColumnState.ts (grid-columns-* is NOT user-scoped by design: the component's cache)", "examples/app-showcase/src/ui/views/task.view.ts", "packages/spec/src/ui/component.zod.ts#ObjectGridPropsSchema (reorderableColumns is a grid component prop, not a ListView key) + packages/spec/src/ui/view.zod.ts#ListColumnSchema (pinned is declared per column by the author) + objectui packages/plugin-grid/src/ObjectGrid.tsx (reorderableColumns defaults false; the persisted columnState holds widths and order)" ], @@ -3722,6 +3728,12 @@ "date": "2026-11-21", "change": "steps[2], steps[6] and acceptance[0] (clause, verify) re-pointed to the list draft (objectstack#35955): a column order is the list's unsaved draft, kept only by Save into a view, so it no longer comes back after a reload; the widths and the row height still persist in the user's ui.list. row. Not loosened: widths and row height must still survive a reload and follow the user to a fresh browser", "ref": "#35955" + }, + { + "revision": 10, + "date": "2026-11-21", + "change": "steps[2], acceptance[1] (verify), acceptance[4] (clause, verify, evidence) and source[2] re-pointed (objectstack#35955 PR3, Sales ruling D1 on #35955): column widths and row height are kept in this browser only, localStorage list-layout::, and the ui.list. row is retired. Changed on purpose: they no longer follow the user to a fresh browser. Not loosened: they still survive a reload in the same browser and never reach another account", + "ref": "#35955" } ] }, diff --git a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts index a62e003efe4..22fcd357c30 100644 --- a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts +++ b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts @@ -14,6 +14,9 @@ import MigrateListPreferences from './list-preferences.js'; // reach through dynamic `import()`s at MODULE LOAD, not inside a case. import '@objectstack/runtime'; import '@objectstack/objectql'; +import '@objectstack/plugin-auth'; +import '@objectstack/plugin-security'; +import '@objectstack/plugin-audit'; /** * `os migrate list-preferences` against a real SQLite database: the step that @@ -23,7 +26,8 @@ import '@objectstack/objectql'; * ## The database * * The schema this version creates (`os migrate apply --yes` over an empty - * file), with the rows an earlier Console left: three `ui.list.*` rows for two + * file, the composition `os serve` mounts with an auth secret, so the auth + * family's `sys_user_preference` is among it), with the rows an earlier Console left: three `ui.list.*` rows for two * users, and two CONTROLS that are never touched — another family's row * (`ui.record.account`) and a key that only looks alike (`ui.lists`). * @@ -40,6 +44,7 @@ import '@objectstack/objectql'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); const CASE_TIMEOUT_MS = 240_000; +const SECRET = 'os35955-integration-secret-at-least-32-chars'; const RETIRED = [ { id: 'pref_l1', user_id: 'u1', key: 'ui.list.account', value: '{"viewOrder":["account.all"]}' }, @@ -145,12 +150,16 @@ beforeAll(async () => { [ 'export default {', " manifest: { id: 'com.example.os35955listprefs', name: 'list prefs', version: '0.0.0', type: 'app' },", + " requires: ['auth'],", " objects: [{ name: 'os35955_thing', fields: { title: { type: 'text' } } }],", '};', '', ].join('\n'), ); process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + // `os serve` composes the auth family, whose objects hold the preference + // rows, only when an auth secret resolves. + process.env.OS_AUTH_SECRET = SECRET; process.env.NODE_ENV = 'production'; process.env.OS_TELEMETRY_DB = '0'; dbFile = join(dir, 'upgraded.db'); diff --git a/packages/cli/src/commands/migrate/list-preferences.ts b/packages/cli/src/commands/migrate/list-preferences.ts index 10e7a0ddcf2..92876fc5745 100644 --- a/packages/cli/src/commands/migrate/list-preferences.ts +++ b/packages/cli/src/commands/migrate/list-preferences.ts @@ -19,6 +19,7 @@ import { errorCodeFields, } from '../../utils/format.js'; import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; import { absentTableReads } from '../../utils/absent-table-reads.js'; @@ -187,7 +188,7 @@ export default class MigrateListPreferences extends Command { if (!json) printHeader('Migrate · list-preferences'); - const refuse = async (error: string, message: string, extra: Record = {}): Promise => { + const refuse = async (error: string, message: string, extra: object = {}): Promise => { if (json) await emitJson({ error, message, ...extra }, 0, { compact: true }); else printError(message); this.exit(1); @@ -256,11 +257,16 @@ export default class MigrateListPreferences extends Command { let stack; try { - // The dry run boots READ-ONLY, the boot `os migrate plan` takes: no - // schema DDL, no artifact seed, no sqlite file brought into existence. + // `sys_user_preference` is plugin-auth's: its identity objects are + // composed for their declarations only (no auth manager, nothing + // started), as `os user set-password` composes them. The dry run boots + // READ-ONLY, the boot `os migrate plan` takes: no schema DDL, no + // artifact seed, no sqlite file brought into existence. + const { createIdentityObjectsPlugin } = await import('@objectstack/plugin-auth'); stack = await bootSchemaStack({ jsonOutput: json, databaseUrl: flags['database-url'], + extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], ...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), }); } catch (error: any) { diff --git a/packages/cli/test/json-stdout-purity.e2e.test.ts b/packages/cli/test/json-stdout-purity.e2e.test.ts index eafcbb40a03..6646bf645a9 100644 --- a/packages/cli/test/json-stdout-purity.e2e.test.ts +++ b/packages/cli/test/json-stdout-purity.e2e.test.ts @@ -140,6 +140,10 @@ const FAMILY: Record = { // it boots read-only (plugin-audit's objects registered), reads // `sys_comment` below the data door and writes nothing. 'migrate comment-reactions': [], + // [#35955] A dry run is its DEFAULT and the only form driven here: it boots + // read-only (plugin-auth's identity objects registered for their + // declarations) and reads `sys_user_preference`; it writes nothing. + 'migrate list-preferences': [], 'migrate files-to-references': [], 'migrate meta': ['--stored'], 'migrate multi-value-columns': [], diff --git a/packages/cli/test/migrate-confirmation-exit.pin.test.ts b/packages/cli/test/migrate-confirmation-exit.pin.test.ts index 88d0d1e36a1..258a44e096e 100644 --- a/packages/cli/test/migrate-confirmation-exit.pin.test.ts +++ b/packages/cli/test/migrate-confirmation-exit.pin.test.ts @@ -261,6 +261,8 @@ const ROSTER: Record = { 'text-scalars': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'comment-parent-pair': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'comment-reactions': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, + // The export path is mandatory with `--apply` and must not exist yet; the gate sits after both checks. + 'list-preferences': { argv: ['--apply', '--export', join(SCRATCH, 'list-preferences-export.json')], confirm: '--yes', writes: BOOT }, 'files-to-references': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, // `--yes` belongs to the stored-row pass; without `--stored` the command converts source files. meta: { argv: ['--stored', '--apply'], confirm: '--yes', writes: BOOT }, diff --git a/packages/platform-objects/src/pages/sys-user.page.ts b/packages/platform-objects/src/pages/sys-user.page.ts index 6672ef51589..83c52e15dc9 100644 --- a/packages/platform-objects/src/pages/sys-user.page.ts +++ b/packages/platform-objects/src/pages/sys-user.page.ts @@ -718,7 +718,7 @@ export const SysUserDetailPage: Page = { }, // ── Preferences ─────────────────────────────────────────── // [#23803] This user's `sys_user_preference` rows — the console's - // per-user UI state (`ui.recent`, `ui.favorites`, `ui.list.` + // per-user UI state (`ui.recent`, `ui.favorites`, `ui.record.` // …). Setup's "User Preferences" menu entry, which listed every // user's rows, left the menu; this tab is where an administrator // reaches them now, from the user they belong to. diff --git a/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx b/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx index fddd86d6bfb..9d7edea9887 100644 --- a/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx @@ -29,11 +29,18 @@ * objectstack#35881 adds a fourth key, the person's last app (`ui.app.last`): * the budget stays ONE read, now asking for four keys and both prefixes. * + * objectstack#35955 retires the list-state family: a list's widths, row height + * and tab order are kept in this browser only (`list-layout::`), + * and no Console reads or writes `ui.list.` any more. The read asks + * for the four keys and the record-state prefix alone; a `ui.list.*` row an + * earlier Console stored stays where it is, unread and never written + * (`os migrate list-preferences` removes it). + * * ## The tree * * The real `ConsoleShell` providers and the real `ConnectedShell`: its * `AdapterProvider` builds the real `ObjectStackAdapter` and client, and its - * `UserStateBridge` builds the three adapters and the list-state family. The + * `UserStateBridge` builds the adapters and the record-state family. The * network is the fake framework of `preferenceFramework.ts` on the global * `fetch`, which answers preference reads the way the server does, by * `user_id` and by `key` (`=`, `in`, `startswith`), and refuses any other @@ -42,11 +49,10 @@ * ## The pins * * 1. One boot puts ONE `sys_user_preference` GET on the wire, and it asks - * for the three keys, the list-state prefix and the record-state prefix. - * 2. Every consumer receives its own row from that one answer, the list - * state of an object included. - * 3. Each adapter still writes its own row, and only its own; the list state - * writes its object's row. + * for the four keys and the record-state prefix, never `ui.list.`. + * 2. Every consumer receives its own row from that one answer. + * 3. Each adapter still writes its own row, and only its own; a list layout + * change writes no row at all. * 4. Signing in as another user reads again, for that user, and every * consumer ends on that user's rows. * 5. Two loads of one key at once are still one request. @@ -95,7 +101,7 @@ import { useFavorites } from '../../context/FavoritesProvider'; import { useRecentItems } from '../../context/RecentItemsProvider'; import { useFlowPaletteRecents } from '../../context/FlowPaletteRecentsProvider'; import { useLastApp } from '../../context/LastAppProvider'; -import { useObjectListPreferences, type ObjectListPreference } from '../../context/ListPreferencesProvider'; +import { useObjectListLayout } from '../../views/listLayoutStore'; import { useRecordPagePreferences } from '@object-ui/react'; import { createPreferenceFramework, preferenceRowId as rowId, type PreferenceFramework } from './preferenceFramework'; @@ -105,13 +111,12 @@ const FLOW_KEY = 'ui.flow.palette.recents'; /** objectstack#35881 — the person's last app, a fourth key in the same read. */ const LAST_APP_KEY = 'ui.app.last'; const BRIDGE_KEYS = [FAVORITES_KEY, RECENT_KEY, FLOW_KEY, LAST_APP_KEY]; -/** objectui#12418 — the list-state family, and one object's row of it. */ +/** objectstack#35955 — a row of the retired list-state family an earlier Console stored. */ const LIST_PREFIX = 'ui.list.'; const LIST_KEY = 'ui.list.account'; /** objectstack#25883 — the record-state family, and one object's row of it. */ const RECORD_PREFIX = 'ui.record.'; const RECORD_KEY = 'ui.record.account'; -const BOTH_PREFIXES = [LIST_PREFIX, RECORD_PREFIX].sort(); /** Each user's stored rows, one distinct payload per key, so a starved consumer shows up. */ const STORE: Record> = { @@ -145,7 +150,7 @@ interface Seen { flow: string[]; /** The person's last app (objectstack#35881). */ lastApp: string | null; - /** The `account` list state's tab order (objectui#12418). */ + /** The `account` list's tab order, kept in this browser (objectstack#35955). */ listOrder: string[]; /** The `account` record page's "show empty fields" choice (objectstack#25883). */ recordShowEmpty: boolean | undefined; @@ -164,7 +169,7 @@ const actions: { addRecentItem?: ReturnType['addRecentItem']; recordRecent?: ReturnType['recordRecent']; rememberApp?: ReturnType['rememberApp']; - patchListView?: ReturnType['patchView']; + patchListView?: ReturnType['patchView']; updateRecordPage?: NonNullable>['update']; }; } = { current: {} }; @@ -174,9 +179,8 @@ function Consumers() { const { recentItems, addRecentItem } = useRecentItems(); const { recents, recordRecent } = useFlowPaletteRecents(); const { lastApp, rememberApp } = useLastApp(); - const list = useObjectListPreferences('account'); - const listPreference: ObjectListPreference = list.preference; - const listOrderKey = JSON.stringify(listPreference.viewOrder ?? []); + const list = useObjectListLayout('account'); + const listOrderKey = JSON.stringify(list.layout.viewOrder ?? []); const patchListView = list.patchView; const recordPage = useRecordPagePreferences(); const recordShowEmpty = recordPage?.get('account').showEmptyFields; @@ -218,11 +222,12 @@ async function settle(ms = 150) { const U1_SEEN: Seen = { favorites: ['object:contact'], recent: ['object:lead'], flow: ['flow_step_alpha'], lastApp: 'sales', - listOrder: ['account.mine', 'account.all'], recordShowEmpty: true, + // The stored `ui.list.account` row is never read: the list has no order of the reader's. + listOrder: [], recordShowEmpty: true, }; const U2_SEEN: Seen = { favorites: ['object:invoice'], recent: ['object:quote'], flow: ['flow_step_omega'], lastApp: 'service', - listOrder: ['account.all', 'account.closed'], recordShowEmpty: false, + listOrder: [], recordShowEmpty: false, }; describe('console sys_user_preference request budget (objectui#12187)', () => { @@ -239,7 +244,7 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { vi.unstubAllGlobals(); }); - it('one boot puts one sys_user_preference read on the wire, asking for the four keys and both family prefixes', async () => { + it('one boot puts one sys_user_preference read on the wire, asking for the four keys and the record-state prefix', async () => { boot(); await waitFor(() => expect(wire().gets.length).toBeGreaterThan(0)); await settle(); @@ -247,9 +252,10 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { expect(wire().gets).toHaveLength(1); expect(wire().gets[0].user).toBe('u1'); expect([...wire().gets[0].keys].sort()).toEqual([...BRIDGE_KEYS].sort()); - // objectui#12418 / objectstack#25883 — every object's list state and - // record-page state ride the same read. - expect([...wire().gets[0].prefixes].sort()).toEqual(BOTH_PREFIXES); + // objectstack#25883 — every object's record-page state rides the same + // read; objectstack#35955 — the list-state family no longer does. + expect([...wire().gets[0].prefixes]).toEqual([RECORD_PREFIX]); + expect([...wire().gets[0].prefixes]).not.toContain(LIST_PREFIX); }); it('every consumer receives its own row from that one answer', async () => { @@ -260,7 +266,7 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { expect(wire().gets).toHaveLength(1); }); - it('each adapter still writes its own row, and only its own', async () => { + it('each adapter still writes its own row, and only its own; a list layout change writes none', async () => { boot(); await waitFor(() => expect(latest.current).toEqual(U1_SEEN)); await settle(); @@ -271,31 +277,31 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { actions.current.addRecentItem?.({ id: 'object:deal', type: 'object', name: 'deal', href: '/deal' }); actions.current.recordRecent?.('flow_step_beta'); actions.current.rememberApp?.('service'); - actions.current.patchListView?.('account.all', { sort: [{ field: 'name', order: 'desc' }] }); + actions.current.patchListView?.('account.all', { widths: { name: 240 } }); actions.current.updateRecordPage?.('account', { showEmptyFields: false }); }); // Each provider debounces its write (500 ms; the record page writes on the - // click); all six land, once each. - await waitFor(() => expect(wire().writes).toHaveLength(6), { timeout: 3000 }); - await settle(); - expect(wire().writes).toHaveLength(6); + // click); all five land, once each. The list layout is this browser's. + await waitFor(() => expect(wire().writes).toHaveLength(5), { timeout: 3000 }); + await settle(700); + expect(wire().writes).toHaveLength(5); + expect(JSON.parse(localStorage.getItem('list-layout:u1:account')!)).toEqual({ + perView: { 'account.all': { widths: { name: 240 } } }, + }); const byId = new Map(wire().writes.map((w) => [w.id, w])); // An update of the row its own load found — no insert, no other row. expect(wire().writes.every((w) => w.method === 'PATCH' || w.method === 'PUT')).toBe(true); - expect([...byId.keys()].sort()).toEqual([...BRIDGE_KEYS, LIST_KEY, RECORD_KEY].map((k) => rowId('u1', k)).sort()); + expect([...byId.keys()].sort()).toEqual([...BRIDGE_KEYS, RECORD_KEY].map((k) => rowId('u1', k)).sort()); expect((byId.get(rowId('u1', FAVORITES_KEY))?.value as { id: string }[]).map((f) => f.id)).toContain( 'object:account', ); expect((byId.get(rowId('u1', RECENT_KEY))?.value as { id: string }[])[0].id).toBe('object:deal'); expect(byId.get(rowId('u1', FLOW_KEY))?.value).toEqual(['flow_step_beta', 'flow_step_alpha']); expect(byId.get(rowId('u1', LAST_APP_KEY))?.value).toEqual(['service']); - // The object's row carries what it held and the new sort. - expect(byId.get(rowId('u1', LIST_KEY))?.value).toEqual({ - viewOrder: ['account.mine', 'account.all'], - perView: { 'account.all': { sort: [{ field: 'name', order: 'desc' }] } }, - }); + // The retired row is never written. + expect(byId.has(rowId('u1', LIST_KEY))).toBe(false); expect(byId.get(rowId('u1', RECORD_KEY))?.value).toEqual({ showEmptyFields: false }); // A write found its row from the load: it asked the server nothing more. expect(wire().gets).toHaveLength(1); @@ -315,10 +321,10 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { const afterSwitch = wire().gets.slice(before); const forU2 = afterSwitch.filter((g) => g.user === 'u2'); - // One read for the new user, asking for all four keys and both prefixes. + // One read for the new user, asking for all four keys and the record-state prefix. expect(forU2).toHaveLength(1); expect([...forU2[0].keys].sort()).toEqual([...BRIDGE_KEYS].sort()); - expect([...forU2[0].prefixes].sort()).toEqual(BOTH_PREFIXES); + expect([...forU2[0].prefixes]).toEqual([RECORD_PREFIX]); // No u2 read was answered with u1's rows: every consumer shows u2's. expect(latest.current).toEqual(U2_SEEN); }); diff --git a/ui/packages/app-shell/src/context/__tests__/ListPreferencesProvider.slot-12418.test.ts b/ui/packages/app-shell/src/context/__tests__/ListPreferencesProvider.slot-12418.test.ts deleted file mode 100644 index 23765b77cd7..00000000000 --- a/ui/packages/app-shell/src/context/__tests__/ListPreferencesProvider.slot-12418.test.ts +++ /dev/null @@ -1,186 +0,0 @@ -/** - * objectui#12418 — the `ui.list.` slot's shape, kept by the pure - * helpers every write goes through. - * - * - A stored value keeps only what the slot declares, well formed: a - * malformed piece is dropped, never coerced into another meaning. - * - A view's entry: an empty sort is the user's choice and is KEPT (the list - * then asks for no order), distinct from a `null` sort, which clears it; a - * filter group with no condition and an empty column layout CLEAR their - * part; a view left with nothing is removed. - * - "Reset view" removes one view's entry and leaves the tab order. - * - The older per-browser keys are folded into the first read of an object - * with no cached entry, and only then. - */ -import { describe, it, expect, beforeEach } from 'vitest'; -import { - localListStateKey, - patchViewPreference, - readLocalListState, - resetViewPreference, - sanitizeObjectListPreference, - setViewOrderPreference, - writeLocalListState, -} from '../ListPreferencesProvider'; - -const GROUP = { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'x' }] }; - -describe('the slot keeps only what it declares (objectui#12418)', () => { - it('drops malformed pieces and the builder row ids of a sort', () => { - expect(sanitizeObjectListPreference({ - viewOrder: ['a', 2, 'b'], - perView: { - v1: { - sort: [{ id: 'r1', field: 'name', order: 'desc' }, { order: 'asc' }, 'x'], - filters: GROUP, - columnState: { order: ['name'], widths: { name: 200, bad: 'wide' } }, - unknown: true, - }, - v2: { filters: { conditions: [] } }, - v3: 'not an object', - }, - extra: 1, - })).toEqual({ - perView: { - v1: { - sort: [{ field: 'name', order: 'desc' }], - filters: GROUP, - columnState: { order: ['name'], widths: { name: 200 } }, - }, - }, - }); - expect(sanitizeObjectListPreference(['not', 'an', 'object'])).toEqual({}); - expect(sanitizeObjectListPreference({ viewOrder: ['a', 'b'] })).toEqual({ viewOrder: ['a', 'b'] }); - }); -}); - -describe('a view entry\'s patch (objectui#12418)', () => { - it('keeps an empty sort — the user cleared the order, which is not the view\'s order', () => { - expect(patchViewPreference({}, 'v1', { sort: [] })).toEqual({ perView: { v1: { sort: [] } } }); - }); - - it('`sort: []` stores "no sort"; `sort: null` (or undefined) clears the stored sort — two different facts', () => { - const sorted = patchViewPreference({}, 'v1', { sort: [{ field: 'name', order: 'asc' }], filters: GROUP }); - const noSort = patchViewPreference(sorted, 'v1', { sort: [] }); - const cleared = patchViewPreference(sorted, 'v1', { sort: null }); - expect(noSort).toEqual({ perView: { v1: { sort: [], filters: GROUP } } }); - expect(cleared).toEqual({ perView: { v1: { filters: GROUP } } }); - expect(patchViewPreference(sorted, 'v1', { sort: undefined })).toEqual(cleared); - expect(noSort).not.toEqual(cleared); - }); - - it('clears the filters on a group with no condition, and drops a view left empty', () => { - const state = patchViewPreference({}, 'v1', { filters: GROUP }); - expect(state).toEqual({ perView: { v1: { filters: GROUP } } }); - expect(patchViewPreference(state, 'v1', { filters: { id: 'root', logic: 'and', conditions: [] } })).toEqual({}); - }); - - it('clears the column layout on an empty one, and leaves the other parts', () => { - const state = patchViewPreference({}, 'v1', { sort: [{ field: 'name', order: 'asc' }], columnState: { widths: { name: 1 } } }); - expect(patchViewPreference(state, 'v1', { columnState: {} })).toEqual({ - perView: { v1: { sort: [{ field: 'name', order: 'asc' }] } }, - }); - }); - - it('"Reset view" removes one view\'s entry and leaves the tab order and the other views', () => { - let state = setViewOrderPreference({}, ['v2', 'v1']); - state = patchViewPreference(state, 'v1', { sort: [{ field: 'name', order: 'asc' }] }); - state = patchViewPreference(state, 'v2', { filters: GROUP }); - expect(resetViewPreference(state, 'v1')).toEqual({ viewOrder: ['v2', 'v1'], perView: { v2: { filters: GROUP } } }); - // Nothing stored for the view: the same state back. - expect(resetViewPreference(state, 'v9')).toBe(state); - }); -}); - -describe('this browser\'s cache and the older keys (objectui#12418)', () => { - beforeEach(() => localStorage.clear()); - - it('the first read of an object with no cached entry folds `viewOrder:` and each view\'s Filter panel group', () => { - localStorage.setItem('viewOrder:deal', JSON.stringify(['deal.b', 'deal.a'])); - localStorage.setItem('list-filters:u1:deal:deal.a', JSON.stringify({ filters: GROUP, search: 'x' })); - localStorage.setItem('list-filters:u1:deal:deal.b', JSON.stringify({ search: 'only a term' })); - // Another user's and another object's keys are not this object's. - localStorage.setItem('list-filters:u2:deal:deal.a', JSON.stringify({ filters: GROUP })); - localStorage.setItem('list-filters:u1:lead:lead.a', JSON.stringify({ filters: GROUP })); - - expect(readLocalListState('u1', 'deal')).toEqual({ - viewOrder: ['deal.b', 'deal.a'], - perView: { 'deal.a': { filters: GROUP } }, - }); - }); - - it('once the object has a cached entry, the older keys are not read', () => { - localStorage.setItem('viewOrder:deal', JSON.stringify(['deal.b', 'deal.a'])); - writeLocalListState('u1', 'deal', {}); - expect(readLocalListState('u1', 'deal')).toEqual({}); - expect(localStorage.getItem(localListStateKey('u1', 'deal'))).toBe('{}'); - }); -}); - -describe('the density and the hidden fields are two more parts of a view\'s entry (objectui#12474)', () => { - it('keeps a spec row height and drops any other value, never coercing it', () => { - expect(sanitizeObjectListPreference({ - perView: { - v1: { rowHeight: 'medium' }, - v2: { rowHeight: 'comfortable' }, - v3: { rowHeight: 7 }, - }, - })).toEqual({ perView: { v1: { rowHeight: 'medium' } } }); - }); - - it('keeps the hidden fields as names, once each, and keeps an empty list as the user\'s choice', () => { - expect(sanitizeObjectListPreference({ - perView: { - v1: { hiddenFields: ['amount', 3, '', 'amount', 'stage'] }, - v2: { hiddenFields: [] }, - v3: { hiddenFields: 'amount' }, - }, - })).toEqual({ perView: { v1: { hiddenFields: ['amount', 'stage'] }, v2: { hiddenFields: [] } } }); - }); - - it('a patch sets each part beside the others, and `null` clears only its own part', () => { - let state = patchViewPreference({}, 'v1', { sort: [{ field: 'name', order: 'asc' }] }); - state = patchViewPreference(state, 'v1', { rowHeight: 'compact' }); - state = patchViewPreference(state, 'v1', { hiddenFields: ['amount'] }); - expect(state).toEqual({ - perView: { v1: { sort: [{ field: 'name', order: 'asc' }], rowHeight: 'compact', hiddenFields: ['amount'] } }, - }); - state = patchViewPreference(state, 'v1', { rowHeight: null }); - expect(state).toEqual({ perView: { v1: { sort: [{ field: 'name', order: 'asc' }], hiddenFields: ['amount'] } } }); - state = patchViewPreference(state, 'v1', { hiddenFields: null, sort: null }); - expect(state).toEqual({}); - }); - - it('"Reset view" drops the density and the hidden fields with the rest of the view\'s entry', () => { - const state = { - viewOrder: ['v2', 'v1'], - perView: { v1: { rowHeight: 'tall' as const, hiddenFields: [] }, v2: { rowHeight: 'short' as const } }, - }; - expect(resetViewPreference(state, 'v1')).toEqual({ viewOrder: ['v2', 'v1'], perView: { v2: { rowHeight: 'short' } } }); - }); -}); - -describe('the added fields are one more part of a view\'s entry (objectstack#30077)', () => { - it('keeps the added fields as names, once each, and drops an empty list: nothing added is the view\'s own', () => { - expect(sanitizeObjectListPreference({ - perView: { - v1: { addedFields: ['owner', 3, '', 'owner', 'discount'] }, - v2: { addedFields: [] }, - v3: { addedFields: 'owner' }, - }, - })).toEqual({ perView: { v1: { addedFields: ['owner', 'discount'] } } }); - }); - - it('a patch sets the added fields beside the hidden ones; an empty list or `null` clears only that part', () => { - let state = patchViewPreference({}, 'v1', { hiddenFields: ['amount'] }); - state = patchViewPreference(state, 'v1', { addedFields: ['owner'] }); - expect(state).toEqual({ perView: { v1: { hiddenFields: ['amount'], addedFields: ['owner'] } } }); - expect(patchViewPreference(state, 'v1', { addedFields: [] })).toEqual({ perView: { v1: { hiddenFields: ['amount'] } } }); - expect(patchViewPreference(state, 'v1', { addedFields: null })).toEqual({ perView: { v1: { hiddenFields: ['amount'] } } }); - }); - - it('"Reset view" drops the added fields with the rest of the view\'s entry', () => { - const state = { perView: { v1: { addedFields: ['owner'] }, v2: { addedFields: ['discount'] } } }; - expect(resetViewPreference(state, 'v1')).toEqual({ perView: { v2: { addedFields: ['discount'] } } }); - }); -}); diff --git a/ui/packages/app-shell/src/context/__tests__/signOutPurge.test.tsx b/ui/packages/app-shell/src/context/__tests__/signOutPurge.test.tsx index 814c17a499b..2d3e798959e 100644 --- a/ui/packages/app-shell/src/context/__tests__/signOutPurge.test.tsx +++ b/ui/packages/app-shell/src/context/__tests__/signOutPurge.test.tsx @@ -1,16 +1,18 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * Sign-out clears the per-user list state and list filters the console wrote - * for the signed-out user, on every sign-out path, and leaves the server-side - * preference rows alone. + * Sign-out clears the list layout this browser keeps for the signed-out user, + * on every sign-out path, and the keys an earlier Console wrote list state + * under with it. * - * The keys are written here by their real writers — `ListPreferencesProvider` - * (`list-state:USER:OBJECT`) and `listFilterStorage` (`list-filters:USER:OBJECT:VIEW`) - * — and removed by signing out through the real `AuthProvider` - * (`@object-ui/auth`). `@object-ui/app-shell` depends on `@object-ui/auth`, so - * the sweep cannot import these spellings; filling the keys by running their - * writers is what keeps the two ends from drifting. + * The layout key is written here by its real writer — `useObjectListLayout` + * (`list-layout:USER:OBJECT`, objectstack#35955) — and removed by signing out + * through the real `AuthProvider` (`@object-ui/auth`). `@object-ui/app-shell` + * depends on `@object-ui/auth`, so the sweep cannot import this spelling; + * filling the key by running its writer is what keeps the two ends from + * drifting. The retired spellings (`list-state:USER:OBJECT`, the cache of the + * retired server row `ui.list.`, and `list-filters:USER:OBJECT:VIEW`) + * have no writer left, so they are planted by hand. * * The sign-in page language stays: the two keys are imported from * `@object-ui/i18n` here, so a spelling that changes there fails this file @@ -28,25 +30,15 @@ import { type AuthContextValue, } from '@object-ui/auth'; import { LOCALE_SEED_STORAGE_KEY, LOCALE_STORAGE_KEY } from '@object-ui/i18n'; -import type { UserPreferenceFamily } from '@object-ui/data-objectstack'; -import { - ListPreferencesProvider, - localListStateKey, - useObjectListPreferences, - type ObjectListPreference, -} from '../ListPreferencesProvider'; -import { UserStateAdaptersProvider, useAttachListStateFamily } from '../UserStateAdapters'; -import { buildListFilterKey, writeListFilterState } from '../../views/listFilterStorage'; +import { listLayoutStorageKey, resetListLayoutStoreForTests, useObjectListLayout } from '../../views/listLayoutStore'; const ORG = { id: 'org_a', name: 'Acme', slug: 'acme' }; const ALICE = { id: 'u_alice', name: 'Alice', email: 'alice@test.com' }; const OBJECT = 'account'; -const VIEW = 'all'; -const GROUP = { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'x' }] }; +const VIEW = 'account.all'; -/** The keys this file's writers produce for Alice. */ -const LIST_STATE_KEY = localListStateKey(ALICE.id, OBJECT); -const LIST_FILTER_KEY = buildListFilterKey(ALICE.id, OBJECT, VIEW)!; +/** The key this file's writer produces for Alice. */ +const LAYOUT_KEY = listLayoutStorageKey(ALICE.id, OBJECT)!; /** The real client clears `TokenStorage` on sign-out; this double does too. */ function authClient(getSession: () => Promise): AuthClient { @@ -64,37 +56,10 @@ function authClient(getSession: () => Promise): AuthClient { } as unknown as AuthClient; } -/** The server-side list-state family: one row per object, never asked to change at sign-out. */ -function serverFamily(): UserPreferenceFamily & { - load: ReturnType; - save: ReturnType; -} { - return { - prefix: 'ui.list.', - load: vi.fn().mockResolvedValue({}), - save: vi.fn().mockResolvedValue(undefined), - }; -} - -/** Attaches the family while a user is signed in, as the console's bridge does. */ -function FamilyBridge({ family }: { family: UserPreferenceFamily }) { - const { user } = useAuth(); - const attach = useAttachListStateFamily(); - useEffect(() => { - if (!user?.id) { - attach(null); - return; - } - attach(family); - return () => attach(null); - }, [user?.id, family, attach]); - return null; -} - -/** What one committed render showed: the session, and the list state it offered. */ +/** What one committed render showed: the session, and the layout it offered. */ interface Committed { auth: AuthContextValue; - prefs: ReturnType; + layout: ReturnType; } /** The last committed render's view, written as one object so its two halves never come from two renders. */ @@ -102,9 +67,9 @@ const committed: { current: Committed | null } = { current: null }; function Probe() { const auth = useAuth(); - const prefs = useObjectListPreferences(OBJECT); + const layout = useObjectListLayout(OBJECT); useEffect(() => { - committed.current = { auth, prefs }; + committed.current = { auth, layout }; }); return {auth.user?.name ?? 'none'}; } @@ -113,75 +78,34 @@ function auth(): AuthContextValue { return committed.current!.auth; } -function renderConsole(client: AuthClient, family = serverFamily()) { +/** Sign in, and return the layout handle of a committed render that holds Alice's session. */ +async function signIn(client: AuthClient) { const view = render( - - - - - - + , ); - return { view, family }; -} - -/** - * Sign in, and return the list state of a committed render that holds Alice's - * session AND reports her stored state read. - * - * Both facts are read from ONE snapshot, and the patch goes through that - * snapshot. The snapshot is written after commit, so it trails the screen: a - * signed-out render reports `ready` (no user to wait for), and Alice's first - * render precedes the bridge attaching her family. A patch through either is - * written to this browser only and queues no server save. - */ -async function signIn(client: AuthClient, family = serverFamily()) { - const rendered = renderConsole(client, family); - const prefs = await waitFor(() => { - const view = committed.current; - expect(view?.auth.user?.id).toBe(ALICE.id); - expect(view?.prefs.ready).toBe(true); - return view!.prefs; + const layout = await waitFor(() => { + const seen = committed.current; + expect(seen?.auth.user?.id).toBe(ALICE.id); + return seen!.layout; }); - expect(rendered.view.getByTestId('user').textContent).toBe('Alice'); - return { ...rendered, prefs }; + expect(view.getByTestId('user').textContent).toBe('Alice'); + return { view, layout }; } -/** Sign in, then write a filter group and a search term through the real writers. */ -async function signInAndFilter(client: AuthClient) { - const { prefs, ...rendered } = await signIn(client); - act(() => { - prefs.patchView(VIEW, { filters: GROUP }); - }); - writeListFilterState(LIST_FILTER_KEY, { search: 'term' }); - // The search write has landed past its debounce; the list state is written - // at once, and is what the user's server row holds once its save is sent. - await waitFor(() => expect(localStorage.getItem(LIST_FILTER_KEY)).not.toBeNull()); - const userState = JSON.parse(localStorage.getItem(LIST_STATE_KEY)!) as ObjectListPreference; - expect(userState).not.toEqual({}); - return { ...rendered, userState }; -} - -/** - * The server-side row is the user's state on every device: whatever is sent - * to it, before or after the sign-out, is the state the user left, never a - * cleared one. - */ -function expectServerRowsKept( - family: ReturnType, - userState: ObjectListPreference, -) { - // Sent by its debounce or by the flush: `signOut()` flushes it before the - // session ends, and a session that ends any other way flushes it as the - // family detaches. Sent either way, before the sign-out settles. - expect(family.save).toHaveBeenCalled(); - for (const [, value] of family.save.mock.calls) expect(value).toEqual(userState); +/** Sign in, drag a width through the real writer, and plant the keys an earlier Console left. */ +async function signInAndArrange(client: AuthClient) { + const signedIn = await signIn(client); + act(() => signedIn.layout.patchView(VIEW, { widths: { name: 240 } })); + expect(JSON.parse(localStorage.getItem(LAYOUT_KEY)!)).toEqual({ perView: { [VIEW]: { widths: { name: 240 } } } }); + localStorage.setItem(`list-state:${ALICE.id}:${OBJECT}`, JSON.stringify({ viewOrder: [VIEW] })); + localStorage.setItem(`list-filters:${ALICE.id}:${OBJECT}:${VIEW}`, JSON.stringify({ search: 'term' })); + return signedIn; } function listKeysLeft(): string[] { - return Object.keys(localStorage).filter((k) => k.startsWith('list-state:') || k.startsWith('list-filters:')); + return Object.keys(localStorage).filter((k) => /^(list-layout|list-state|list-filters):/.test(k)); } beforeEach(() => { @@ -189,6 +113,7 @@ beforeEach(() => { localStorage.clear(); sessionStorage.clear(); TokenStorage.clear(); + resetListLayoutStoreForTests(); }); afterEach(() => { @@ -196,12 +121,17 @@ afterEach(() => { vi.restoreAllMocks(); }); -describe('sign-out clears the signed-out user’s list state and list filters', () => { - it('signOut() removes every list-state and list-filters key and keeps the sign-in page language', async () => { +describe('sign-out clears the list layout this browser keeps for the signed-out user (objectstack#35955)', () => { + it('signOut() removes every list-layout key, and the retired list-state and list-filters keys, and keeps the sign-in page language', async () => { const client = authClient(async () => ({ user: ALICE, session: { token: 'tok-alice' } })); - const { family, userState } = await signInAndFilter(client); + await signInAndArrange(client); localStorage.setItem(LOCALE_STORAGE_KEY, 'de'); localStorage.setItem(LOCALE_SEED_STORAGE_KEY, 'de'); + expect(listKeysLeft().sort()).toEqual([ + `list-filters:${ALICE.id}:${OBJECT}:${VIEW}`, + LAYOUT_KEY, + `list-state:${ALICE.id}:${OBJECT}`, + ]); await act(async () => { await auth().signOut(); @@ -210,45 +140,12 @@ describe('sign-out clears the signed-out user’s list state and list filters', expect(listKeysLeft()).toEqual([]); expect(localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('de'); expect(localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('de'); - expectServerRowsKept(family, userState); - }); - - it('signOut() saves the last list change under the session, before the session ends', async () => { - // What happened, in order: the save is sent and settles while the session - // still exists. Sent after `client.signOut()`, the server would refuse it - // and the user's last list change would be lost on every device. - const events: string[] = []; - const client = authClient(async () => ({ user: ALICE, session: { token: 'tok-alice' } })); - (client.signOut as ReturnType).mockImplementation(async () => { - events.push('session ended'); - TokenStorage.clear(); - }); - const family = serverFamily(); - family.save.mockImplementation(async () => { - events.push('save sent'); - // A server answer arrives in a later task, never in the same one. - await new Promise((resolve) => setTimeout(resolve, 0)); - events.push('save settled'); - }); - const { prefs } = await signIn(client, family); - act(() => { - prefs.patchView(VIEW, { filters: GROUP }); - }); - const userState = JSON.parse(localStorage.getItem(LIST_STATE_KEY)!) as ObjectListPreference; - - await act(async () => { - await auth().signOut(); - }); - - expect(events).toEqual(['save sent', 'save settled', 'session ended']); - expect(family.save).toHaveBeenCalledWith(`ui.list.${OBJECT}`, userState); - expect(listKeysLeft()).toEqual([]); }); it('a session read that answers no session removes them too', async () => { let live = true; const client = authClient(async () => (live ? { user: ALICE, session: { token: 'tok-alice' } } : null)); - const { view, family, userState } = await signInAndFilter(client); + const { view } = await signInAndArrange(client); live = false; await act(async () => { @@ -257,39 +154,18 @@ describe('sign-out clears the signed-out user’s list state and list filters', expect(view.getByTestId('user').textContent).toBe('none'); expect(listKeysLeft()).toEqual([]); - expectServerRowsKept(family, userState); }); - it('a search typed just before sign-out is not written after it', async () => { + it('with nobody signed in, a layout change writes nothing back', async () => { const client = authClient(async () => ({ user: ALICE, session: { token: 'tok-alice' } })); - await signInAndFilter(client); - - writeListFilterState(LIST_FILTER_KEY, { search: 'typed-at-sign-out' }); + await signInAndArrange(client); await act(async () => { await auth().signOut(); }); - // Past the write debounce. - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 400)); - }); - - expect(listKeysLeft()).toEqual([]); - }); - - it('a search typed just before a session read answers no session is not written after it', async () => { - let live = true; - const client = authClient(async () => (live ? { user: ALICE, session: { token: 'tok-alice' } } : null)); - await signInAndFilter(client); + await waitFor(() => expect(committed.current?.auth.user ?? null).toBeNull()); - writeListFilterState(LIST_FILTER_KEY, { search: 'typed-at-expiry' }); - live = false; - await act(async () => { - await auth().refreshSession(); - }); - // Past the write debounce. - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 400)); - }); + act(() => committed.current!.layout.patchView(VIEW, { widths: { name: 300 } })); + act(() => committed.current!.layout.setViewOrder([VIEW])); expect(listKeysLeft()).toEqual([]); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx index 8c8c59cfd7e..4e310a7e3f4 100644 --- a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx @@ -179,7 +179,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { localListStateKey } from '../context/ListPreferencesProvider'; +import { listLayoutStorageKey } from './listLayoutStore'; import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; const OBJECT_NAME = 'duly_task'; @@ -320,11 +320,11 @@ const viewWrites = (dataSource: any): unknown[][] => [ * objectui#12474 — the hidden fields this user chose for `viewId`. Since * objectstack#35955 the choice is the list's DRAFT (`./listDraftStore.ts`): * kept while the reader opens a record and comes back (a remount here), never - * stored. The second half reads that nothing reaches the reader's stored - * state either. + * stored. The second half reads that nothing reaches the layout this + * browser keeps for the reader either. */ function storedHiddenFields(viewId: string): unknown { - const raw = localStorage.getItem(localListStateKey('u1', OBJECT_NAME)); + const raw = localStorage.getItem(listLayoutStorageKey('u1', OBJECT_NAME)!); expect(raw ? JSON.parse(raw)?.perView?.[viewId]?.hiddenFields : undefined).toBeUndefined(); return readListDraft(listDraftScope('u1', OBJECT_NAME, viewId)).hiddenFields; } @@ -641,7 +641,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the }, }; localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), + `list-state:u1:${OBJECT_NAME}`, JSON.stringify({ perView: { [PROBE_ID]: { hiddenFields: ['stage'] } } }), ); await mountRoute(listViews, PROBE_ID, makeDataSource()); diff --git a/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx index c7192e39f05..9ec2fa5cee7 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx @@ -1,7 +1,7 @@ /** * objectstack#35955 — Discard and Save on a list that holds a draft (the - * 「Personalized」 marker of objectstack#28950 before it), at the host seam: the real object page, the real - * `ListPreferencesProvider` and the real router, with `ListView` captured (its + * 「Personalized」 marker of objectstack#28950 before it), at the host seam: the real object page, the + * reader's list layout in this browser (`./listLayoutStore.ts`) and the real router, with `ListView` captured (its * own half, what of the list differs from the view, is pinned in plugin-list's * `ListView.personalization-28950.test.tsx`). * @@ -115,11 +115,9 @@ vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ import { ObjectView, type ConsoleObjectViewProps } from './ObjectView'; import { listDraftScope, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; -import { ListPreferencesProvider } from '../context/ListPreferencesProvider'; +import { listLayoutStorageKey, resetListLayoutStoreForTests } from './listLayoutStore'; import { withoutListStateParams } from './objectViewListUrlState'; import { applyListStateParams, applyUserFilterParams } from './userFilterUrlState'; -import { buildListFilterKey } from './listFilterStorage'; const FIELDS = { id: { type: 'text', label: 'Id' }, @@ -152,25 +150,6 @@ function makeDataSource() { } as unknown as ConsoleObjectViewProps['dataSource']; } -function makeFamily(rows: Record) { - return { - prefix: 'ui.list.', - load: vi.fn(async () => structuredClone(rows) as Record), - save: vi.fn(async (key: string, value: unknown) => { - rows[key] = structuredClone(value); - }), - }; -} - -function AttachFamily({ family }: { family: any }) { - const attach = useAttachListStateFamily(); - React.useEffect(() => { - attach(family); - return () => attach(null); - }, [attach, family]); - return null; -} - /** The address bar, as the page last wrote it. */ let currentSearch = ''; function LocationProbe() { @@ -181,28 +160,23 @@ function LocationProbe() { return null; } -function mount(family: any, query = '') { +function mount(query = '') { return render( - - - - - - - - - {}} /> - - )} - /> - - - - - , + + + + + + {}} /> + + )} + /> + + + , ); } @@ -236,6 +210,7 @@ beforeEach(() => { currentSearch = ''; localStorage.clear(); resetListDraftStoreForTests(); + resetListLayoutStoreForTests(); client = new MetadataClient({ baseUrl: 'http://localhost', fetch: vi.fn(async () => json({ data: [] }, 200)) as unknown as typeof fetch }); vi.stubGlobal('fetch', vi.fn(async () => json({ data: [] }, 200))); vi.spyOn(console, 'error').mockImplementation(() => {}); @@ -271,7 +246,7 @@ function openMenu(trigger: HTMLElement) { describe('Discard and Save, while the list holds a draft (objectstack#35955; the marker of objectstack#28950 before it)', () => { it('is drawn only while the list reports a draft part, names the parts in the Save menu, and the header ⋯ carries no reset', async () => { - mount(makeFamily({})); + mount(); await listReady(); expect(screen.queryByTestId('list-draft')).toBeNull(); @@ -298,8 +273,7 @@ describe('Discard and Save, while the list holds a draft (objectstack#35955; the }); it('after a reload, Discard opens the list as the view declares it and leaves no `uf_*` param behind', async () => { - const family = makeFamily({}); - mount(family, personalizedQuery()); + mount(personalizedQuery()); await listReady(); // The list opened from the link: every part of it is the reader's. expect(listProps.initialSearchTerm).toBe('Alan'); @@ -327,13 +301,12 @@ describe('Discard and Save, while the list holds a draft (objectstack#35955; the }); it('in session, the search is the draft\'s: kept nowhere durable, and Discard drops it', async () => { - mount(makeFamily({})); + mount(); await listReady(); - const cacheKey = buildListFilterKey(session.userId, OBJECT_NAME, SYSTEM_ID); act(() => listProps.onSearchChange('Alan')); await wait(400); - expect(localStorage.getItem(cacheKey!)).toBeNull(); + expect(Object.keys(localStorage).filter((key) => key.includes(OBJECT_NAME))).toEqual([]); expect(readListDraft(listDraftScope(session.userId, OBJECT_NAME, SYSTEM_ID)).search).toBe('Alan'); expect(new URLSearchParams(currentSearch).get('uf__search')).toBe('Alan'); @@ -348,9 +321,10 @@ describe('Discard and Save, while the list holds a draft (objectstack#35955; the expect(ufParams()).toEqual([]); }); - it('column widths are the reader\'s, never a draft: a stored width draws nothing, and Discard keeps it', async () => { - const family = makeFamily({ [`ui.list.${OBJECT_NAME}`]: { perView: { [SYSTEM_ID]: { columnState: { widths: { name: 280 } } } } } }); - mount(family); + it('column widths are the reader\'s, never a draft: a kept width draws nothing, and Discard keeps it', async () => { + const layoutKey = listLayoutStorageKey(session.userId, OBJECT_NAME)!; + localStorage.setItem(layoutKey, JSON.stringify({ perView: { [SYSTEM_ID]: { widths: { name: 280 } } } })); + mount(); await listReady(); expect(screen.queryByTestId('list-draft')).toBeNull(); expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); @@ -365,9 +339,7 @@ describe('Discard and Save, while the list holds a draft (objectstack#35955; the expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); expect(screen.queryByTestId('list-draft')).toBeNull(); - // Nothing of the order reached the reader's stored row. - for (const [, value] of family.save.mock.calls) { - expect(JSON.stringify(value)).not.toContain('order'); - } + // Nothing of the order reached the reader's kept layout. + expect(JSON.parse(localStorage.getItem(layoutKey)!)).toEqual({ perView: { [SYSTEM_ID]: { widths: { name: 280 } } } }); }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx index 62631fd7f18..c29549736db 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx @@ -98,9 +98,7 @@ import '@objectstack/lint'; // opened with is read (objectui#11860's grouping pins below). import '@object-ui/plugin-grid'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { buildListFilterKey } from './listFilterStorage'; import { LIST_FILTER_PARAM, LIST_GROUP_PARAM, LIST_SEARCH_PARAM, LIST_SORT_PARAM, withoutListStateParams } from './userFilterUrlState'; -import { localListStateKey } from '../context/ListPreferencesProvider'; import { listDraftScope, patchListDraft, resetListDraftStoreForTests, type ListDraftPatch } from './listDraftStore'; import { acceptStoredFilters, acceptStoredSort } from './objectViewListUrlState'; import { toast } from 'sonner'; @@ -485,10 +483,10 @@ function storeViewPreference(viewId: string, pref: { sort?: unknown; filters?: u describe('objectstack#35955 — state an earlier console stored for the reader no longer opens the list', () => { it('a stored sort and filter, in the server row\'s cache or the older per-browser key, are not applied', async () => { - localStorage.setItem(localListStateKey('u1', OBJ), JSON.stringify({ + localStorage.setItem(`list-state:u1:${OBJ}`, JSON.stringify({ perView: { all: { sort: [{ field: 'due_date', order: 'desc' }], filters: { id: 'root', logic: 'and', conditions: [{ id: 'p', field: 'priority', operator: 'equals', value: 'urgent' }] } } }, })); - localStorage.setItem(buildListFilterKey('u1', OBJ, 'all')!, JSON.stringify({ search: 'mine' })); + localStorage.setItem(`list-filters:u1:${OBJ}:all`, JSON.stringify({ search: 'mine' })); const host = await mountHost([`${VIEW}/all`]); const q = lastQuery(); expect(filterOf(q)).not.toContain('urgent'); diff --git a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts index 650f672b86a..1f491723604 100644 --- a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts +++ b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts @@ -350,7 +350,7 @@ describe('objectui#12504 census — the toolbar-to-view write family is retired' }); it('CONTROL: the doors objectui#12474 moved write the reader\'s state, never the view (density kept, hidden fields a draft since objectstack#35955)', () => { - expect(objectViewCode).toMatch(/onDensityChange:\s*\(mode\)\s*=>\s*\{\s*listPrefs\.patchView\(/); + expect(objectViewCode).toMatch(/onDensityChange:\s*\(mode\)\s*=>\s*\{[\s\S]{0,240}?listLayout\.patchView\(/); expect(objectViewCode).toMatch(/const persistHiddenFields = \(hidden: string\[\]\) => \{[\s\S]{0,120}?listDraft\.patch\(\{ hiddenFields: hidden \}\)/); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx index adb040185ad..f8c92932732 100644 --- a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx @@ -107,8 +107,6 @@ vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); import { ObjectView } from './ObjectView'; import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests, type ListDraftPatch } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; -import { ListPreferencesProvider, listPreferenceKey } from '../context/ListPreferencesProvider'; import { applyListStateParams } from './userFilterUrlState'; import { toast } from 'sonner'; @@ -444,26 +442,24 @@ describe('objectstack#29635 — My views in the list view switcher', () => { }); /** - * objectstack#30034 — the two reads a personal view opened by its address - * waits on: the reader's own views (`sys_personal_view`) and the list - * preferences (the attached family's first load). Each lands when the case - * says, and the address bar is the page's history, read where the router - * wrote it. + * objectstack#30034 — a personal view opened by its address waits on the + * reader's own views (`sys_personal_view`), while the default view holds a + * draft of the reader's (objectstack#35955: what they changed there and left; + * before it, the stored list preferences, a second read). The read lands when + * the case says, and the address bar is the page's history, read where the + * router wrote it. * * The race the card measured: the location the router hands the page moves in * a transition, so a read landing between the page's URL write and its commit * renders against the address as it was before that write. `landPersonalOn` - * `'firstReplace'` lands the personal views read exactly there. + * `'firstReplace'` lands the personal views read exactly there; `'atOnce'` + * lands it before the page writes the address at all. */ describe('objectstack#30034 — a personal view opened by its address never carries the default view\'s list state', () => { - /** The reader's stored list state for the DEFAULT view, `v1`: a filter and a sort. */ - const DEFAULT_VIEW_STATE = { - perView: { - v1: { - sort: [{ field: 'status', order: 'desc' }], - filters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'city', operator: 'equals', value: 'Rome' }] }, - }, - }, + /** The reader's draft on the DEFAULT view, `v1`: a filter and a sort. */ + const DEFAULT_VIEW_DRAFT = { + sort: [{ field: 'status', order: 'desc' as const }], + filters: { id: 'root', logic: 'and' as const, conditions: [{ id: 'c1', field: 'city', operator: 'equals', value: 'Rome' }] }, }; function deferred() { @@ -472,26 +468,15 @@ describe('objectstack#30034 — a personal view opened by its address never carr return { promise, resolve }; } - function AttachFamily({ family }: { family: unknown }) { - const attach = useAttachListStateFamily(); - React.useEffect(() => { - attach(family as never); - return () => attach(null); - }, [attach, family]); - return null; - } - function mountPersonal( entry: string, - { landPersonalOn }: { landPersonalOn: 'firstReplace' | 'beforePreferences' }, + { landPersonalOn }: { landPersonalOn: 'firstReplace' | 'atOnce' }, ) { + patchListDraft(listDraftScope('u1', 'crm_lead', 'v1'), DEFAULT_VIEW_DRAFT as ListDraftPatch); const objects = [LEAD]; const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); const personalRead = deferred<{ data: unknown[]; total: number }>(); - const preferencesRead = deferred>(); const landPersonal = () => personalRead.resolve({ data: [OWN], total: 1 }); - const landPreferences = () => preferencesRead.resolve({ [listPreferenceKey('crm_lead')]: structuredClone(DEFAULT_VIEW_STATE) }); - const family = { prefix: 'ui.list.', load: vi.fn(() => preferencesRead.promise), save: vi.fn(async () => {}) }; const history = createMemoryHistory({ initialEntries: [entry], v5Compat: true }); const replace = history.replace.bind(history); let replaced = 0; @@ -509,28 +494,22 @@ describe('objectstack#30034 — a personal view opened by its address never carr delete: vi.fn(async () => ({})), }; render( - - - - - - - - {}} />} - /> - - - - - - , + + + + + {}} />} + /> + + + + , ); return { dataSource, landPersonal, - landPreferences, /** The `uf_*` params of the address bar, by name. */ ufParams: () => Object.fromEntries([...new URLSearchParams(history.location.search)].filter(([key]) => key.startsWith('uf_'))), }; @@ -544,11 +523,9 @@ describe('objectstack#30034 — a personal view opened by its address never carr .filter(([resource, params]) => resource === 'crm_lead' && (params as { $top?: number } | undefined)?.$top !== 0) .map(([, params]) => params as Record); - it('the personal views read landing AFTER the preferences read: the address bar ends clean, holding only the personal view\'s own state', async () => { + it('the personal views read still out while the default view\'s draft is held: the address bar ends clean, holding only the personal view\'s own state', async () => { const page = mountPersonal('/apps/crm/crm_lead/view/pv_mine', { landPersonalOn: 'firstReplace' }); - // The preferences land first; the personal views read is still out. await waitFor(() => expect(page.dataSource.find.mock.calls.some(([r]) => r === 'sys_personal_view')).toBe(true)); - page.landPreferences(); await settle(); // Nothing wrote the address while the requested view was unresolved, so // the personal views read is still out: land it now. @@ -563,12 +540,10 @@ describe('objectstack#30034 — a personal view opened by its address never carr expect(last).not.toContain('Rome'); }); - it('the reverse order — the personal views read landing BEFORE the preferences read: the address bar ends clean too', async () => { - const page = mountPersonal('/apps/crm/crm_lead/view/pv_mine', { landPersonalOn: 'beforePreferences' }); + it('the personal views read landing at once: the address bar ends clean too', async () => { + const page = mountPersonal('/apps/crm/crm_lead/view/pv_mine', { landPersonalOn: 'atOnce' }); await waitFor(() => expect(page.dataSource.find.mock.calls.some(([r]) => r === 'sys_personal_view')).toBe(true)); page.landPersonal(); - await settle(); - page.landPreferences(); await listToolbar(); expect(switcher()).toHaveTextContent('Paris leads'); await settle(); @@ -583,7 +558,6 @@ describe('objectstack#30034 — a personal view opened by its address never carr const query = applyListStateParams(new URLSearchParams(), { sort }).toString(); const page = mountPersonal(`/apps/crm/crm_lead/view/pv_mine?${query}`, { landPersonalOn: 'firstReplace' }); await waitFor(() => expect(page.dataSource.find.mock.calls.some(([r]) => r === 'sys_personal_view')).toBe(true)); - page.landPreferences(); await settle(); page.landPersonal(); await listToolbar(); diff --git a/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx b/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx index 620cce2eb42..d6bd204838a 100644 --- a/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx @@ -325,12 +325,11 @@ afterEach(() => { describe('objectui#11642 — two toolbar changes in one session both survive a reload, on every row kind', () => { /** * objectui#12474 — the density and the hidden fields are the USER's own - * list state now (`listPrefs`, beside the sort and the column layout), so - * neither change writes the view on any row kind: each row is left exactly - * as stored, and the reload shows both changes from the user's state. This - * harness mounts no preference provider, so that state is this browser's - * (the provider-less fallback); the cross-device half is - * `ObjectView.userListState-12418.test.tsx`'s. + * now, so neither change writes the view on any row kind: each row is left + * exactly as stored, and the reload shows both changes. Since + * objectstack#35955 the density is the reader's layout in this browser + * (`./listLayoutStore.ts`) and the hidden fields are the list's draft; the + * rest is `ObjectView.userListState-12418.test.tsx`'s. */ async function bothSurviveWithNoViewWrite(seed: Record, viewId: string) { const { meta, rows } = makeStore([seed]); @@ -364,5 +363,5 @@ describe('objectui#11642 — two toolbar changes in one session both survive a r // own write queue (a 300 ms debounce, then each PUT waiting for the previous // one). Since objectui#12474 no list toolbar control reached that function, and // objectui#12504 retired it, so there is no toolbar write left to queue; the -// user's state has its own debounce, pinned by +// reader's layout is written to this browser at once, pinned by // `ObjectView.userListState-12418.test.tsx`. diff --git a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx index c0bbecd8966..ac45e9ef4e2 100644 --- a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx @@ -96,7 +96,6 @@ import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { resetListDraftStoreForTests } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { buildListFilterKey } from './listFilterStorage'; import { LIST_FILTER_PARAM } from './userFilterUrlState'; const OBJ = 'uf_task'; @@ -278,7 +277,7 @@ describe('a view switch reads the next view\'s own URL for its quick filters (ob // A Filter panel group an earlier console kept for this browser: since // objectstack#35955 a list opens on its draft only, never on stored state. localStorage.setItem( - buildListFilterKey('u1', OBJ, 'qb')!, + `list-filters:u1:${OBJ}:qb`, JSON.stringify({ filters: { id: 'root', logic: 'and', conditions: [{ id: 'r', field: 'status', operator: 'equals', value: 'open' }] } }), ); const host = await mountHost(`${VIEW}/qa?uf_priority=urgent`); diff --git a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx index f6636a599e6..5067daa5544 100644 --- a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx @@ -15,42 +15,40 @@ * * ## What runs * - * The real object page, the real `ListPreferencesProvider` (its 500 ms write - * debounce included) and a list-state family that records its `load` and - * `save` the way `@object-ui/data-objectstack`'s does (`sys_user_preference`, - * one `ui.list.` row per object). The view writes are the adapter's - * `updateView` spy and, for the view editor's save, a real `MetadataClient` - * whose `PUT /meta/view/…` is counted. `ListView` is captured (a toolbar change - * is the page's own callback) and Manage Views is reduced to its reorder and - * its config entry. + * The real object page, with the reader's list layout kept where the page + * keeps it: this browser's `list-layout::` entry + * (`./listLayoutStore.ts`), every write of which is recorded. The view writes + * are the adapter's `updateView` spy and, for the view editor's save, a real + * `MetadataClient` whose `PUT /meta/view/…` is counted. `ListView` is captured + * (a toolbar change is the page's own callback) and Manage Views is reduced to + * its reorder and its config entry. * * ## The pins * * 1. A header sort writes no view and nothing stored: it is the draft's. A - * column resize lands as ONE save of the object's row, widths only. A - * Manage Views drag lands as ONE save. The view editor's save still - * writes `/meta/view`. - * 2. A fresh browser opens on the reader's stored tab order and column - * widths once the family has loaded; a sort or filter an earlier console - * stored there no longer applies. Another user sees the view's own. - * Discard puts the list back as its view declares it and keeps the - * widths; it writes nothing. - * 3. objectui#12474 — the density stays the reader's stored choice; a Hide + * column resize is ONE write of the reader's layout, widths only. A + * Manage Views drag is ONE write. The view editor's save still writes + * `/meta/view`. + * 2. The list opens on the tab order and column widths this browser keeps + * for the reader; another user sees the view's own. Discard puts the list + * back as its view declares it and keeps the widths; it writes nothing. + * 3. objectui#12474 — the density stays the reader's kept choice; a Hide * Fields change is the draft's. objectui#12505 — on a saved view that * declares no `columns` the draft's hide applies over the drawn defaults. * 4. objectui#12949 — the list is handed the view's own density and hidden * fields in `viewDefaults`, beside the reader's in `schema`. * 5. objectstack#28948 — the list's "Reset to view default" drops the reset - * parts (from the draft, or the stored row height), so the reader follows + * parts (from the draft, or the kept row height), so the reader follows * later changes to the view; a deliberate `sort: []` / `hiddenFields: []` * is a draft part too. * 6. objectstack#30077 — a field the reader adds is a draft part: the list is * handed it appended to the view's columns, and Discard drops it. - * 7. CONTROL — no provider (a host without the console shell): a sort is the - * draft's there too; the older `viewOrder:` key still orders the - * tabs, and the Filter panel's older per-browser group no longer applies. - * 8. objectstack#32627 — a width change writes the reader's row only when it - * changes it. + * 7. objectstack#35955 — what an earlier Console kept (the `ui.list.` + * row's cache `list-state:*`, the Filter panel's `list-filters:*`, the + * bare `viewOrder:`) is removed and never read: a part an earlier + * Console stored no longer applies. + * 8. objectstack#32627 — a width change writes the reader's layout only when + * it changes it. */ @@ -142,7 +140,6 @@ vi.mock('./metadata-admin/inspectors/ViewVariantInspector', () => ({ const OBJECT_NAME = 'crm_deal'; const SYSTEM_ID = `${OBJECT_NAME}.all`; const SAVED_ID = `${OBJECT_NAME}.pipeline`; -const LIST_KEY = `ui.list.${OBJECT_NAME}`; /** The tab order Manage Views is handed, as its stub last saw it. */ let manageViewsOrder: string[] = []; @@ -190,8 +187,7 @@ vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ import '@objectstack/lint'; import { ObjectView, type ConsoleObjectViewProps } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; -import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; -import { ListPreferencesProvider, localListStateKey } from '../context/ListPreferencesProvider'; +import { listLayoutStorageKey, resetListLayoutStoreForTests } from './listLayoutStore'; import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; const FIELDS = { @@ -231,30 +227,34 @@ function makeDataSource(savedRow: Record = SAVED_ROW) { } as unknown as ConsoleObjectViewProps['dataSource']; } -/** A list-state family recording its traffic; `rows` is the user's stored rows. */ -function makeFamily(rows: Record, opts: { held?: boolean } = {}) { - let release: () => void = () => {}; - const gate = opts.held ? new Promise((resolve) => { release = resolve; }) : Promise.resolve(); - const family = { - prefix: 'ui.list.', - load: vi.fn(async () => { - await gate; - return structuredClone(rows) as Record; - }), - save: vi.fn(async (key: string, value: unknown) => { - rows[key] = structuredClone(value); - }), +/** The signed-in reader's layout entry for the object, in this browser. */ +const layoutKey = () => listLayoutStorageKey(session.userId, OBJECT_NAME); + +/** + * Every write of a `list-layout:` entry since the case's {@link makeLayout}, as + * the value written (a removed entry as `{}`). Recorded by wrapping the storage + * methods once for the file, so no case's spy outlives it. + */ +const layoutWrites: unknown[] = []; +{ + const proto = Storage.prototype; + const setItem = proto.setItem; + const removeItem = proto.removeItem; + proto.setItem = function (this: Storage, key: string, value: string) { + if (key.startsWith('list-layout:')) layoutWrites.push(JSON.parse(value)); + return setItem.call(this, key, value); + }; + proto.removeItem = function (this: Storage, key: string) { + if (key.startsWith('list-layout:')) layoutWrites.push({}); + return removeItem.call(this, key); }; - return { family, release: () => release() }; } -function AttachFamily({ family }: { family: any }) { - const attach = useAttachListStateFamily(); - React.useEffect(() => { - attach(family); - return () => attach(null); - }, [attach, family]); - return null; +/** The reader's layout in this browser: `seed` is kept under their entry before the page mounts, and is not a write. */ +function makeLayout(seed?: Record) { + if (seed) localStorage.setItem(layoutKey()!, JSON.stringify(seed)); + layoutWrites.length = 0; + return { writes: layoutWrites }; } function page(dataSource: ConsoleObjectViewProps['dataSource'], viewId: string, opts: { app?: boolean } = {}) { @@ -275,14 +275,9 @@ function page(dataSource: ConsoleObjectViewProps['dataSource'], viewId: string, ); } -/** Mount the page in the console's preference providers, with `family` attached. */ -function mountWithFamily(dataSource: ConsoleObjectViewProps['dataSource'], family: any, viewId = SYSTEM_ID, opts: { app?: boolean } = {}) { - return render( - - - {page(dataSource, viewId, opts)} - , - ); +/** Mount the object page. */ +function mount(dataSource: ConsoleObjectViewProps['dataSource'], viewId = SYSTEM_ID, opts: { app?: boolean } = {}) { + return render(page(dataSource, viewId, opts)); } const wait = (ms: number) => act(() => new Promise((resolve) => setTimeout(resolve, ms))); @@ -339,6 +334,8 @@ beforeEach(() => { manageViewsOrder = []; localStorage.clear(); resetListDraftStoreForTests(); + resetListLayoutStoreForTests(); + layoutWrites.length = 0; client = new MetadataClient({ baseUrl: 'http://localhost', fetch: wire() as unknown as typeof fetch }); vi.stubGlobal('fetch', vi.fn(async () => json({ data: [] }, 200))); vi.spyOn(console, 'error').mockImplementation(() => {}); @@ -353,24 +350,21 @@ afterEach(() => { }); describe('a toolbar change writes no view (objectui#12418); what it changes is a draft (objectstack#35955)', () => { - it('a header sort writes nothing stored; a column resize lands as one save of the object\'s row, widths only', async () => { + it('a header sort writes nothing stored; a column resize is one write of the reader\'s layout, widths only', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => { listProps.onSortChange([{ id: 'row-1', field: 'amount', order: 'desc' }]); listProps.onColumnStateChange({ widths: { name: 320 } }); }); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { - perView: { [SYSTEM_ID]: { columnState: { widths: { name: 320 } } } }, - }); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { widths: { name: 320 } } } }]); // The sort is the draft's (the list holds it on screen itself). expect(draftOf().sort).toEqual([{ field: 'amount', order: 'desc' }]); // The page hands the grid the reader's widths back. @@ -379,18 +373,15 @@ describe('a toolbar change writes no view (objectui#12418); what it changes is a it('a column drag is the draft\'s order; the widths reported with it are the only stored part', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => listProps.onColumnStateChange({ order: ['amount', 'name'], widths: { name: 300 } })); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { - perView: { [SYSTEM_ID]: { columnState: { widths: { name: 300 } } } }, - }); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { widths: { name: 300 } } } }]); expect(draftOf().columnOrder).toEqual(['amount', 'name']); expect(listProps.schema.columnState).toEqual({ order: ['amount', 'name'], widths: { name: 300 } }); // A drag lights Discard and Save on its own: the list reports no part for it. @@ -399,42 +390,41 @@ describe('a toolbar change writes no view (objectui#12418); what it changes is a it('the schema-level sort relay is the same draft write', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => listProps.schema.onSortChange([{ field: 'amount', order: 'asc' }])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf().sort).toEqual([{ field: 'amount', order: 'asc' }]); }); - it('a Manage Views drag writes no view and lands as one save', async () => { + it('a Manage Views drag writes no view and is one write of the reader\'s layout', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(manageViewsOrder).toEqual([SYSTEM_ID, SAVED_ID]); await act(async () => { fireEvent.click(screen.getByTestId('stub-reorder')); }); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { viewOrder: [SAVED_ID, SYSTEM_ID] }); + expect(layout.writes).toEqual([{ viewOrder: [SAVED_ID, SYSTEM_ID] }]); // The tabs follow the user's order at once. expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); }); it('the view editor\'s save still writes /meta/view', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); fireEvent.click(screen.getByTestId('stub-config')); @@ -447,38 +437,23 @@ describe('a toolbar change writes no view (objectui#12418); what it changes is a }); await waitFor(() => expect(puts).toEqual([`/api/v1/meta/view/${SAVED_ID}`])); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); }); }); describe('what the reader keeps follows them; the draft does not (objectui#12418, objectstack#35955)', () => { - /** A row an earlier console stored: its sort and filters are no longer read. */ + /** The reader's layout kept in this browser: their tab order and one view's widths. */ const STORED = { - [LIST_KEY]: { - viewOrder: [SAVED_ID, SYSTEM_ID], - perView: { - [SYSTEM_ID]: { - sort: [{ field: 'amount', order: 'desc' }], - filters: { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'Acme' }] }, - columnState: { widths: { name: 280 } }, - }, - }, - }, + viewOrder: [SAVED_ID, SYSTEM_ID], + perView: { [SYSTEM_ID]: { widths: { name: 280 } } }, }; - it('a fresh browser opens on the stored tab order and column widths once the family has loaded; the stored sort and filters no longer apply', async () => { + it('the list opens on the tab order and column widths this browser keeps for the reader', async () => { const ds = makeDataSource(); - const { family, release } = makeFamily(structuredClone(STORED), { held: true }); - mountWithFamily(ds, family); - - // The list waits for the reader's state: nothing to open on yet. - await screen.findByTestId('object-view-list-preferences-pending'); - expect(listProps).toBeNull(); - - await act(async () => release()); + makeLayout(STORED); + mount(ds); await listReady(); - expect(family.load).toHaveBeenCalledTimes(1); expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); expect(listProps.schema.sort).toEqual(AUTHORED_SORT); @@ -490,8 +465,8 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 it('another user, with no state of their own, sees the view\'s authored defaults', async () => { session.userId = 'u2'; const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(manageViewsOrder).toEqual([SYSTEM_ID, SAVED_ID]); @@ -505,8 +480,8 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 it('Discard puts the list back as its view declares it, keeps the widths and writes nothing', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); const filters = { id: 'root', logic: 'and', conditions: [{ id: 'c2', field: 'name', operator: 'contains', value: 'Beta' }] }; act(() => { @@ -524,10 +499,10 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 expect(button.textContent?.trim()).toBe('console.objectView.draft.discard'); expect(button.getAttribute('title')).toBe('console.objectView.draft.discardTitle'); await discard(); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf()).toEqual({}); // The list is mounted again on the view's own. expect(listProps).not.toBe(before); @@ -541,8 +516,8 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 it('with no favorites entry (no app segment), the ⋯ offers no reset: the way back is Discard', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SYSTEM_ID, { app: false }); + const layout = makeLayout(); + mount(ds, SYSTEM_ID, { app: false }); await listReady(); // objectstack#35548 — the page bar's ⋮ also holds the description and @@ -566,8 +541,8 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 it('"Clear all" in the Filter panel drops the draft\'s filters and keeps its sort', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => { listProps.onSortChange([{ field: 'amount', order: 'asc' }]); @@ -576,62 +551,57 @@ describe('what the reader keeps follows them; the draft does not (objectui#12418 expect(draftOf().filters).toBeDefined(); act(() => listProps.onFilterChange({ id: 'root', logic: 'and', conditions: [] })); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf()).not.toHaveProperty('filters'); expect(draftOf().sort).toEqual([{ field: 'amount', order: 'asc' }]); }); }); describe('the density stays the reader\'s; the hidden fields are the draft\'s (objectui#12474, objectstack#35955)', () => { - it('a density toggle writes no view and lands as one save of the object\'s row', async () => { + it('a density toggle writes no view and is one write of the reader\'s layout', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); act(() => listProps.schema.onDensityChange('compact')); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }]); expect(listProps.schema.rowHeight).toBe('compact'); expect(draftOf()).toEqual({}); }); it('a Hide Fields change writes no view and nothing stored: the list is handed the draft\'s', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); // The whole list the popover emits: the reader showed `amount` and hid `name`. act(() => listProps.onHiddenFieldsChange(['name'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf().hiddenFields).toEqual(['name']); expect(listProps.schema.hiddenFields).toEqual(['name']); }); - const STORED = { - [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact', hiddenFields: [] } } }, - }; + const STORED = { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }; - it('a fresh browser opens on the stored density; hidden fields an earlier console stored no longer apply', async () => { + it('the list opens on the kept density; hidden fields found in the entry are not one of its parts and do not apply', async () => { const ds = makeDataSource(); - const { family, release } = makeFamily(structuredClone(STORED), { held: true }); - mountWithFamily(ds, family); - await screen.findByTestId('object-view-list-preferences-pending'); - await act(async () => release()); + makeLayout({ perView: { [SYSTEM_ID]: { rowHeight: 'compact', hiddenFields: [] } } }); + mount(ds); await listReady(); expect(listProps.schema.rowHeight).toBe('compact'); @@ -641,8 +611,8 @@ describe('the density stays the reader\'s; the hidden fields are the draft\'s (o it('another user, with no state of their own, sees the view\'s authored density and hidden fields', async () => { session.userId = 'u2'; const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); @@ -651,8 +621,8 @@ describe('the density stays the reader\'s; the hidden fields are the draft\'s (o it('Discard drops the hidden fields and keeps the stored density', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => { listProps.onHiddenFieldsChange(['name']); @@ -661,18 +631,18 @@ describe('the density stays the reader\'s; the hidden fields are the draft\'s (o expect(listProps.schema.hiddenFields).toEqual(['name']); await discard(); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(listProps.schema.rowHeight).toBe('compact'); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); }); it('a density the list reports alone draws no Discard: it is not a draft part', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => listProps.onPersonalizationChange(['density'])); await wait(50); @@ -690,26 +660,26 @@ describe('on a saved view that declares no `columns`, the draft\'s hidden fields it('a Hide Fields change writes no view and nothing stored, and applies at once', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); // The drawn defaults, with neither the view's key nor anyone's list applied. expect(listProps.schema.columns).toEqual(expect.arrayContaining(['name', 'amount'])); expect(listProps.schema.hiddenFields).toBeUndefined(); act(() => listProps.onHiddenFieldsChange(['amount'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf(SAVED_ID).hiddenFields).toEqual(['amount']); expect(listProps.schema.hiddenFields).toEqual(['amount']); }); - it('a list an earlier console stored for the view no longer applies', async () => { + it('a hidden list found in the reader\'s entry for the view does not apply', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({ [LIST_KEY]: { perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } } }); - mountWithFamily(ds, family, SAVED_ID); + makeLayout({ perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } }); + mount(ds, SAVED_ID); await listReady(); expect(listProps.schema.columns).toEqual(expect.arrayContaining(['name', 'amount'])); @@ -719,8 +689,8 @@ describe('on a saved view that declares no `columns`, the draft\'s hidden fields it('Discard drops the draft\'s list, and the list opens on the default columns', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); act(() => { listProps.onHiddenFieldsChange(['amount']); @@ -728,38 +698,36 @@ describe('on a saved view that declares no `columns`, the draft\'s hidden fields }); await discard(); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(listProps.schema.hiddenFields).toBeUndefined(); }); it('CONTROL: on the saved view that declares `columns`, the hide applies the same way', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); expect(listProps.schema.columns).toEqual(['name']); act(() => listProps.onHiddenFieldsChange(['name'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(listProps.schema.hiddenFields).toEqual(['name']); }); }); describe('the list is handed the view\'s own density and hidden fields beside the reader\'s (objectui#12949)', () => { - const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } } }; + const STORED = { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }; it('`schema` carries the reader\'s density and the draft\'s hidden fields, `viewDefaults` the view\'s own', async () => { const ds = makeDataSource(); - const { family, release } = makeFamily(structuredClone(STORED), { held: true }); - mountWithFamily(ds, family); - await screen.findByTestId('object-view-list-preferences-pending'); - await act(async () => release()); + makeLayout(STORED); + mount(ds); await listReady(); act(() => listProps.onHiddenFieldsChange(['name'])); @@ -770,19 +738,18 @@ describe('the list is handed the view\'s own density and hidden fields beside th it('a choice equal to the view\'s own, made through the controls\' doors, is still the reader\'s choice', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => { listProps.onHiddenFieldsChange(listProps.viewDefaults.hiddenFields); listProps.schema.onDensityChange('spacious'); }); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { rowHeight: AUTHORED_ROW_HEIGHT } } }); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { rowHeight: AUTHORED_ROW_HEIGHT } } }]); expect(draftOf().hiddenFields).toEqual(AUTHORED_HIDDEN); expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); @@ -792,8 +759,8 @@ describe('the list is handed the view\'s own density and hidden fields beside th it('CONTROL: another user, with no state of their own, is handed the same value twice', async () => { session.userId = 'u2'; const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); @@ -806,8 +773,8 @@ describe('the list is handed the view\'s own density and hidden fields beside th it('on a saved view that declares no `columns`, the view hides nothing: its authored key stays unapplied (objectui#12505)', async () => { const UNPROJECTED_SAVED_ROW = { name: SAVED_ID, object: OBJECT_NAME, label: 'Pipeline', type: 'grid', hiddenFields: ['name'] }; const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); act(() => listProps.onHiddenFieldsChange(['amount'])); @@ -817,24 +784,24 @@ describe('the list is handed the view\'s own density and hidden fields beside th }); describe('the list\'s "Reset to view default" drops the reset parts instead of copying the view into them (objectstack#28948)', () => { - const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } } }; + const STORED = { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }; const VIEW = OBJECT.listViews[SYSTEM_ID] as Record; /** - * Mount on `rows` with a draft sort and hidden fields that differ from the + * Mount on the kept layout `seed` with a draft sort and hidden fields that differ from the * view's: the draft is held before the list mounts, as when the reader comes * back from a record. */ - async function mountChanged(rows: Record = structuredClone(STORED)) { + async function mountChanged(seed: Record | undefined = STORED) { patchListDraft(listDraftScope(session.userId, OBJECT_NAME, SYSTEM_ID), { sort: [{ field: 'amount', order: 'desc' }], hiddenFields: ['name'], }); const ds = makeDataSource(); - const { family } = makeFamily(rows); - const mounted = mountWithFamily(ds, family); + const layout = makeLayout(seed); + const mounted = mount(ds); await listReady(); - return { ds, family, ...mounted }; + return { ds, layout, ...mounted }; } it('the list is wired to tell a reset from a choice, and is handed the view\'s own sort', async () => { @@ -846,15 +813,15 @@ describe('the list\'s "Reset to view default" drops the reset parts instead of c expect(listProps.viewDefaults.sort).toEqual(AUTHORED_SORT); }); - it('a Display reset of density and hidden fields drops the draft\'s hidden fields and the stored row height', async () => { - const { ds, family } = await mountChanged(); + it('a Display reset of density and hidden fields drops the draft\'s hidden fields and the kept row height', async () => { + const { ds, layout } = await mountChanged(); act(() => listProps.onRestoreViewDefaults(['hiddenFields', 'rowHeight'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); + // The view's entry is left with nothing: the reader's entry is removed. + expect(layout.writes).toEqual([{}]); expect(draftOf()).toEqual({ sort: [{ field: 'amount', order: 'desc' }] }); // The list is handed the view's own again. expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); @@ -862,10 +829,9 @@ describe('the list\'s "Reset to view default" drops the reset parts instead of c }); it('after the reset the reader follows the view: a changed `rowHeight` and `hiddenFields` reach them on the next open', async () => { - const rows = structuredClone(STORED) as Record; - const { unmount } = await mountChanged(rows); + const { unmount } = await mountChanged(); act(() => listProps.onRestoreViewDefaults(['hiddenFields', 'rowHeight'])); - await wait(700); + await wait(50); unmount(); // The view's author changes its defaults. @@ -874,7 +840,7 @@ describe('the list\'s "Reset to view default" drops the reset parts instead of c VIEW.hiddenFields = ['name']; try { listProps = null; - mountWithFamily(makeDataSource(), makeFamily(rows).family); + mount(makeDataSource()); await listReady(); expect(listProps.schema.rowHeight).toBe('short'); expect(listProps.schema.hiddenFields).toEqual(['name']); @@ -885,32 +851,31 @@ describe('the list\'s "Reset to view default" drops the reset parts instead of c }); it('a sort reset drops the draft\'s sort and writes nothing', async () => { - const { ds, family } = await mountChanged({}); + const { ds, layout } = await mountChanged(undefined); act(() => listProps.onRestoreViewDefaults(['sort'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf()).toEqual({ hiddenFields: ['name'] }); }); it('CONTROL: a deliberate "no sort" and "show every column" are draft parts, and survive the list being mounted again', async () => { - const rows: Record = {}; - const { unmount } = mountWithFamily(makeDataSource(), makeFamily(rows).family); + const { unmount } = mount(makeDataSource()); await listReady(); act(() => { listProps.onSortChange([]); listProps.onHiddenFieldsChange([]); }); - await wait(700); - expect(rows).toEqual({}); + await wait(50); + expect(localStorage.getItem(layoutKey()!)).toBeNull(); expect(draftOf()).toEqual({ sort: [], hiddenFields: [] }); unmount(); // Opening a record as a page and coming back mounts the list again. listProps = null; - mountWithFamily(makeDataSource(), makeFamily(rows).family); + mount(makeDataSource()); await listReady(); expect(listProps.schema.sort).toEqual([]); expect(listProps.schema.hiddenFields).toEqual([]); @@ -920,28 +885,28 @@ describe('the list\'s "Reset to view default" drops the reset parts instead of c describe('a field the reader adds to their list is a draft part (objectstack#30077, objectstack#35955)', () => { it('adding a field writes no view and nothing stored, and the list is handed it as a column', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); expect(listProps.schema.columns).toEqual(['name', 'amount']); expect(listProps.addedFields).toEqual([]); expect(typeof listProps.onAddedFieldsChange).toBe('function'); act(() => listProps.onAddedFieldsChange(['owner'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(draftOf().addedFields).toEqual(['owner']); expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); expect(listProps.addedFields).toEqual(['owner']); }); - it('a field an earlier console stored as added no longer applies', async () => { + it('an added field found in the reader\'s entry does not apply', async () => { const ds = makeDataSource(); - const { family } = makeFamily({ [LIST_KEY]: { perView: { [SYSTEM_ID]: { addedFields: ['owner'] } } } }); - mountWithFamily(ds, family); + makeLayout({ perView: { [SYSTEM_ID]: { addedFields: ['owner'] } } }); + mount(ds); await listReady(); expect(listProps.schema.columns).toEqual(['name', 'amount']); @@ -950,8 +915,8 @@ describe('a field the reader adds to their list is a draft part (objectstack#300 it('Discard drops the added field: the addition alone draws Discard and Save, and the list opens on the view\'s columns', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => listProps.onAddedFieldsChange(['owner'])); expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); @@ -959,10 +924,10 @@ describe('a field the reader adds to their list is a draft part (objectstack#300 // Nothing reported by the list: the addition is a part of its own. expect(screen.getByTestId('list-draft')).toBeTruthy(); await discard(); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(listProps.schema.columns).toEqual(['name', 'amount']); expect(listProps.addedFields).toEqual([]); expect(screen.queryByTestId('list-draft')).toBeNull(); @@ -970,8 +935,8 @@ describe('a field the reader adds to their list is a draft part (objectstack#300 it('a name the view declares itself is the view\'s column, not an addition: no duplicate, nothing handed as added', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => listProps.onAddedFieldsChange(['amount', 'owner'])); @@ -981,79 +946,90 @@ describe('a field the reader adds to their list is a draft part (objectstack#300 it('on a saved view that declares `columns` the addition applies the same way', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); - mountWithFamily(ds, family, SAVED_ID); + const layout = makeLayout(); + mount(ds, SAVED_ID); await listReady(); expect(listProps.schema.columns).toEqual(['name']); act(() => listProps.onAddedFieldsChange(['amount'])); - await wait(700); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); expect(listProps.schema.columns).toEqual(['name', 'amount']); }); }); -describe('CONTROL — no provider: a sort is the draft\'s here too (objectui#12418, objectstack#35955)', () => { - function mountBare(ds: ConsoleObjectViewProps['dataSource'], viewId = SYSTEM_ID) { - return render(page(ds, viewId)); - } - - it('a sort writes no view and nothing in this browser\'s storage, and the list mounted again opens on it', async () => { +describe('what an earlier Console kept is removed and never read (objectstack#35955)', () => { + it('a sort writes no view and nothing in this browser\'s storage, and the list mounted again opens on it (the draft)', async () => { const ds = makeDataSource(); - mountBare(ds); + const layout = makeLayout(); + mount(ds); await listReady(); act(() => listProps.onSortChange([{ id: 'row-1', field: 'amount', order: 'desc' }])); - await wait(400); + await wait(50); expect(viewWrites(ds)).toBe(0); - expect(localStorage.getItem(localListStateKey('u1', OBJECT_NAME))).toBeNull(); + expect(layout.writes).toEqual([]); + expect(Object.keys(localStorage).filter((k) => k.includes(OBJECT_NAME))).toEqual([]); cleanup(); listProps = null; - mountBare(makeDataSource()); + mount(makeDataSource()); await listReady(); expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'desc' }]); }); - it('the older `viewOrder:` key still orders the tabs; the Filter panel\'s older per-browser group no longer applies', async () => { - localStorage.setItem(`viewOrder:${OBJECT_NAME}`, JSON.stringify([SAVED_ID, SYSTEM_ID])); + it('the `ui.list.` row\'s cache, the Filter panel\'s group and the bare `viewOrder:` are removed, and none applies', async () => { const filters = { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'Acme' }] }; + localStorage.setItem(`list-state:u1:${OBJECT_NAME}`, JSON.stringify({ + viewOrder: [SAVED_ID, SYSTEM_ID], + perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }], filters, columnState: { widths: { name: 280 } }, rowHeight: 'compact' } }, + })); localStorage.setItem(`list-filters:u1:${OBJECT_NAME}:${SYSTEM_ID}`, JSON.stringify({ filters, search: 'acme' })); + localStorage.setItem(`viewOrder:${OBJECT_NAME}`, JSON.stringify([SAVED_ID, SYSTEM_ID])); + const layout = makeLayout(); - mountBare(makeDataSource()); + mount(makeDataSource()); await listReady(); - expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); + expect(localStorage.getItem(`list-state:u1:${OBJECT_NAME}`)).toBeNull(); + expect(localStorage.getItem(`list-filters:u1:${OBJECT_NAME}:${SYSTEM_ID}`)).toBeNull(); + expect(localStorage.getItem(`viewOrder:${OBJECT_NAME}`)).toBeNull(); + // Nothing they held is carried over: the list opens on its view's own. + expect(layout.writes).toEqual([]); + expect(manageViewsOrder).toEqual([SYSTEM_ID, SAVED_ID]); + expect(listProps.schema.columnState).toEqual({}); + expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); + expect(listProps.schema.sort).toEqual(AUTHORED_SORT); expect(listProps.initialFilters).toBeUndefined(); expect(listProps.initialSearchTerm ?? '').toBe(''); }); - it('a drag writes no view and keeps the order in this browser', async () => { + it('a drag after the sweep keeps the order under the reader\'s layout entry', async () => { + localStorage.setItem(`viewOrder:${OBJECT_NAME}`, JSON.stringify([SYSTEM_ID, SAVED_ID])); const ds = makeDataSource(); - mountBare(ds); + mount(ds); await listReady(); await act(async () => { fireEvent.click(screen.getByTestId('stub-reorder')); }); - await wait(100); + await wait(50); expect(viewWrites(ds)).toBe(0); expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); - expect(JSON.parse(localStorage.getItem(localListStateKey('u1', OBJECT_NAME)) ?? '{}')).toEqual({ - viewOrder: [SAVED_ID, SYSTEM_ID], - }); + expect(JSON.parse(localStorage.getItem(layoutKey()!) ?? '{}')).toEqual({ viewOrder: [SAVED_ID, SYSTEM_ID] }); + expect(localStorage.getItem(`viewOrder:${OBJECT_NAME}`)).toBeNull(); }); }); -describe('a width change writes the reader\'s row only when it changes it (objectstack#32627)', () => { - const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { columnState: { widths: { name: 280 } } } } } }; +describe('a width change writes the reader\'s layout only when it changes it (objectstack#32627)', () => { + const STORED = { perView: { [SYSTEM_ID]: { widths: { name: 280 } } } }; it('re-stating the stored widths, a sort, and clearing filters nobody set, sends no write', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => { @@ -1061,39 +1037,38 @@ describe('a width change writes the reader\'s row only when it changes it (objec listProps.onColumnStateChange({ widths: { name: 280 } }); listProps.onFilterChange({ id: 'root', logic: 'and', conditions: [] }); }); - await wait(700); + await wait(50); - expect(family.save).not.toHaveBeenCalled(); + expect(layout.writes).toEqual([]); }); - it('a width change undone before the write leaves sends no write', async () => { + it('re-stating a width just written sends no second write', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => listProps.onColumnStateChange({ widths: { name: 400 } })); - act(() => listProps.onColumnStateChange({ widths: { name: 280 } })); - await wait(700); + act(() => listProps.onColumnStateChange({ widths: { name: 400 } })); + await wait(50); - expect(family.save).not.toHaveBeenCalled(); - expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { widths: { name: 400 } } } }]); + expect(listProps.schema.columnState).toEqual({ widths: { name: 400 } }); }); - it('CONTROL: a width that differs from the stored one is one write, and undoing it after it landed is another', async () => { + it('CONTROL: a width that differs from the kept one is one write, and undoing it is another', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const layout = makeLayout(STORED); + mount(ds); await listReady(); act(() => listProps.onColumnStateChange({ widths: { name: 400 } })); - await wait(700); - expect(family.save).toHaveBeenCalledTimes(1); - expect((family.save.mock.calls[0][1] as any).perView[SYSTEM_ID].columnState).toEqual({ widths: { name: 400 } }); + await wait(50); + expect(layout.writes).toEqual([{ perView: { [SYSTEM_ID]: { widths: { name: 400 } } } }]); act(() => listProps.onColumnStateChange({ widths: { name: 280 } })); - await wait(700); - expect(family.save).toHaveBeenCalledTimes(2); - expect((family.save.mock.calls[1][1] as any).perView[SYSTEM_ID].columnState).toEqual({ widths: { name: 280 } }); + await wait(50); + expect(layout.writes).toHaveLength(2); + expect(layout.writes[1]).toEqual({ perView: { [SYSTEM_ID]: { widths: { name: 280 } } } }); }); }); diff --git a/ui/packages/app-shell/src/views/listLayoutStore.slot-35955.test.tsx b/ui/packages/app-shell/src/views/listLayoutStore.slot-35955.test.tsx new file mode 100644 index 00000000000..4c7f074b106 --- /dev/null +++ b/ui/packages/app-shell/src/views/listLayoutStore.slot-35955.test.tsx @@ -0,0 +1,170 @@ +/** + * objectstack#35955 — the list LAYOUT is this browser's alone: the tab order, + * and per view the column widths and the row height. + * + * - A stored value keeps only what the entry declares, well formed: a + * malformed piece, and any part an earlier Console kept (a sort, filters, + * a column order, hidden or added columns), is dropped. + * - A patch sets a part beside the others; `null` clears only its own part, + * and a view left with nothing is removed. + * - The hook writes localStorage and nothing else: no request leaves the + * page, and every reader of the same object sees the write at once. + * - The entry is the signed-in reader's: with nobody signed in there is no + * key, and nothing is read or written. + * - The keys an earlier Console wrote list state under are removed once, + * and never read: their values are not carried over. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import { + clearRetiredListStateKeys, + listLayoutStorageKey, + patchViewLayout, + readListLayout, + resetListLayoutStoreForTests, + sanitizeObjectListLayout, + setViewOrderLayout, + useObjectListLayout, + writeListLayout, +} from './listLayoutStore'; + +const { session } = vi.hoisted(() => ({ session: { userId: 'u1' as string | null } })); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: session.userId ? { id: session.userId, name: 'Ada' } : null, activeOrganization: null }), +})); + +beforeEach(() => { + session.userId = 'u1'; + localStorage.clear(); + resetListLayoutStoreForTests(); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the entry keeps only what it declares (objectstack#35955)', () => { + it('keeps widths, a spec row height and the tab order; drops malformed pieces and every retired part', () => { + expect(sanitizeObjectListLayout({ + viewOrder: ['a', 2, '', 'b'], + perView: { + v1: { widths: { name: 200, bad: 'wide', zero: 0 }, rowHeight: 'compact', sort: [{ field: 'name', order: 'desc' }] }, + v2: { rowHeight: 'enormous', filters: { conditions: [{ field: 'x' }] }, hiddenFields: ['x'] }, + v3: 'not an object', + v4: { columnState: { order: ['name'], widths: { name: 120 } } }, + }, + unknown: true, + })).toEqual({ + viewOrder: ['a', 'b'], + perView: { v1: { widths: { name: 200 }, rowHeight: 'compact' } }, + }); + }); + + it('answers `{}` for anything that is not an object', () => { + expect(sanitizeObjectListLayout(null)).toEqual({}); + expect(sanitizeObjectListLayout([1, 2])).toEqual({}); + expect(sanitizeObjectListLayout('x')).toEqual({}); + }); +}); + +describe('a view\'s patch (objectstack#35955)', () => { + it('sets each part beside the other, and `null` clears only its own part', () => { + let state = patchViewLayout({}, 'v1', { widths: { name: 180 } }); + state = patchViewLayout(state, 'v1', { rowHeight: 'tall' }); + expect(state).toEqual({ perView: { v1: { widths: { name: 180 }, rowHeight: 'tall' } } }); + state = patchViewLayout(state, 'v1', { rowHeight: null }); + expect(state).toEqual({ perView: { v1: { widths: { name: 180 } } } }); + }); + + it('drops a view left with nothing, and an empty width map clears the widths', () => { + const state = patchViewLayout({ viewOrder: ['v1'], perView: { v1: { widths: { name: 180 } } } }, 'v1', { widths: {} }); + expect(state).toEqual({ viewOrder: ['v1'] }); + }); + + it('sets the tab order, and an empty list clears it', () => { + const state = setViewOrderLayout({}, ['b', 'a']); + expect(state).toEqual({ viewOrder: ['b', 'a'] }); + expect(setViewOrderLayout(state, [])).toEqual({}); + }); +}); + +describe('the hook keeps the layout in this browser only (objectstack#35955)', () => { + it('a width, a row height and a tab order are written to localStorage, per user and object, and send no request', () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + const { result } = renderHook(() => useObjectListLayout('account')); + act(() => result.current.patchView('account.all', { widths: { name: 240 } })); + act(() => result.current.patchView('account.all', { rowHeight: 'short' })); + act(() => result.current.setViewOrder(['account.mine', 'account.all'])); + + expect(result.current.layout).toEqual({ + viewOrder: ['account.mine', 'account.all'], + perView: { 'account.all': { widths: { name: 240 }, rowHeight: 'short' } }, + }); + expect(JSON.parse(localStorage.getItem('list-layout:u1:account')!)).toEqual(result.current.layout); + expect(listLayoutStorageKey('u1', 'account')).toBe('list-layout:u1:account'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('every reader of the same object sees a write at once; another object is untouched', () => { + const a = renderHook(() => useObjectListLayout('account')); + const b = renderHook(() => useObjectListLayout('account')); + const other = renderHook(() => useObjectListLayout('contact')); + act(() => a.result.current.patchView('account.all', { widths: { name: 300 } })); + expect(b.result.current.layout).toEqual({ perView: { 'account.all': { widths: { name: 300 } } } }); + expect(other.result.current.layout).toEqual({}); + }); + + it('clearing the last part removes the entry', () => { + const { result } = renderHook(() => useObjectListLayout('account')); + act(() => result.current.patchView('account.all', { rowHeight: 'tall' })); + act(() => result.current.patchView('account.all', { rowHeight: null })); + expect(localStorage.getItem('list-layout:u1:account')).toBeNull(); + expect(result.current.layout).toEqual({}); + }); + + it('with nobody signed in there is no entry: the layout is `{}` and a change writes nothing', () => { + session.userId = null; + expect(listLayoutStorageKey(null, 'account')).toBeNull(); + expect(listLayoutStorageKey('u1', '')).toBeNull(); + const { result } = renderHook(() => useObjectListLayout('account')); + act(() => result.current.patchView('account.all', { widths: { name: 240 } })); + act(() => result.current.setViewOrder(['account.mine'])); + expect(result.current.layout).toEqual({}); + expect(Object.keys(localStorage).filter((k) => k.startsWith('list-layout'))).toEqual([]); + writeListLayout(undefined, 'account', { viewOrder: ['account.mine'] }); + expect(Object.keys(localStorage).filter((k) => k.startsWith('list-layout'))).toEqual([]); + }); + + it('reads and writes outside the hook through the same key', () => { + writeListLayout('u2', 'deal', { viewOrder: ['deal.won'] }); + expect(readListLayout('u2', 'deal')).toEqual({ viewOrder: ['deal.won'] }); + expect(readListLayout('u1', 'deal')).toEqual({}); + }); +}); + +describe('the keys an earlier Console wrote are removed, never read (objectstack#35955)', () => { + const seedRetired = () => { + localStorage.setItem('list-state:u1:account', JSON.stringify({ viewOrder: ['account.mine'], perView: { 'account.all': { columnState: { widths: { name: 400 } }, rowHeight: 'tall' } } })); + localStorage.setItem('list-filters:u1:account:account.all', JSON.stringify({ search: 'acme' })); + localStorage.setItem('viewOrder:account', JSON.stringify(['account.mine'])); + localStorage.setItem('objectui-locale', 'de'); + localStorage.setItem('list-layout:u1:contact', JSON.stringify({ viewOrder: ['contact.all'] })); + }; + + it('the sweep removes every retired key and keeps every other one', () => { + seedRetired(); + clearRetiredListStateKeys(); + expect(Object.keys(localStorage).sort()).toEqual(['list-layout:u1:contact', 'objectui-locale']); + }); + + it('the first hook of the page load sweeps them, and what they held is not carried over', () => { + seedRetired(); + const { result } = renderHook(() => useObjectListLayout('account')); + expect(result.current.layout).toEqual({}); + expect(localStorage.getItem('list-state:u1:account')).toBeNull(); + expect(localStorage.getItem('list-filters:u1:account:account.all')).toBeNull(); + expect(localStorage.getItem('viewOrder:account')).toBeNull(); + expect(localStorage.getItem('objectui-locale')).toBe('de'); + }); +}); diff --git a/ui/packages/app-shell/src/views/listLayoutStore.ts b/ui/packages/app-shell/src/views/listLayoutStore.ts index bb7a23262e9..c9b6ea78e62 100644 --- a/ui/packages/app-shell/src/views/listLayoutStore.ts +++ b/ui/packages/app-shell/src/views/listLayoutStore.ts @@ -13,7 +13,8 @@ * * ## Where it is kept * - * One localStorage entry per reader and object, `list-layout::`: + * One localStorage entry per signed-in reader and object, + * `list-layout::`, holding these three parts and nothing else: * * ```json * { "viewOrder": ["", …], @@ -26,6 +27,9 @@ * held is not carried over, so every list opens on its view's own layout * until the reader changes it again. * + * With no signed-in reader there is no entry: nothing is read or written, and + * the list opens on its view's own layout. + * * A sign-out clears this browser's storage, these entries with it * (`@object-ui/auth`'s signed-out purge). * @@ -66,9 +70,13 @@ export interface ListViewLayoutPatch { /** The localStorage key family this module owns. */ export const LIST_LAYOUT_STORAGE_PREFIX = 'list-layout'; -/** The localStorage key of one reader's layout for one object. */ -export function listLayoutStorageKey(userId: string | null | undefined, objectName: string): string { - return `${LIST_LAYOUT_STORAGE_PREFIX}:${userId || 'anon'}:${objectName}`; +/** + * The localStorage key of one reader's layout for one object; `null` with no + * signed-in reader or no object, which keeps no entry. + */ +export function listLayoutStorageKey(userId: string | null | undefined, objectName: string): string | null { + if (!userId || !objectName) return null; + return `${LIST_LAYOUT_STORAGE_PREFIX}:${userId}:${objectName}`; } /** @@ -206,9 +214,10 @@ function clearRetiredListStateKeysOnce(): void { /** This browser's layout for the reader and object; `{}` when there is none. */ export function readListLayout(userId: string | null | undefined, objectName: string): ObjectListLayout { const store = storage(); - if (!objectName || !store) return {}; + const key = listLayoutStorageKey(userId, objectName); + if (!key || !store) return {}; try { - const raw = store.getItem(listLayoutStorageKey(userId, objectName)); + const raw = store.getItem(key); return raw == null ? {} : sanitizeObjectListLayout(JSON.parse(raw)); } catch { return {}; @@ -221,7 +230,7 @@ const snapshots = new Map void>(); function snapshotOf(key: string): ObjectListLayout { - let raw: string | null = null; + let raw: string | null; try { raw = storage()?.getItem(key) ?? null; } catch { @@ -248,8 +257,8 @@ export function writeListLayout( state: ObjectListLayout, ): void { const store = storage(); - if (!objectName || !store) return; const key = listLayoutStorageKey(userId, objectName); + if (!key || !store) return; try { if (!state.viewOrder && !state.perView) store.removeItem(key); else store.setItem(key, JSON.stringify(state)); @@ -283,7 +292,7 @@ export interface ObjectListLayoutHandle { patchView(viewId: string, patch: ListViewLayoutPatch): void; } -/** The signed-in reader's list layout for one object, in this browser. */ +/** The signed-in reader's list layout for one object, in this browser; `{}` and no writes while nobody is signed in. */ export function useObjectListLayout(objectName: string | undefined): ObjectListLayoutHandle { clearRetiredListStateKeysOnce(); const { user } = useAuth(); @@ -292,13 +301,13 @@ export function useObjectListLayout(objectName: string | undefined): ObjectListL const key = listLayoutStorageKey(userId, name); const layout = useSyncExternalStore( subscribe, - () => (name ? snapshotOf(key) : EMPTY), + () => (key ? snapshotOf(key) : EMPTY), () => EMPTY, ); const update = useCallback( (fn: (prev: ObjectListLayout) => ObjectListLayout) => { - if (!name) return; + if (!listLayoutStorageKey(userId, name)) return; const prev = readListLayout(userId, name); const next = fn(prev); if (JSON.stringify(next) === JSON.stringify(prev)) return; diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx index 640dcfc1f67..0f793025268 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx @@ -47,7 +47,7 @@ function mount() { setViewDraft, setRefreshKey, confirmHandler: vi.fn() as unknown as Args['confirmHandler'], - listPrefs: { setViewOrder: vi.fn() } as unknown as Args['listPrefs'], + listLayout: { setViewOrder: vi.fn() } as unknown as Args['listLayout'], views: [], activeViewId: 'crm_account.team', baseView: { id: 'crm_account.team' } as Args['baseView'], diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 86d94a861cf..9003e73e664 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -437,9 +437,10 @@ export function useObjectViewViewCrud({ * sequence, then a stored `sortOrder` — stays every user's default, and * the view editor is where an author changes it. */ + const setViewOrder = listLayout.setViewOrder; const handleReorderViews = useCallback((orderedIds: string[]) => { - listLayout.setViewOrder(orderedIds); - }, [listLayout.setViewOrder]); + setViewOrder(orderedIds); + }, [setViewOrder]); const handleConfigView = useCallback((vid: string) => { // System (metadata-defined) views are read-only — opening the diff --git a/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts b/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts index acb73843805..68ed1b85a45 100644 --- a/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts +++ b/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts @@ -6,7 +6,7 @@ * * **objectui#4155 (the current contract): the list toolbar's filter panel must * not persist ANYTHING.** Filter-panel state is transient — it belongs to the - * session and to `writeListFilterState`'s per-browser restore, not to the + * session and to the list's draft (objectstack#35955), not to the * view's stored body. It used to write a view-customization overlay on every * `onFilterChange`, so opening the panel and clicking `Add filter` put an * incomplete `field equals ''` condition into `sys_metadata`, where it REPLACED diff --git a/ui/packages/react/src/context/RecordPagePreferencesContext.tsx b/ui/packages/react/src/context/RecordPagePreferencesContext.tsx index 734c3d2828a..008dce1fe50 100644 --- a/ui/packages/react/src/context/RecordPagePreferencesContext.tsx +++ b/ui/packages/react/src/context/RecordPagePreferencesContext.tsx @@ -14,9 +14,8 @@ * Its first choice is "show empty fields": a reader who opens a * section's "Show N empty fields" row wants to see the whole record, and wants * it on every section of the page, on the next record of the same object and - * after a reload. The host keeps that choice where it keeps the user's list - * state, a `sys_user_preference` row per object (the Console's key is - * `ui.record.`, beside `ui.list.`). + * after a reload. The host keeps that choice in a `sys_user_preference` row + * per object (the Console's key is `ui.record.`). * * ## Why a context, and why here * From 9c1b9be41de4e81a4fc2e041106b2f075ace52bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:45:23 +0000 Subject: [PATCH 3/6] refactor(cli): move os migrate list-preferences to its own pull request This pull request keeps the browser side only. The cleanup command follows once it merges. Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- content/docs/deployment/cli.mdx | 38 +- content/docs/upgrading.mdx | 2 - .../list-preferences.integration.test.ts | 240 ----------- .../list-preferences.no-auto-run.test.ts | 82 ---- .../src/commands/migrate/list-preferences.ts | 399 ------------------ ...igrate.one-shot-family.integration.test.ts | 8 - .../cli/test/json-stdout-purity.e2e.test.ts | 4 - .../migrate-confirmation-exit.pin.test.ts | 2 - 8 files changed, 1 insertion(+), 774 deletions(-) delete mode 100644 packages/cli/src/commands/migrate/list-preferences.integration.test.ts delete mode 100644 packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts delete mode 100644 packages/cli/src/commands/migrate/list-preferences.ts diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index fff2df462a4..3a5e2f5979d 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1541,7 +1541,6 @@ where the data lives. | `os migrate record-currency-codes` | Write the currency code you give into the rows of a record-mode currency field that hold an amount and no code, the rows stored before the field was switched to `currencyMode: 'record'`. The code is never derived. No flag; idempotent. See [below](#os-migrate-record-currency-codes) | | `os migrate recompute-home-amounts` | Recompute the home-currency amounts a record-mode currency field stores, at the exchange rates in force now, after a rate is corrected or added. Reports the rows that change and lists, without writing, the rows it cannot convert. No flag; idempotent. See [below](#os-migrate-recompute-home-amounts) | | `os migrate comment-reactions` | Carry the emoji reactions a 17.x deployment stored in the retired `sys_comment.reactions` column into `sys_comment_reaction` records, list every stored value that does not read, and record the verified run that lets `os migrate apply --allow-destructive` drop the column | -| `os migrate list-preferences` | Remove the per-user list preference rows (`sys_user_preference` keys starting with `ui.list.`) that the Console no longer reads. Dry run by default; `--apply` deletes only with `--export`, which writes every row it deletes to a file first. No flag. See [below](#os-migrate-list-preferences) | | `os migrate organization-ownership` | The v18 ownership ceremony (ADR-0131 D10): write a plan of what each table's rows will become, then `--apply` that reviewed plan. It upgrades a database 17.x or an 18.0 pre-release (`18.0.0-next.*`) created; a v18 server refuses to start on one until it has run. See [below](#os-migrate-organization-ownership) | | `os migrate activity-changed-fields` | Stamp the two read-rule columns (`changed_fields`, `milestone_key`) on the `sys_activity` rows written before they existed. Until it runs, those rows are withheld from every reader but the system, so run it at once after upgrading. No flag; idempotent | | `os migrate audit-mail-bodies` | Mask the mail bodies (`body_text`, `body_html`) that `sys_audit_log` and `sys_activity` copies of `sys_email` / `sys_identity_email` rows still hold in clear, written before the audit writer masked them. Covers the `archive` datasource `sys_audit_log` archives to as well. Reports counts only. No flag; idempotent. See [below](#os-migrate-audit-mail-bodies) | @@ -1566,7 +1565,7 @@ A read-only data command does not read a table it found missing, since that tabl holds nothing, and answers with empty work and exit 0. `os migrate value-shapes` is clean over zero records and names the objects it did not read. `os migrate recorded-by` has nothing to convert and `os migrate resume` no interrupted runs. -`os migrate meta --stored` has no stored metadata to examine, `os migrate list-preferences` no preference row to report, `os migrate +`os migrate meta --stored` has no stored metadata to examine, `os migrate audit-metadata-bodies`, `os migrate audit-mail-bodies`, `os migrate audit-key-material` and `os migrate audit-side-copies` no audit copy to rewrite, and `os migrate account-issuer` no account to collide. `os secret orphans`, `os secret rewrap` and `os storage orphans` report no secret and no file. A read the command cannot avoid and that fails for any @@ -2064,41 +2063,6 @@ A run that lists an unreadable value or fails a write exits `1`, and so does an A database created on v18 never had the column: the run finds nothing, and there is no drop to wait for. -#### `os migrate list-preferences` - -The Console used to keep one `sys_user_preference` row per user and object, keyed -`ui.list.`, holding that user's state for the object's lists: the order of -the view tabs and, per view, a sort, filters, a column layout, a row height and -hidden or added columns. It keeps none of that on the server any more. A change a -reader makes on a list is a draft that they save into a view or discard, and the -column widths, the row height and the tab order are kept in the reader's own -browser. Nothing reads the old rows, so leaving them does no harm. This command -removes them. What they held is not carried over: every list opens on its view's -own layout until the reader changes it again. - -```bash -os migrate list-preferences # Dry run: how many rows, for how many users and which objects -os migrate list-preferences --apply --export ./list-preferences-backup.json -os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json # CI / scripts -``` - -**Options:** -- `--apply` — delete the listed rows (default off: a read-only dry run that writes nothing) -- `--export ` — **mandatory with `--apply`**: every row the run deletes, as stored, written - owner-only and read back before the first delete; refuses to overwrite an existing file -- `-y, --yes` — skip the confirmation prompt -- `--force` — apply even when another process is using the SQLite file -- `--database-url `, `--json` - -Only keys that start with `ui.list.` are touched. Every other preference row, -`ui.record.` included, stays as it is. The rows are deleted by id, the ones -the export holds and no others, and none of them enters the recycle bin. The run then -reads the prefix again. If a row remains, or was written since by a Console that has -not been upgraded, it is reported and the run exits `1`; run it again once every -Console is upgraded. A run that finds nothing writes no export and exits `0`. It is -never run for you: nothing on any boot, upgrade, migrate or lifecycle path invokes it, -and it records no `sys_migration` verdict, because nothing waits for one. - #### `os migrate activity-changed-fields` An activity row is served to a reader only when the platform can judge it for diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index 035474a49cf..5f48d0b1765 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -493,8 +493,6 @@ the protocol-18 step, which `os migrate meta --from 17` lists for your sources **Upgrading from 18.5.0 or earlier:** the first [`os migrate plan`](/docs/deployment/cli#schema-migrations) after the move lists a safe `create_index` for each `(created_at, id)` and `(owner_id)` index schema sync now builds without a declaration, and on SQLite a `normalize_boolean_storage` step for boolean cells stored as text; the next sync or `os migrate apply` builds them, and neither is destructive. Where an app declares `lifecycle.seal`, an `os migrate audit-* --apply` run on SQLite or Turso now needs every sealing server stopped and `--sealer-stopped` ([18.6.0 checklist](/docs/releases/v18/18-6#upgrade-checklist)). -**Upgrading from 18.6.0 or earlier:** the Console no longer reads the per-user list preference rows (`sys_user_preference` keys `ui.list.`). A reader's column widths, row height and view tab order are kept in their own browser from now on, so each list opens on its view's own layout until the reader changes it again. To clear the old rows, run [`os migrate list-preferences`](/docs/deployment/cli#os-migrate-list-preferences) once all your Consoles are upgraded, a dry run first and then `--apply --export `. Leaving them does no harm: nothing reads them. - The v17 and v18 lines are broken out per release. Each v17 minor shipped breaking changes under the repo's launch-window convention — which ships a breaking change as `minor` rather than `major`, so the version number is not the diff --git a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts deleted file mode 100644 index 22fcd357c30..00000000000 --- a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import Database from 'better-sqlite3'; -import { isExitSignal } from '../../utils/format.js'; -import MigrateApply from './apply.js'; -import MigrateListPreferences from './list-preferences.js'; - -// Pay the first transform of the dist-resolved workspace deps the commands -// reach through dynamic `import()`s at MODULE LOAD, not inside a case. -import '@objectstack/runtime'; -import '@objectstack/objectql'; -import '@objectstack/plugin-auth'; -import '@objectstack/plugin-security'; -import '@objectstack/plugin-audit'; - -/** - * `os migrate list-preferences` against a real SQLite database: the step that - * removes the `sys_user_preference` rows keyed `ui.list.`, which no - * Console reads any more (objectstack#35955). - * - * ## The database - * - * The schema this version creates (`os migrate apply --yes` over an empty - * file, the composition `os serve` mounts with an auth secret, so the auth - * family's `sys_user_preference` is among it), with the rows an earlier Console left: three `ui.list.*` rows for two - * users, and two CONTROLS that are never touched — another family's row - * (`ui.record.account`) and a key that only looks alike (`ui.lists`). - * - * ## The cases run in order over ONE database, as an operator runs the steps - * - * 1. a dry run reports the rows and deletes nothing; - * 2. `--apply` without `--export` is refused, and so is an export path that - * already exists — both with nothing deleted; - * 3. `--apply --export` writes the export (owner-only, every row as stored), - * deletes exactly the `ui.list.*` rows, and keeps the controls; - * 4. a re-run finds nothing and writes no export. - */ - -const HERE = dirname(fileURLToPath(import.meta.url)); -const CLI_ROOT = resolve(HERE, '..', '..', '..'); -const CASE_TIMEOUT_MS = 240_000; -const SECRET = 'os35955-integration-secret-at-least-32-chars'; - -const RETIRED = [ - { id: 'pref_l1', user_id: 'u1', key: 'ui.list.account', value: '{"viewOrder":["account.all"]}' }, - { id: 'pref_l2', user_id: 'u1', key: 'ui.list.contact', value: '{"perView":{"contact.all":{"rowHeight":"compact"}}}' }, - { id: 'pref_l3', user_id: 'u2', key: 'ui.list.account', value: '{"perView":{"account.all":{"sort":[{"field":"name","order":"desc"}]}}}' }, -]; -const CONTROLS = [ - { id: 'pref_r1', user_id: 'u1', key: 'ui.record.account', value: '{"showEmptyFields":true}' }, - { id: 'pref_x1', user_id: 'u2', key: 'ui.lists', value: '{}' }, -]; - -type Invoke = (argv: string[]) => Promise; -const invoke = (command: { run: (argv: string[], opts: { root: string }) => Promise }): Invoke => - (argv) => command.run(argv, { root: CLI_ROOT }); - -/** Env that would point a command's boot somewhere other than the fixture. */ -const OVERRIDING_ENV = [ - 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', - 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ARTIFACT_PATH', -] as const; - -/** Run one command and capture its JSON document and exit status. */ -async function runJson(command: Invoke, argv: string[]): Promise<{ payload: any; exitCode: number }> { - const savedExit = process.exitCode; - const swallow = ((_chunk: unknown, ...rest: unknown[]) => { - const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; - if (cb) cb(); - return true; - }) as typeof process.stdout.write; - const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); - vi.spyOn(process.stderr, 'write').mockImplementation(swallow); - vi.spyOn(console, 'log').mockImplementation(() => {}); - vi.spyOn(console, 'warn').mockImplementation(() => {}); - vi.spyOn(console, 'error').mockImplementation(() => {}); - let processExit: number | undefined; - vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { - processExit = code ?? 0; - throw new Error(`__PROCESS_EXIT__:${processExit}`); - }) as never); - let thrownExit: number | undefined; - try { - try { - await command(argv); - } catch (error) { - const trapped = error instanceof Error && error.message.startsWith('__PROCESS_EXIT__'); - if (!trapped && !isExitSignal(error)) throw error; - if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; - } - const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); - let payload: any; - try { - payload = JSON.parse(out); - } catch { - payload = { unparsed: out.slice(-400) }; - } - return { payload, exitCode: processExit ?? thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; - } finally { - process.exitCode = savedExit; - vi.restoreAllMocks(); - } -} - -let dir: string; -let dbFile: string; -const savedEnv: Record = {}; -const savedCwd = process.cwd(); - -function withDb(fn: (db: Database.Database) => T, readonly = true): T { - const db = new Database(dbFile, { readonly }); - try { - return fn(db); - } finally { - db.close(); - } -} - -/** Insert a row, filling every other NOT NULL column without a default with a placeholder of its type. */ -function plant(db: Database.Database, table: string, values: Record): void { - const columns = db.prepare(`PRAGMA table_info('${table}')`).all() as Array< - { name: string; type: string; notnull: number; dflt_value: unknown; pk: number } - >; - const row: Record = { ...values }; - for (const c of columns) { - if (c.name in row || !c.notnull || c.dflt_value !== null) continue; - row[c.name] = /INT|BOOL|REAL|NUM/i.test(c.type) ? 0 : `${c.name}-placeholder`; - } - const names = Object.keys(row); - db.prepare(`INSERT INTO "${table}" (${names.map((n) => `"${n}"`).join(', ')}) VALUES (${names.map(() => '?').join(', ')})`) - .run(...names.map((n) => row[n] as never)); -} - -const storedIds = (): string[] => - withDb((db) => (db.prepare("SELECT id FROM sys_user_preference WHERE id LIKE 'pref_%' ORDER BY id").all() as - Array<{ id: string }>).map((r) => r.id)); - -beforeAll(async () => { - for (const key of [...OVERRIDING_ENV, 'NODE_ENV'] as const) savedEnv[key] = process.env[key]; - for (const key of OVERRIDING_ENV) delete process.env[key]; - dir = mkdtempSync(join(tmpdir(), 'os-35955-list-prefs-')); - mkdirSync(join(dir, 'dist'), { recursive: true }); - writeFileSync( - join(dir, 'objectstack.config.ts'), - [ - 'export default {', - " manifest: { id: 'com.example.os35955listprefs', name: 'list prefs', version: '0.0.0', type: 'app' },", - " requires: ['auth'],", - " objects: [{ name: 'os35955_thing', fields: { title: { type: 'text' } } }],", - '};', - '', - ].join('\n'), - ); - process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); - // `os serve` composes the auth family, whose objects hold the preference - // rows, only when an auth secret resolves. - process.env.OS_AUTH_SECRET = SECRET; - process.env.NODE_ENV = 'production'; - process.env.OS_TELEMETRY_DB = '0'; - dbFile = join(dir, 'upgraded.db'); - process.chdir(dir); - try { - const created = await runJson(invoke(MigrateApply), ['--database-url', `file:${dbFile}`, '--yes', '--json']); - expect(created.exitCode, JSON.stringify(created.payload).slice(0, 400)).toBe(0); - } finally { - process.chdir(savedCwd); - } - withDb((db) => { - for (const row of [...RETIRED, ...CONTROLS]) plant(db, 'sys_user_preference', row); - }, false); - expect(storedIds()).toEqual([...RETIRED, ...CONTROLS].map((r) => r.id).sort()); -}, CASE_TIMEOUT_MS); - -afterAll(() => { - process.chdir(savedCwd); - for (const [key, value] of Object.entries(savedEnv)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } -}); - -beforeEach(() => { process.chdir(dir); }); -afterEach(() => { process.chdir(savedCwd); }); - -describe('os migrate list-preferences removes the ui.list.* preference rows (objectstack#35955)', () => { - const db = () => `file:${dbFile}`; - const run = (argv: string[]) => runJson(invoke(MigrateListPreferences), ['--database-url', db(), ...argv, '--json']); - const all = [...RETIRED, ...CONTROLS].map((r) => r.id).sort(); - - it('1. a dry run reports the rows, users and objects, and deletes nothing', async () => { - const { payload, exitCode } = await run([]); - expect(exitCode).toBe(0); - expect(payload).toMatchObject({ apply: false, rows: 3, users: 2, objects: ['account', 'contact'], deleted: 0, remaining: 3 }); - expect(storedIds()).toEqual(all); - }, CASE_TIMEOUT_MS); - - it('2. --apply is refused without --export, and over an existing export, with nothing deleted', async () => { - const bare = await run(['--apply', '--yes']); - expect(bare.exitCode).toBe(1); - expect(bare.payload.error).toBe('export_required'); - - const taken = join(dir, 'taken.json'); - writeFileSync(taken, 'keep me\n'); - const over = await run(['--apply', '--yes', '--export', taken]); - expect(over.exitCode).toBe(1); - expect(over.payload.error).toBe('export_exists'); - expect(readFileSync(taken, 'utf8')).toBe('keep me\n'); - expect(storedIds()).toEqual(all); - }, CASE_TIMEOUT_MS); - - it('3. --apply --export writes every retired row to an owner-only export, then deletes exactly those rows', async () => { - const exportPath = join(dir, 'list-preferences-export.json'); - const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); - expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0); - expect(payload).toMatchObject({ apply: true, rows: 3, users: 2, deleted: 3, remaining: 0, failures: [] }); - - const doc = JSON.parse(readFileSync(exportPath, 'utf8')); - expect(doc.keyPrefix).toBe('ui.list.'); - expect(doc.rows.map((r: { id: string }) => r.id).sort()).toEqual(RETIRED.map((r) => r.id)); - expect(doc.rows.find((r: { id: string }) => r.id === 'pref_l3')).toMatchObject({ user_id: 'u2', key: 'ui.list.account' }); - if (process.platform !== 'win32') expect(statSync(exportPath).mode & 0o077).toBe(0); - - expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); - }, CASE_TIMEOUT_MS); - - it('4. a re-run finds nothing, writes no export, and keeps the controls', async () => { - const exportPath = join(dir, 'second-export.json'); - const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); - expect(exitCode).toBe(0); - expect(payload).toMatchObject({ rows: 0, deleted: 0, remaining: 0 }); - expect(existsSync(exportPath)).toBe(false); - expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); - }, CASE_TIMEOUT_MS); -}); diff --git a/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts b/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts deleted file mode 100644 index 4ec27eea355..00000000000 --- a/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Nothing runs `os migrate list-preferences` for you: it deletes stored rows, - * so it stays an operator's command, and no boot, upgrade, migrate or - * lifecycle path may import it. - * - * Every absence below is preceded by the SAME scanner finding a call site that - * really exists (a dynamic import on the boot path), so an empty answer is - * not a broken scanner. The shape is `../db/orphans.no-auto-run.test.ts`'s. - */ - -import { describe, it, expect } from 'vitest'; -import { readFileSync, readdirSync, statSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -/** `packages/cli/src` — this package only; the scan never leaves it. */ -const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url)); - -function everyTsFile(dir: string, out: string[] = []): string[] { - for (const entry of readdirSync(dir)) { - const full = join(dir, entry); - if (statSync(full).isDirectory()) everyTsFile(full, out); - else if (entry.endsWith('.ts')) out.push(full); - } - return out; -} - -const ALL_FILES = everyTsFile(SRC_ROOT); -const relative = (file: string) => file.slice(SRC_ROOT.length).replaceAll('\\', '/'); -const isTestFile = (path: string) => /\.test\.ts$/.test(path); - -/** A static `from '…'` or a dynamic `import('…')` specifier. */ -const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g; - -/** Files whose relative import RESOLVES to `target` (a path under `src/`), whatever the specifier's spelling. */ -function importersOf(target: string): string[] { - const wanted = join(SRC_ROOT, target); - return ALL_FILES.filter((file) => { - for (const m of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) { - const spec = m[1]!; - if (!spec.startsWith('.')) continue; - if (resolve(dirname(file), spec).replace(/\.js$/, '.ts') === wanted) return true; - } - return false; - }).map(relative); -} - -const COMMAND = 'commands/migrate/list-preferences.ts'; -/** The one-shot boot family's enumeration pin RUNS every bootSchemaStack caller's modes; a test, never a boot path. */ -const FAMILY_PIN = 'utils/schema-migrate.one-shot-family.integration.test.ts'; - -describe('the scanner works (positive controls)', () => { - it('finds the CLI’s own boot path reaching the kernel:ready migration gate — a DYNAMIC import', () => { - expect(importersOf('utils/artifact-boot-migration.ts').filter((p) => !isTestFile(p))).toContain('commands/serve.ts'); - }); - - it('finds the family pin importing this command', () => { - expect(importersOf(COMMAND)).toContain(FAMILY_PIN); - }); - - it('the file population itself is real', () => { - expect(ALL_FILES.length).toBeGreaterThan(100); - expect(ALL_FILES.map(relative)).toContain(COMMAND); - }); -}); - -describe('nothing on a boot, upgrade, migrate or lifecycle path invokes os migrate list-preferences', () => { - it('no source file imports the command — its own tests and the family pin are the only readers', () => { - const importers = importersOf(COMMAND); - expect(importers.filter((p) => !isTestFile(p))).toEqual([]); - expect( - importers.every((p) => p.startsWith('commands/migrate/list-preferences.') || p === FAMILY_PIN), - importers.join(', '), - ).toBe(true); - }); - - it('the CLI barrel does not export it', () => { - expect(readFileSync(join(SRC_ROOT, 'index.ts'), 'utf8')).not.toContain('list-preferences'); - }); -}); diff --git a/packages/cli/src/commands/migrate/list-preferences.ts b/packages/cli/src/commands/migrate/list-preferences.ts deleted file mode 100644 index 92876fc5745..00000000000 --- a/packages/cli/src/commands/migrate/list-preferences.ts +++ /dev/null @@ -1,399 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import { Command, Flags } from '@oclif/core'; -import chalk from 'chalk'; -import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { createInterface } from 'node:readline'; -import { resolve as resolvePath } from 'node:path'; -import type { IObjectQLEngine } from '@objectstack/spec/contracts'; -import { - printHeader, - printSuccess, - printWarning, - printError, - printInfo, - printStep, - createTimer, - emitJson, - isExitSignal, - errorCodeFields, -} from '../../utils/format.js'; -import { bootSchemaStack } from '../../utils/schema-migrate.js'; -import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; -import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; -import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; -import { absentTableReads } from '../../utils/absent-table-reads.js'; - -async function confirm(question: string): Promise { - if (!process.stdin.isTTY) return false; // non-interactive → require --yes - const rl = createInterface({ input: process.stdin, output: process.stdout }); - try { - const answer: string = await new Promise((resolve) => rl.question(question, resolve)); - return /^y(es)?$/i.test(answer.trim()); - } finally { - rl.close(); - } -} - -/** The object the retired rows are stored in. */ -export const USER_PREFERENCE_OBJECT = 'sys_user_preference'; - -/** - * The key prefix of the retired rows: one per user and object, written by - * Consoles before the list layout moved to the browser. - */ -export const RETIRED_LIST_PREFERENCE_PREFIX = 'ui.list.'; - -const SYSTEM = { isSystem: true } as const; -const PAGE_SIZE = 500; - -/** One retired row, as stored. */ -export interface RetiredListPreferenceRow { - id: string; - user_id: unknown; - key: string; - value: unknown; - [column: string]: unknown; -} - -/** The pre-delete export: every row the run deletes, as stored. */ -export interface RetiredListPreferenceExport { - producedBy: string; - object: typeof USER_PREFERENCE_OBJECT; - keyPrefix: typeof RETIRED_LIST_PREFERENCE_PREFIX; - rows: RetiredListPreferenceRow[]; -} - -type ReadEngine = Pick; - -/** - * Every stored `ui.list.*` row, walked in id order a page at a time, so a row - * written mid-walk cannot shift another out of the walk. - */ -export async function listRetiredListPreferenceRows( - engine: ReadEngine, - read: (run: () => Promise) => Promise = (run) => run(), -): Promise { - const out: RetiredListPreferenceRow[] = []; - let after: string | undefined; - for (;;) { - const page = await read(async () => (await engine.find(USER_PREFERENCE_OBJECT, { - where: { - key: { $startsWith: RETIRED_LIST_PREFERENCE_PREFIX }, - ...(after !== undefined ? { id: { $gt: after } } : {}), - }, - orderBy: [{ field: 'id', order: 'asc' }], - limit: PAGE_SIZE, - context: { ...SYSTEM }, - } as never)) as RetiredListPreferenceRow[]); - for (const row of page) { - if (row && typeof row.key === 'string' && row.key.startsWith(RETIRED_LIST_PREFERENCE_PREFIX)) out.push(row); - } - if (page.length < PAGE_SIZE) break; - after = String(page[page.length - 1].id); - } - return out; -} - -/** What a dry run reports, and what `--apply` deletes. */ -export interface RetiredListPreferenceSummary { - rows: number; - users: number; - objects: string[]; -} - -export function summarizeRetiredListPreferences(rows: readonly RetiredListPreferenceRow[]): RetiredListPreferenceSummary { - const users = new Set(rows.map((row) => String(row.user_id))); - const objects = new Set(rows.map((row) => row.key.slice(RETIRED_LIST_PREFERENCE_PREFIX.length))); - return { rows: rows.length, users: users.size, objects: [...objects].sort() }; -} - -/** - * `os migrate list-preferences` — remove the per-user list preference rows a - * Console no longer reads: every `sys_user_preference` row whose key starts - * with `ui.list.` (objectstack#35955). - * - * Such a row held one user's state for one object's lists — the view tab - * order, and per view a sort, filters, a column layout, a row height, hidden - * and added columns. The Console keeps none of that on the server any more: - * a change on a list is a draft, and the column widths, the row height and - * the tab order are kept in the reader's browser. Nothing reads these rows, - * so leaving them is harmless; this step clears them, as the upgrade notes - * ask. What they held is not carried anywhere: every reader's lists open on - * their views' own layout. - * - * ## The family's conventions, and the delete's own - * - * - Dry run by default: it boots read-only and reports how many rows, for how - * many users and which objects. It writes nothing. - * - `--apply` deletes, and only with `--export `: every row it deletes - * is first written to that file as stored (owner-only, never over an - * existing file) and read back. A failed or incomplete export refuses the - * run with nothing deleted. The export is the only copy that survives. - * - Only the exported rows are deleted, by id, under the system context, and - * none of them enters the recycle bin. The step then reads the prefix again: - * a row left (or written since) is reported and the run exits non-zero; a - * re-run finishes it. - * - Confirmed with `[y/N]` or `--yes`; `--force` past a busy SQLite file; - * `--json` for one document; `--database-url` / `$OS_DATABASE_URL`. - * - ⛔ Nothing on any boot, upgrade or lifecycle path runs it - * (`list-preferences.no-auto-run.test.ts`). No `sys_migration` verdict is - * recorded: nothing reads one. - * - * Exit status: 0 when nothing is stored, when a dry run lists rows (they are - * inert), or when every listed row was deleted; 1 when a delete failed, a row - * remains, the export could not be written, or the database could not be read. - */ -export default class MigrateListPreferences extends Command { - // The tracker id stays in the comment above: a command description reaches - // operators, who have no tracker to resolve it against. - static override description = - 'Remove the per-user list preference rows (sys_user_preference keys starting with "ui.list.") that the Console ' - + 'no longer reads. Dry run by default; --apply --export writes every row it deletes to the file first, ' - + 'then deletes them.'; - - static override examples = [ - '$ os migrate list-preferences', - '$ os migrate list-preferences --json', - '$ os migrate list-preferences --apply --export ./list-preferences-backup.json', - '$ os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json', - ]; - - static override flags = { - 'database-url': Flags.string({ - description: 'Database URL to migrate (defaults to $OS_DATABASE_URL / the project DB)', - env: 'OS_DATABASE_URL', - }), - apply: Flags.boolean({ - description: 'Delete the listed rows (default is a read-only dry run). Requires --export.', - default: false, - }), - export: Flags.string({ - description: 'Path for the MANDATORY pre-delete export: every row --apply deletes, as stored, written owner-only ' - + 'and read back before the first delete. Must not exist yet.', - }), - yes: Flags.boolean({ char: 'y', description: 'Skip the --apply confirmation prompt', default: false }), - force: Flags.boolean({ - description: 'Apply even when another process is using the database (SQLite occupancy check)', - default: false, - }), - json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), - }; - - async run(): Promise { - const { flags } = await this.parse(MigrateListPreferences); - const timer = createTimer(); - const apply = flags.apply; - const json = flags.json === true; - - if (!json) printHeader('Migrate · list-preferences'); - - const refuse = async (error: string, message: string, extra: object = {}): Promise => { - if (json) await emitJson({ error, message, ...extra }, 0, { compact: true }); - else printError(message); - this.exit(1); - }; - - const exportPath = flags.export ? resolvePath(flags.export) : undefined; - if (apply && !exportPath) { - await refuse( - 'export_required', - 'Refusing to delete without --export . The pre-delete export is mandatory: it is the only copy of ' - + 'the rows this run deletes.', - ); - return; - } - if (apply && exportPath && existsSync(exportPath)) { - await refuse('export_exists', `Refusing to overwrite an existing export at ${exportPath}. Name a new path.`, { - path: exportPath, - }); - return; - } - - const occupancy = await probeMigrationTarget(flags['database-url']); - if (occupancy.status === 'busy' && apply && !flags.force) { - if (json) { - await emitJson( - { error: 'database_busy', database: occupancy.filename, signal: occupancy.signal, detail: occupancy.detail, hint: OCCUPANCY_HINT }, - 0, - { compact: true }, - ); - this.exit(1); - return; - } - printError(describeOccupancy(occupancy)); - printWarning(OCCUPANCY_HINT); - this.exit(1); - return; - } - if (occupancy.status === 'busy' && !json) { - printWarning(apply - ? `--force: ${describeOccupancy(occupancy)} Deleting anyway — an old Console still open may write a row mid-run; a re-run removes it.` - : `${describeOccupancy(occupancy)} The dry run below writes no row or table. ${JOURNAL_MODE_SWITCH_NOTE}`); - } - if (occupancy.status === 'unknown' && !json) { - printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); - } - - if (apply && !flags.yes) { - if (json || !process.stdin.isTTY) { - if (json) { - await emitJson({ error: 'confirmation_required', hint: 'pass --yes' }, 0, { compact: true }); - this.exit(1); - return; - } - printWarning('Apply mode deletes sys_user_preference rows. Re-run with --yes to confirm, or run without --apply to preview.'); - this.exit(1); - return; - } - const ok = await confirm(chalk.bold('\nDelete every "ui.list." preference row on this database, after writing the export? [y/N] ')); - if (!ok) { - printInfo('Aborted — no export was written and no row was deleted.'); - return; - } - } - - if (!json) printStep(apply ? 'Booting data stack (APPLY mode)…' : 'Booting data stack (dry run)…'); - - let stack; - try { - // `sys_user_preference` is plugin-auth's: its identity objects are - // composed for their declarations only (no auth manager, nothing - // started), as `os user set-password` composes them. The dry run boots - // READ-ONLY, the boot `os migrate plan` takes: no schema DDL, no - // artifact seed, no sqlite file brought into existence. - const { createIdentityObjectsPlugin } = await import('@objectstack/plugin-auth'); - stack = await bootSchemaStack({ - jsonOutput: json, - databaseUrl: flags['database-url'], - extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], - ...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), - }); - } catch (error: any) { - await refuse('boot_failed', error?.message ?? String(error), errorCodeFields(error)); - return; - } - - let exitCode = 0; - try { - const engine = stack.kernel.getService('objectql') as IObjectQLEngine | undefined; - if (typeof engine?.find !== 'function' || typeof engine?.delete !== 'function') { - throw new Error(`No ObjectQL engine on this stack — cannot read ${USER_PREFERENCE_OBJECT}.`); - } - // A table the read-only boot measured absent stores no row. - const reads = absentTableReads(stack, (object) => engine.getObject(object)); - const read = (run: () => Promise) => reads.rows(USER_PREFERENCE_OBJECT, run); - - const rows = await listRetiredListPreferenceRows(engine, read); - const summary = summarizeRetiredListPreferences(rows); - - if (!apply || rows.length === 0) { - if (json) { - reads.notice(true); - await emitJson({ database: stack.dbLabel, apply, ...summary, deleted: 0, remaining: summary.rows, duration: timer.elapsed() }); - return; - } - printInfo(`Database: ${chalk.white(stack.dbLabel)}`); - reads.notice(false); - console.log(''); - if (rows.length === 0) { - printSuccess(`No "ui.list." preference row is stored — nothing to remove ${chalk.dim(`(${timer.display()})`)}`); - } else { - console.log(` ${chalk.white(USER_PREFERENCE_OBJECT)}: ${summary.rows} "ui.list." row(s) for ${summary.users} user(s)`); - console.log(` objects: ${summary.objects.join(', ')}`); - console.log(''); - printInfo( - 'Dry run only — nothing reads these rows, so they are harmless where they are. Re-run with ' - + '--apply --export to remove them.', - ); - } - return; - } - - // ── The export, written and READ BACK before anything is deleted ────── - const doc: RetiredListPreferenceExport = { - producedBy: `${this.config.bin} migrate list-preferences --apply`, - object: USER_PREFERENCE_OBJECT, - keyPrefix: RETIRED_LIST_PREFERENCE_PREFIX, - rows, - }; - let exported: Set; - try { - writeFileSync(exportPath!, `${JSON.stringify(doc, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); - const back = JSON.parse(readFileSync(exportPath!, 'utf8')) as RetiredListPreferenceExport; - exported = new Set((back.rows ?? []).map((row) => String(row.id))); - } catch (error) { - exitCode = 1; - const message = `Refusing to delete: the pre-delete export could not be written and read back at ${exportPath} — ` - + `${error instanceof Error ? error.message : String(error)}. No row was deleted.`; - if (json) await emitJson({ error: 'export_failed', message }, 0, { compact: true }); - else printError(message); - return; - } - const missing = rows.filter((row) => !exported.has(String(row.id))); - if (missing.length > 0) { - exitCode = 1; - const message = `Refusing to delete: the export at ${exportPath} does not hold ${missing.length} of the ` - + `${rows.length} row(s). No row was deleted.`; - if (json) await emitJson({ error: 'export_incomplete', message }, 0, { compact: true }); - else printError(message); - return; - } - if (!json) printSuccess(`Pre-delete export written (owner-only): ${exportPath}`); - - // ── The delete: the exported rows, by id, and nothing else ──────────── - const failed: Array<{ ids: string[]; message: string }> = []; - const ids = rows.map((row) => String(row.id)); - for (let i = 0; i < ids.length; i += PAGE_SIZE) { - const batch = ids.slice(i, i + PAGE_SIZE); - try { - await engine.delete(USER_PREFERENCE_OBJECT, { - where: { id: { $in: batch } }, - multi: true, - context: { ...SYSTEM }, - } as never); - } catch (error) { - failed.push({ ids: batch, message: error instanceof Error ? error.message : String(error) }); - } - } - // Judged by what is gone, never by what the delete returned. - const left = await listRetiredListPreferenceRows(engine); - const leftIds = new Set(left.map((row) => String(row.id))); - const deleted = ids.filter((id) => !leftIds.has(id)).length; - if (failed.length > 0 || left.length > 0) exitCode = 1; - - if (json) { - await emitJson({ - database: stack.dbLabel, - apply, - export: exportPath, - ...summary, - deleted, - remaining: left.length, - failures: failed.map((f) => f.message), - duration: timer.elapsed(), - }); - return; - } - printInfo(`Database: ${chalk.white(stack.dbLabel)}`); - console.log(''); - console.log(` ${chalk.white(USER_PREFERENCE_OBJECT)}: ${deleted} of ${summary.rows} "ui.list." row(s) deleted, for ${summary.users} user(s)`); - for (const f of failed) printWarning(`A delete of ${f.ids.length} row(s) failed: ${f.message}`); - console.log(''); - if (left.length > 0) { - printError(`${left.length} "ui.list." row(s) are still stored — re-run with a new --export path to remove them.`); - } else { - printSuccess(`Removed every "ui.list." preference row ${chalk.dim(`(${timer.display()})`)}`); - printInfo(`Keep ${exportPath} until you are certain — it is the only copy of the deleted rows.`); - } - } catch (error: any) { - if (isExitSignal(error)) throw error; - exitCode = 1; - if (json) await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); - else printError(error.message || String(error)); - } finally { - await stack.shutdown(); - } - if (exitCode !== 0) this.exit(exitCode); - } -} diff --git a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts index abcaa09487d..d8538606d64 100644 --- a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts +++ b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts @@ -87,7 +87,6 @@ import MigrateTextScalars from '../commands/migrate/text-scalars.js'; import MigrateCommentReactions from '../commands/migrate/comment-reactions.js'; import MigrateDuplicates from '../commands/migrate/duplicates.js'; import MigrateFilesToReferences from '../commands/migrate/files-to-references.js'; -import MigrateListPreferences from '../commands/migrate/list-preferences.js'; import MigrateMeta from '../commands/migrate/meta.js'; import MigrateMultiValueColumns from '../commands/migrate/multi-value-columns.js'; import MigrateOrganizationOwnership from '../commands/migrate/organization-ownership.js'; @@ -241,13 +240,6 @@ const CALLERS: Record = { noWrite: [{ label: 'migrate text-scalars', argv: ['--database-url', '@DB@', '--json'] }], write: [{ label: 'migrate text-scalars --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], }, - 'commands/migrate/list-preferences.ts': { - run: invoke(MigrateListPreferences), - noWrite: [{ label: 'migrate list-preferences', argv: ['--database-url', '@DB@', '--json'] }], - // The fixture stores no `ui.list.` row, so the run deletes nothing and - // writes no export: the plain boot a delete takes is what this case is about. - write: [{ label: 'migrate list-preferences --apply', argv: ['--apply', '--export', '@DIR@/list-preferences-export.json', '--yes', '--database-url', '@DB@', '--json'] }], - }, 'commands/migrate/comment-parent-pair.ts': { run: invoke(MigrateCommentParentPair), noWrite: [{ label: 'migrate comment-parent-pair', argv: ['--database-url', '@DB@', '--json'] }], diff --git a/packages/cli/test/json-stdout-purity.e2e.test.ts b/packages/cli/test/json-stdout-purity.e2e.test.ts index 6646bf645a9..eafcbb40a03 100644 --- a/packages/cli/test/json-stdout-purity.e2e.test.ts +++ b/packages/cli/test/json-stdout-purity.e2e.test.ts @@ -140,10 +140,6 @@ const FAMILY: Record = { // it boots read-only (plugin-audit's objects registered), reads // `sys_comment` below the data door and writes nothing. 'migrate comment-reactions': [], - // [#35955] A dry run is its DEFAULT and the only form driven here: it boots - // read-only (plugin-auth's identity objects registered for their - // declarations) and reads `sys_user_preference`; it writes nothing. - 'migrate list-preferences': [], 'migrate files-to-references': [], 'migrate meta': ['--stored'], 'migrate multi-value-columns': [], diff --git a/packages/cli/test/migrate-confirmation-exit.pin.test.ts b/packages/cli/test/migrate-confirmation-exit.pin.test.ts index 258a44e096e..88d0d1e36a1 100644 --- a/packages/cli/test/migrate-confirmation-exit.pin.test.ts +++ b/packages/cli/test/migrate-confirmation-exit.pin.test.ts @@ -261,8 +261,6 @@ const ROSTER: Record = { 'text-scalars': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'comment-parent-pair': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'comment-reactions': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, - // The export path is mandatory with `--apply` and must not exist yet; the gate sits after both checks. - 'list-preferences': { argv: ['--apply', '--export', join(SCRATCH, 'list-preferences-export.json')], confirm: '--yes', writes: BOOT }, 'files-to-references': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, // `--yes` belongs to the stored-row pass; without `--stored` the command converts source files. meta: { argv: ['--stored', '--apply'], confirm: '--yes', writes: BOOT }, From 237bbe0249074e2a691c73bce2d6885a0ed76704 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:03:16 +0000 Subject: [PATCH 4/6] test(app-shell): pay the lint load at collection in the toolbar-writes test Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- .../src/views/ObjectView.toolbarWritesCompose-11642.test.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx b/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx index d6bd204838a..5e422dde4d7 100644 --- a/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.toolbarWritesCompose-11642.test.tsx @@ -121,6 +121,9 @@ vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ })); import { toast } from 'sonner'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; From 4072c3aa07bf6881af342a98ee8d6cc9708b2066 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:30:40 +0000 Subject: [PATCH 5/6] test(app-shell): re-pin the walled list-state test to the browser layout Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- .../consoleListStateWall-12418.test.tsx | 68 +++++++++---------- 1 file changed, 31 insertions(+), 37 deletions(-) diff --git a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx index 9b000e241bc..6f2783dfa96 100644 --- a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx @@ -6,14 +6,17 @@ * `walledCatalogWriteVerdict`). A header sort and a Manage Views drag used to * be such writes: the sort PUT the view, the drag PATCHed a `sortOrder` onto * every saved view, so a workspace admin who is not the operator got an error - * for a personal preference. They are the user's own list state now, a - * `sys_user_preference` row: an organization row the tenant's user may write - * under every posture. + * for a personal preference. They are the user's own list state now. Since + * objectstack#35955 the sort is the list's draft and the tab order and the + * density are the reader's layout in this browser + * (`list-layout::`, `../../views/listLayoutStore.ts`), so + * neither reaches the server at all: no metadata write, and no + * `sys_user_preference` write either. * * ## The tree * * The real `ConsoleShell` providers, the real `ConnectedShell` (its real - * `ObjectStackAdapter`, its `UserStateBridge` and the list-state family), and + * `ObjectStackAdapter` and its `UserStateBridge`), and * the real object page inside it, over the fake framework the preference * budget pin uses (`preferenceFramework.ts`), here WALLED: every metadata * write is answered 403. The session reports the `group` posture and a @@ -23,13 +26,12 @@ * * ## The pins * - * 1. A header sort and a drag-reorder put NO metadata write on the wire - * and raise no error. The drag lands as ONE preference write of the - * object's row; the sort is the list's draft (objectstack#35955) and - * writes nothing. + * 1. A header sort and a drag-reorder put NO write on the wire and raise no + * error. The drag is kept in this browser's layout entry; the sort is + * the list's draft and is kept nowhere. * 2. objectui#12474 — the density toggle and a Hide Fields change put NO - * metadata write on the wire and raise no error. The density lands as - * ONE preference write of the same row; the hide is the draft's. + * write on the wire and raise no error. The density is kept in the same + * layout entry; the hide is the draft's. * 3. CONTROL — the wall is live: a metadata write made in this same tree * (the real adapter's own view write, `createView`) is answered 403. * Since objectui#12474 no list toolbar control makes one, so the control @@ -126,7 +128,8 @@ import { useAdapter } from '../../providers/AdapterProvider'; import '@objectstack/lint'; import { ObjectView } from '../../views/ObjectView'; import { resetListDraftStoreForTests } from '../../views/listDraftStore'; -import { createPreferenceFramework, preferenceRowId, type PreferenceFramework } from './preferenceFramework'; +import { listLayoutStorageKey, resetListLayoutStoreForTests } from '../../views/listLayoutStore'; +import { createPreferenceFramework, type PreferenceFramework } from './preferenceFramework'; const FIELDS = { id: { type: 'text', label: 'Id' }, @@ -142,7 +145,7 @@ const OBJECT = { }, }; -/** The user already has a list-state row for the object (from another device). */ +/** A list-state row an earlier Console stored for the user: no longer read or written (objectstack#35955). */ const STORE = { u1: { 'ui.list.account': { viewOrder: [ALL_ID, MINE_ID] } } }; let fake: PreferenceFramework; @@ -174,10 +177,14 @@ function boot() { ); } +/** The reader's layout entry for the object in this browser. */ +const storedLayout = () => JSON.parse(localStorage.getItem(listLayoutStorageKey('u1', OBJECT_NAME)!) ?? 'null'); + const wait = (ms: number) => act(() => new Promise((resolve) => setTimeout(resolve, ms))); beforeEach(() => { resetListDraftStoreForTests(); + resetListLayoutStoreForTests(); listProps = null; pageAdapter = null; localStorage.clear(); @@ -195,7 +202,7 @@ afterEach(() => { }); describe('a user\'s list state under a walled posture (objectui#12418)', () => { - it('a header sort and a drag-reorder write no metadata and raise no error; the drag lands as one preference write, the sort as the draft', async () => { + it('a header sort and a drag-reorder write nothing to the server and raise no error; the drag is kept in this browser, the sort as the draft', async () => { boot(); await waitFor(() => expect(typeof listProps?.onSortChange).toBe('function'), { timeout: 5000 }); await screen.findByTestId('stub-reorder'); @@ -208,22 +215,18 @@ describe('a user\'s list state under a walled posture (objectui#12418)', () => { await act(async () => { fireEvent.click(screen.getByTestId('stub-reorder')); }); - // Past the preference debounce (500 ms) and the round trip. - await waitFor(() => expect(fake.wire.writes).toHaveLength(1), { timeout: 3000 }); - await wait(400); + // Past the old preference debounce (500 ms) and a round trip. + await wait(900); expect(fake.wire.metaWrites).toEqual([]); + expect(fake.wire.writes).toEqual([]); expect(toast.error).not.toHaveBeenCalled(); - expect(fake.wire.writes).toHaveLength(1); - const [write] = fake.wire.writes; - // An update of the row the boot read found: no second read, no insert. - expect(write.id).toBe(preferenceRowId('u1', 'ui.list.account')); expect(fake.wire.gets.length).toBe(readsBefore); - // objectstack#35955 — the sort is the list's draft: it is stored nowhere. - expect(write.value).toEqual({ viewOrder: [MINE_ID, ALL_ID] }); + // objectstack#35955 — the order is this browser's; the sort is the list's draft, stored nowhere. + expect(storedLayout()).toEqual({ viewOrder: [MINE_ID, ALL_ID] }); }); - it('a density toggle and a Hide Fields change write no metadata and raise no error; the density lands as one preference write, the hide as the draft (objectui#12474)', async () => { + it('a density toggle and a Hide Fields change write nothing to the server and raise no error; the density is kept in this browser, the hide as the draft (objectui#12474)', async () => { boot(); await waitFor(() => expect(typeof listProps?.schema?.onDensityChange).toBe('function'), { timeout: 5000 }); await wait(100); @@ -232,30 +235,21 @@ describe('a user\'s list state under a walled posture (objectui#12418)', () => { act(() => { listProps.schema.onDensityChange('comfortable'); }); - // Past the preference debounce (500 ms) and the round trip. - await waitFor(() => expect(fake.wire.writes).toHaveLength(1), { timeout: 3000 }); - await wait(400); - expect(fake.wire.metaWrites).toEqual([]); - expect(toast.error).not.toHaveBeenCalled(); - expect(fake.wire.writes).toHaveLength(1); - expect(fake.wire.writes[0].id).toBe(preferenceRowId('u1', 'ui.list.account')); - expect(fake.wire.writes[0].value).toEqual({ - viewOrder: [ALL_ID, MINE_ID], - perView: { [ALL_ID]: { rowHeight: 'medium' } }, - }); + await wait(100); + expect(storedLayout()).toEqual({ perView: { [ALL_ID]: { rowHeight: 'medium' } } }); // The list is handed the user's density back. expect(listProps.schema.rowHeight).toBe('medium'); act(() => { listProps.onHiddenFieldsChange(['name']); }); - // Past the preference debounce (500 ms) and a round trip: nothing more is written. + // Past the old preference debounce (500 ms) and a round trip: nothing is written. await wait(900); expect(fake.wire.metaWrites).toEqual([]); + expect(fake.wire.writes).toEqual([]); expect(toast.error).not.toHaveBeenCalled(); - expect(fake.wire.writes).toHaveLength(1); expect(listProps.schema.hiddenFields).toEqual(['name']); - // No second read: each write updates the row the boot read found. + expect(storedLayout()).toEqual({ perView: { [ALL_ID]: { rowHeight: 'medium' } } }); expect(fake.wire.gets.length).toBe(readsBefore); }); From bb99349ced857c6932621dad0a3db5b297afa5d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 01:33:12 +0000 Subject: [PATCH 6/6] test(app-shell): seed the reader's row height in the browser layout in the shared-view footer case Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude --- .../src/views/ObjectView.sharedViewSave-35955.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx b/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx index 387aeb50b3f..1a2020c79a8 100644 --- a/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.sharedViewSave-35955.test.tsx @@ -399,7 +399,7 @@ describe('objectstack#35955 — the layout and the row colour the reader picks a describe('objectstack#36194 + objectstack#36195 — a shared view\'s Save to this view carries the footer calculations, and waits for the package list', () => { it('a footer calculation picked is a part of the draft, saved into the view with no write of its own; the reader\'s row height stays theirs', async () => { - localStorage.setItem(`list-state:u1:${OBJECT}`, JSON.stringify({ perView: { [SHARED.name]: { rowHeight: 'tall' } } })); + localStorage.setItem(listLayoutStorageKey('u1', OBJECT)!, JSON.stringify({ perView: { [SHARED.name]: { rowHeight: 'tall' } } })); mount(SHARED.name); await settle(); await waitFor(() => expect(typeof listProps.current?.onColumnSummaryPick).toBe('function'));