Skip to content

Commit e347607

Browse files
committed
wip: list layout in the browser only; os migrate list-preferences
Claude-Session: https://claude.ai/code/session_01L6bhgUkr3W7rNEqPk3J858 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1586dde commit e347607

19 files changed

Lines changed: 1176 additions & 986 deletions

‎content/docs/ui/views.mdx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -634,8 +634,12 @@ whose menu also holds Discard on a narrow list or a phone).
634634
- The draft survives opening a record and coming back. Opening another view or object,
635635
or reloading the list's page, drops it, so that reload opens the view as it is declared.
636636
- Column widths, the row height (density) and the views' order are not a draft: they are
637-
remembered for the user (`sys_user_preference`, key `ui.list.<object>`). A sort, filter,
638-
column order or hidden column an earlier Console stored there no longer applies.
637+
remembered in this browser only, per user and object (localStorage
638+
`list-layout:<user>:<object>`). Nothing is sent to the server, another browser or device
639+
opens the view's own layout, and signing out clears them with the rest of this browser's
640+
Console state. Earlier Consoles kept them, with a stored sort and filters, in the user's
641+
`sys_user_preference` row `ui.list.<object>`; nothing reads that row now, and
642+
`os migrate list-preferences` removes such rows.
639643
- A link carrying list state (`uf_*` parameters) applies it as a draft, whether it opens in a
640644
new tab or in-app (an AI answer's list link, after a reload of the chat page too).
641645
- When a session ends, the sign-in page's return link keeps the list's path but never its
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest';
4+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5+
import { tmpdir } from 'node:os';
6+
import { dirname, join, resolve } from 'node:path';
7+
import { fileURLToPath } from 'node:url';
8+
import Database from 'better-sqlite3';
9+
import { isExitSignal } from '../../utils/format.js';
10+
import MigrateApply from './apply.js';
11+
import MigrateListPreferences from './list-preferences.js';
12+
13+
// Pay the first transform of the dist-resolved workspace deps the commands
14+
// reach through dynamic `import()`s at MODULE LOAD, not inside a case.
15+
import '@objectstack/runtime';
16+
import '@objectstack/objectql';
17+
18+
/**
19+
* `os migrate list-preferences` against a real SQLite database: the step that
20+
* removes the `sys_user_preference` rows keyed `ui.list.<object>`, which no
21+
* Console reads any more (objectstack#35955).
22+
*
23+
* ## The database
24+
*
25+
* The schema this version creates (`os migrate apply --yes` over an empty
26+
* file), with the rows an earlier Console left: three `ui.list.*` rows for two
27+
* users, and two CONTROLS that are never touched — another family's row
28+
* (`ui.record.account`) and a key that only looks alike (`ui.lists`).
29+
*
30+
* ## The cases run in order over ONE database, as an operator runs the steps
31+
*
32+
* 1. a dry run reports the rows and deletes nothing;
33+
* 2. `--apply` without `--export` is refused, and so is an export path that
34+
* already exists — both with nothing deleted;
35+
* 3. `--apply --export` writes the export (owner-only, every row as stored),
36+
* deletes exactly the `ui.list.*` rows, and keeps the controls;
37+
* 4. a re-run finds nothing and writes no export.
38+
*/
39+
40+
const HERE = dirname(fileURLToPath(import.meta.url));
41+
const CLI_ROOT = resolve(HERE, '..', '..', '..');
42+
const CASE_TIMEOUT_MS = 240_000;
43+
44+
const RETIRED = [
45+
{ id: 'pref_l1', user_id: 'u1', key: 'ui.list.account', value: '{"viewOrder":["account.all"]}' },
46+
{ id: 'pref_l2', user_id: 'u1', key: 'ui.list.contact', value: '{"perView":{"contact.all":{"rowHeight":"compact"}}}' },
47+
{ id: 'pref_l3', user_id: 'u2', key: 'ui.list.account', value: '{"perView":{"account.all":{"sort":[{"field":"name","order":"desc"}]}}}' },
48+
];
49+
const CONTROLS = [
50+
{ id: 'pref_r1', user_id: 'u1', key: 'ui.record.account', value: '{"showEmptyFields":true}' },
51+
{ id: 'pref_x1', user_id: 'u2', key: 'ui.lists', value: '{}' },
52+
];
53+
54+
type Invoke = (argv: string[]) => Promise<unknown>;
55+
const invoke = (command: { run: (argv: string[], opts: { root: string }) => Promise<unknown> }): Invoke =>
56+
(argv) => command.run(argv, { root: CLI_ROOT });
57+
58+
/** Env that would point a command's boot somewhere other than the fixture. */
59+
const OVERRIDING_ENV = [
60+
'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME',
61+
'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ARTIFACT_PATH',
62+
] as const;
63+
64+
/** Run one command and capture its JSON document and exit status. */
65+
async function runJson(command: Invoke, argv: string[]): Promise<{ payload: any; exitCode: number }> {
66+
const savedExit = process.exitCode;
67+
const swallow = ((_chunk: unknown, ...rest: unknown[]) => {
68+
const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined;
69+
if (cb) cb();
70+
return true;
71+
}) as typeof process.stdout.write;
72+
const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow);
73+
vi.spyOn(process.stderr, 'write').mockImplementation(swallow);
74+
vi.spyOn(console, 'log').mockImplementation(() => {});
75+
vi.spyOn(console, 'warn').mockImplementation(() => {});
76+
vi.spyOn(console, 'error').mockImplementation(() => {});
77+
let processExit: number | undefined;
78+
vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
79+
processExit = code ?? 0;
80+
throw new Error(`__PROCESS_EXIT__:${processExit}`);
81+
}) as never);
82+
let thrownExit: number | undefined;
83+
try {
84+
try {
85+
await command(argv);
86+
} catch (error) {
87+
const trapped = error instanceof Error && error.message.startsWith('__PROCESS_EXIT__');
88+
if (!trapped && !isExitSignal(error)) throw error;
89+
if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit;
90+
}
91+
const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim();
92+
let payload: any;
93+
try {
94+
payload = JSON.parse(out);
95+
} catch {
96+
payload = { unparsed: out.slice(-400) };
97+
}
98+
return { payload, exitCode: processExit ?? thrownExit ?? (process.exitCode as number | undefined) ?? 0 };
99+
} finally {
100+
process.exitCode = savedExit;
101+
vi.restoreAllMocks();
102+
}
103+
}
104+
105+
let dir: string;
106+
let dbFile: string;
107+
const savedEnv: Record<string, string | undefined> = {};
108+
const savedCwd = process.cwd();
109+
110+
function withDb<T>(fn: (db: Database.Database) => T, readonly = true): T {
111+
const db = new Database(dbFile, { readonly });
112+
try {
113+
return fn(db);
114+
} finally {
115+
db.close();
116+
}
117+
}
118+
119+
/** Insert a row, filling every other NOT NULL column without a default with a placeholder of its type. */
120+
function plant(db: Database.Database, table: string, values: Record<string, unknown>): void {
121+
const columns = db.prepare(`PRAGMA table_info('${table}')`).all() as Array<
122+
{ name: string; type: string; notnull: number; dflt_value: unknown; pk: number }
123+
>;
124+
const row: Record<string, unknown> = { ...values };
125+
for (const c of columns) {
126+
if (c.name in row || !c.notnull || c.dflt_value !== null) continue;
127+
row[c.name] = /INT|BOOL|REAL|NUM/i.test(c.type) ? 0 : `${c.name}-placeholder`;
128+
}
129+
const names = Object.keys(row);
130+
db.prepare(`INSERT INTO "${table}" (${names.map((n) => `"${n}"`).join(', ')}) VALUES (${names.map(() => '?').join(', ')})`)
131+
.run(...names.map((n) => row[n] as never));
132+
}
133+
134+
const storedIds = (): string[] =>
135+
withDb((db) => (db.prepare("SELECT id FROM sys_user_preference WHERE id LIKE 'pref_%' ORDER BY id").all() as
136+
Array<{ id: string }>).map((r) => r.id));
137+
138+
beforeAll(async () => {
139+
for (const key of [...OVERRIDING_ENV, 'NODE_ENV'] as const) savedEnv[key] = process.env[key];
140+
for (const key of OVERRIDING_ENV) delete process.env[key];
141+
dir = mkdtempSync(join(tmpdir(), 'os-35955-list-prefs-'));
142+
mkdirSync(join(dir, 'dist'), { recursive: true });
143+
writeFileSync(
144+
join(dir, 'objectstack.config.ts'),
145+
[
146+
'export default {',
147+
" manifest: { id: 'com.example.os35955listprefs', name: 'list prefs', version: '0.0.0', type: 'app' },",
148+
" objects: [{ name: 'os35955_thing', fields: { title: { type: 'text' } } }],",
149+
'};',
150+
'',
151+
].join('\n'),
152+
);
153+
process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json');
154+
process.env.NODE_ENV = 'production';
155+
process.env.OS_TELEMETRY_DB = '0';
156+
dbFile = join(dir, 'upgraded.db');
157+
process.chdir(dir);
158+
try {
159+
const created = await runJson(invoke(MigrateApply), ['--database-url', `file:${dbFile}`, '--yes', '--json']);
160+
expect(created.exitCode, JSON.stringify(created.payload).slice(0, 400)).toBe(0);
161+
} finally {
162+
process.chdir(savedCwd);
163+
}
164+
withDb((db) => {
165+
for (const row of [...RETIRED, ...CONTROLS]) plant(db, 'sys_user_preference', row);
166+
}, false);
167+
expect(storedIds()).toEqual([...RETIRED, ...CONTROLS].map((r) => r.id).sort());
168+
}, CASE_TIMEOUT_MS);
169+
170+
afterAll(() => {
171+
process.chdir(savedCwd);
172+
for (const [key, value] of Object.entries(savedEnv)) {
173+
if (value === undefined) delete process.env[key];
174+
else process.env[key] = value;
175+
}
176+
try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
177+
});
178+
179+
beforeEach(() => { process.chdir(dir); });
180+
afterEach(() => { process.chdir(savedCwd); });
181+
182+
describe('os migrate list-preferences removes the ui.list.* preference rows (objectstack#35955)', () => {
183+
const db = () => `file:${dbFile}`;
184+
const run = (argv: string[]) => runJson(invoke(MigrateListPreferences), ['--database-url', db(), ...argv, '--json']);
185+
const all = [...RETIRED, ...CONTROLS].map((r) => r.id).sort();
186+
187+
it('1. a dry run reports the rows, users and objects, and deletes nothing', async () => {
188+
const { payload, exitCode } = await run([]);
189+
expect(exitCode).toBe(0);
190+
expect(payload).toMatchObject({ apply: false, rows: 3, users: 2, objects: ['account', 'contact'], deleted: 0, remaining: 3 });
191+
expect(storedIds()).toEqual(all);
192+
}, CASE_TIMEOUT_MS);
193+
194+
it('2. --apply is refused without --export, and over an existing export, with nothing deleted', async () => {
195+
const bare = await run(['--apply', '--yes']);
196+
expect(bare.exitCode).toBe(1);
197+
expect(bare.payload.error).toBe('export_required');
198+
199+
const taken = join(dir, 'taken.json');
200+
writeFileSync(taken, 'keep me\n');
201+
const over = await run(['--apply', '--yes', '--export', taken]);
202+
expect(over.exitCode).toBe(1);
203+
expect(over.payload.error).toBe('export_exists');
204+
expect(readFileSync(taken, 'utf8')).toBe('keep me\n');
205+
expect(storedIds()).toEqual(all);
206+
}, CASE_TIMEOUT_MS);
207+
208+
it('3. --apply --export writes every retired row to an owner-only export, then deletes exactly those rows', async () => {
209+
const exportPath = join(dir, 'list-preferences-export.json');
210+
const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]);
211+
expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0);
212+
expect(payload).toMatchObject({ apply: true, rows: 3, users: 2, deleted: 3, remaining: 0, failures: [] });
213+
214+
const doc = JSON.parse(readFileSync(exportPath, 'utf8'));
215+
expect(doc.keyPrefix).toBe('ui.list.');
216+
expect(doc.rows.map((r: { id: string }) => r.id).sort()).toEqual(RETIRED.map((r) => r.id));
217+
expect(doc.rows.find((r: { id: string }) => r.id === 'pref_l3')).toMatchObject({ user_id: 'u2', key: 'ui.list.account' });
218+
if (process.platform !== 'win32') expect(statSync(exportPath).mode & 0o077).toBe(0);
219+
220+
expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort());
221+
}, CASE_TIMEOUT_MS);
222+
223+
it('4. a re-run finds nothing, writes no export, and keeps the controls', async () => {
224+
const exportPath = join(dir, 'second-export.json');
225+
const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]);
226+
expect(exitCode).toBe(0);
227+
expect(payload).toMatchObject({ rows: 0, deleted: 0, remaining: 0 });
228+
expect(existsSync(exportPath)).toBe(false);
229+
expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort());
230+
}, CASE_TIMEOUT_MS);
231+
});
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Nothing runs `os migrate list-preferences` for you: it deletes stored rows,
5+
* so it stays an operator's command, and no boot, upgrade, migrate or
6+
* lifecycle path may import it.
7+
*
8+
* Every absence below is preceded by the SAME scanner finding a call site that
9+
* really exists (a dynamic import on the boot path), so an empty answer is
10+
* not a broken scanner. The shape is `../db/orphans.no-auto-run.test.ts`'s.
11+
*/
12+
13+
import { describe, it, expect } from 'vitest';
14+
import { readFileSync, readdirSync, statSync } from 'node:fs';
15+
import { dirname, join, resolve } from 'node:path';
16+
import { fileURLToPath } from 'node:url';
17+
18+
/** `packages/cli/src` — this package only; the scan never leaves it. */
19+
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
20+
21+
function everyTsFile(dir: string, out: string[] = []): string[] {
22+
for (const entry of readdirSync(dir)) {
23+
const full = join(dir, entry);
24+
if (statSync(full).isDirectory()) everyTsFile(full, out);
25+
else if (entry.endsWith('.ts')) out.push(full);
26+
}
27+
return out;
28+
}
29+
30+
const ALL_FILES = everyTsFile(SRC_ROOT);
31+
const relative = (file: string) => file.slice(SRC_ROOT.length).replaceAll('\\', '/');
32+
const isTestFile = (path: string) => /\.test\.ts$/.test(path);
33+
34+
/** A static `from '…'` or a dynamic `import('…')` specifier. */
35+
const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g;
36+
37+
/** Files whose relative import RESOLVES to `target` (a path under `src/`), whatever the specifier's spelling. */
38+
function importersOf(target: string): string[] {
39+
const wanted = join(SRC_ROOT, target);
40+
return ALL_FILES.filter((file) => {
41+
for (const m of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) {
42+
const spec = m[1]!;
43+
if (!spec.startsWith('.')) continue;
44+
if (resolve(dirname(file), spec).replace(/\.js$/, '.ts') === wanted) return true;
45+
}
46+
return false;
47+
}).map(relative);
48+
}
49+
50+
const COMMAND = 'commands/migrate/list-preferences.ts';
51+
/** The one-shot boot family's enumeration pin RUNS every bootSchemaStack caller's modes; a test, never a boot path. */
52+
const FAMILY_PIN = 'utils/schema-migrate.one-shot-family.integration.test.ts';
53+
54+
describe('the scanner works (positive controls)', () => {
55+
it('finds the CLI’s own boot path reaching the kernel:ready migration gate — a DYNAMIC import', () => {
56+
expect(importersOf('utils/artifact-boot-migration.ts').filter((p) => !isTestFile(p))).toContain('commands/serve.ts');
57+
});
58+
59+
it('finds the family pin importing this command', () => {
60+
expect(importersOf(COMMAND)).toContain(FAMILY_PIN);
61+
});
62+
63+
it('the file population itself is real', () => {
64+
expect(ALL_FILES.length).toBeGreaterThan(100);
65+
expect(ALL_FILES.map(relative)).toContain(COMMAND);
66+
});
67+
});
68+
69+
describe('nothing on a boot, upgrade, migrate or lifecycle path invokes os migrate list-preferences', () => {
70+
it('no source file imports the command — its own tests and the family pin are the only readers', () => {
71+
const importers = importersOf(COMMAND);
72+
expect(importers.filter((p) => !isTestFile(p))).toEqual([]);
73+
expect(
74+
importers.every((p) => p.startsWith('commands/migrate/list-preferences.') || p === FAMILY_PIN),
75+
importers.join(', '),
76+
).toBe(true);
77+
});
78+
79+
it('the CLI barrel does not export it', () => {
80+
expect(readFileSync(join(SRC_ROOT, 'index.ts'), 'utf8')).not.toContain('list-preferences');
81+
});
82+
});

0 commit comments

Comments
 (0)