Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(databases): keep column names stable while saving (#9001)

Wolf Mermelsteineb92166b9bf0
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a32c62214c..b042803350 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -141,6 +141,11 @@ new MutationObserver(() => {
Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '1,2,3'` (the same ids coming back) is a `<Suspense>` detach and re-attach. Fresh ids are a true remount. Nothing at all means the subtree never moved and the cause is elsewhere. Re-running the same interaction a second time is the cheapest way to prove a cold-cache cause: a once-per-session query settles after the first attempt, so the second attempt stays clean.
+Column renames have a backend-free desktop/phone regression using the real
+schema query and mutation adapter with delayed service responses:
+`bunx playwright test --config src/features/block-database/browser-test/playwright.config.ts rename.browser.e2e.ts`.
+It checks the optimistic name, header identity, and persistence across reload.
+
## Canvas collaboration
Document sync uses the `sync-via-gateway` PostHog flag in both deployed dev and
diff --git a/apps/web/src/features/block-database/browser-test/rename-data.ts b/apps/web/src/features/block-database/browser-test/rename-data.ts
new file mode 100644
index 0000000000..e1339e1887
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/rename-data.ts
@@ -0,0 +1,57 @@
+import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';
+
+/** Synthetic schema shared by the adapter and browser rename regressions. */
+export const RENAME_DETAIL: DatabaseDetail = {
+ database: {
+ id: 'db',
+ name: 'Planning',
+ owner_id: 'owner',
+ created_at: '',
+ trashed_at: null,
+ },
+ grant: 'owner',
+ tables: [
+ {
+ table: {
+ id: 'tasks',
+ database_id: 'db',
+ name: 'Tasks',
+ position: 'a',
+ version: 1,
+ },
+ sql_name: '"Tasks"',
+ views: [],
+ columns: [
+ {
+ column: {
+ id: 'name',
+ table_id: 'tasks',
+ property_definition_id: 'property',
+ position: 'a',
+ config: null,
+ display_name: null,
+ infer_type: false,
+ },
+ definition: {
+ definition: {
+ id: 'property',
+ display_name: 'Name',
+ data_type: 'STRING',
+ is_multi_select: false,
+ is_metadata: false,
+ is_system: false,
+ specific_entity_type: null,
+ owner: { scope: 'database', database_id: 'db' },
+ created_at: '',
+ updated_at: '',
+ },
+ property_options: [],
+ },
+ sql_name: '"Name"',
+ shared_outside_database: false,
+ writable: true,
+ },
+ ],
+ },
+ ],
+};
diff --git a/apps/web/src/features/block-database/browser-test/rename.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/rename.browser.e2e.ts
new file mode 100644
index 0000000000..4abd6e2d7c
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/rename.browser.e2e.ts
@@ -0,0 +1,133 @@
+import { expect, test } from '@playwright/test';
+import { openFixture } from './open-fixture';
+import { RENAME_DETAIL } from './rename-data';
+
+for (const phone of [false, true]) {
+ test(`column rename never restores the old title or remounts the header (${phone ? 'phone' : 'desktop'})`, async ({
+ browser,
+ }) => {
+ const context = await browser.newContext({
+ viewport: { width: phone ? 390 : 1280, height: 800 },
+ hasTouch: phone,
+ });
+ const page = await context.newPage();
+ const stored = structuredClone(RENAME_DETAIL);
+ let releaseWrite!: () => void;
+ let releaseSchema!: () => void;
+ const writeGate = new Promise<void>((resolve) => {
+ releaseWrite = resolve;
+ });
+ const schemaGate = new Promise<void>((resolve) => {
+ releaseSchema = resolve;
+ });
+ let committed = false;
+ let sawWrite!: () => void;
+ const submitted = new Promise<void>((resolve) => {
+ sawWrite = resolve;
+ });
+ let sawRefresh!: () => void;
+ const refreshing = new Promise<void>((resolve) => {
+ sawRefresh = resolve;
+ });
+ await page.route('https://**', (route) => route.abort());
+ await page.route('**/__macro_dev/**', (route) => route.abort());
+ await page.route('**/databases/db', async (route) => {
+ if (committed) {
+ sawRefresh();
+ await schemaGate;
+ }
+ await route.fulfill({ json: stored });
+ });
+ await page.route('**/databases/db/ops', async (route) => {
+ const { ops } = route.request().postDataJSON();
+ expect(ops[0].change).toEqual({
+ kind: 'rename',
+ name: 'Task',
+ previousName: 'Name',
+ });
+ sawWrite();
+ await writeGate;
+ stored.tables[0].columns[0].column.display_name = 'Task';
+ stored.tables[0].columns[0].sql_name = '"Task"';
+ stored.tables[0].table.version = 2;
+ committed = true;
+ await route.fulfill({
+ json: {
+ results: [
+ {
+ kind: 'column',
+ table: 'tasks',
+ column: 'name',
+ tableVersion: 2,
+ change: { kind: 'renamed' },
+ },
+ ],
+ changes: [],
+ },
+ });
+ });
+ await openFixture(
+ page,
+ '/src/features/block-database/browser-test/rename.html'
+ );
+ const header = page.getByRole('columnheader', {
+ name: 'Name',
+ exact: true,
+ });
+ await expect(header).toBeVisible();
+ await header.evaluate((element) => {
+ element.setAttribute('data-rename-original', 'true');
+ const names: string[] = [];
+ Object.assign(window, { renameNames: names });
+ new MutationObserver(() => {
+ names.push(element.getAttribute('aria-label') ?? '');
+ }).observe(element, {
+ attributes: true,
+ attributeFilter: ['aria-label'],
+ });
+ });
+ await header.dblclick();
+ await page
+ .getByRole('textbox', { name: 'Column name', exact: true })
+ .fill('Task');
+ await page
+ .getByRole('textbox', { name: 'Column name', exact: true })
+ .press('Enter');
+ await submitted;
+ await expect(
+ page.getByRole('columnheader', { name: 'Task', exact: true })
+ ).toBeVisible();
+ releaseWrite();
+ await refreshing;
+ // The write has committed, but the schema refetch is still held. Let the
+ // controller finish the save and reveal any fallback to its old props.
+ await page
+ .locator('[data-rename-original]')
+ .getByRole('button', { name: /column menu$/ })
+ .click();
+ await expect(
+ page.getByRole('menuitem', { name: 'Rename column', exact: true })
+ ).toBeEnabled();
+ await page.getByText('Planning', { exact: true }).click();
+ await expect(page.getByRole('menu')).toHaveCount(0);
+ await page.screenshot({
+ path: `${process.env.RENAME_PROOF_DIR ?? '/tmp/column-rename-proof'}/${phone ? 'phone' : 'desktop'}.png`,
+ });
+ await expect(page.locator('[data-rename-original]')).toHaveAttribute(
+ 'aria-label',
+ 'Task'
+ );
+ expect(
+ await page.evaluate(() => Reflect.get(window, 'renameNames'))
+ ).toEqual(['Task']);
+ releaseSchema();
+ await expect(
+ page.getByRole('columnheader', { name: 'Task', exact: true })
+ ).toBeVisible();
+ await page.reload();
+ await expect(
+ page.getByRole('columnheader', { name: 'Task', exact: true })
+ ).toBeVisible();
+ await context.close();
+ });
+}
diff --git a/apps/web/src/features/block-database/browser-test/rename.html b/apps/web/src/features/block-database/browser-test/rename.html
new file mode 100644
index 0000000000..21abeaa818
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/rename.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta charset="utf-8" /><title>Column rename regression</title></head><body><div id="root"></div><script type="module" src="./rename.tsx"></script></body></html>
diff --git a/apps/web/src/features/block-database/browser-test/rename.tsx b/apps/web/src/features/block-database/browser-test/rename.tsx
new file mode 100644
index 0000000000..26d8de542d
--- /dev/null
+++ b/apps/web/src/features/block-database/browser-test/rename.tsx
@@ -0,0 +1,67 @@
+import '@app/index.css';
+import { queryClient } from '@queries/client';
+import { useDatabaseDetailQuery } from '@queries/storage/databases';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { okAsync } from 'neverthrow';
+import { Show, Suspense } from 'solid-js';
+import { render } from 'solid-js/web';
+import { DatabaseProvider } from '../../database/context/database';
+import { DatabaseRecords } from '../../database/views/database-records';
+import { createMacroDatabaseApi, editorTable } from '../queries/editor-api';
+
+// Real schema query, mutation adapter, controller and headers; only row reads
+// are local. Playwright intercepts the schema service to control response order.
+function RenameFixture() {
+ const detail = useDatabaseDetailQuery(() => 'db');
+ const table = () =>
+ detail.isSuccess ? editorTable(detail.data.tables[0]) : undefined;
+ const view = {
+ query: { filter: null },
+ layout: { kind: 'table' as const, columns: [] },
+ };
+ return (
+ <main class="flex h-screen flex-col bg-panel text-ink">
+ <div class="p-4 text-lg">Planning</div>
+ <Show when={table()}>
+ {(_schema) => (
+ <DatabaseProvider
+ api={createMacroDatabaseApi('db', queryClient)}
+ tableId="tasks"
+ view={view}
+ capabilities={{ editRows: true, editColumns: true }}
+ data={{
+ table,
+ rows: {
+ columns: () => table()?.columns ?? [],
+ snapshot: () => ({
+ rows: [{ rowId: 'one', cells: { name: 'First task' } }],
+ retained: [],
+ version: table()?.version,
+ }),
+ loading: () => false,
+ refreshing: () => false,
+ error: () => undefined,
+ refresh: () => okAsync(undefined),
+ addOption: () => okAsync(undefined),
+ retain: () => {},
+ write: () => okAsync({ insertedRowIds: [], version: 1 }),
+ },
+ }}
+ >
+ <DatabaseRecords view={view} stored={false} />
+ </DatabaseProvider>
+ )}
+ </Show>
+ </main>
+ );
+}
+render(
+ () => (
+ <QueryClientProvider client={queryClient}>
+ <Suspense fallback="Loading schema…">
+ <RenameFixture />
+ </Suspense>
+ </QueryClientProvider>
+ ),
+ document.getElementById('root')!
+);
diff --git a/apps/web/src/features/block-database/queries/detail-cache.ts b/apps/web/src/features/block-database/queries/detail-cache.ts
index def06e0b4c..77bd154cc2 100644
--- a/apps/web/src/features/block-database/queries/detail-cache.ts
+++ b/apps/web/src/features/block-database/queries/detail-cache.ts
@@ -19,20 +19,30 @@ import type { DatabaseOpFailure } from '../../database/core/write-failure';
*/
export async function patchDetail(
databaseId: string,
- change: (detail: DatabaseDetail) => DatabaseDetail
+ change: (detail: DatabaseDetail) => DatabaseDetail,
+ client: QueryClient = queryClient,
+ /** Restore only this change when unrelated cached edits must survive. */
+ restore?: (
+ current: DatabaseDetail,
+ previous: DatabaseDetail
+ ) => DatabaseDetail
): Promise<() => void> {
const queryKey = databasesKeys.detail(databaseId).queryKey;
- await queryClient.cancelQueries({ queryKey, exact: true });
- const previous = queryClient.getQueryData<DatabaseDetail>(queryKey);
- const optimistic = queryClient.setQueryData<DatabaseDetail>(
+ await client.cancelQueries({ queryKey, exact: true });
+ const previous = client.getQueryData<DatabaseDetail>(queryKey);
+ const optimistic = client.setQueryData<DatabaseDetail>(
queryKey,
(current) => current && change(current)
);
return () => {
// Never restore a snapshot over a newer edit or server read.
- if (previous && queryClient.getQueryData(queryKey) === optimistic)
- queryClient.setQueryData(queryKey, previous);
- queryClient.invalidateQueries({ queryKey });
+ if (previous)
+ client.setQueryData<DatabaseDetail>(queryKey, (current) => {
+ if (!current) return current;
+ if (restore) return restore(current, previous);
+ return current === optimistic ? previous : current;
+ });
+ client.invalidateQueries({ queryKey });
};
}
diff --git a/apps/web/src/features/block-database/queries/editor-api.test.ts b/apps/web/src/features/block-database/queries/editor-api.test.ts
new file mode 100644
index 0000000000..4a310c228b
--- /dev/null
+++ b/apps/web/src/features/block-database/queries/editor-api.test.ts
@@ -0,0 +1,137 @@
+import type { DatabaseOp } from '@core/database-sql/generated/types';
+import { queryClient } from '@queries/client';
+import { databasesKeys } from '@queries/storage/keys';
+import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';
+import { errAsync, okAsync, ResultAsync } from 'neverthrow';
+import { afterEach, expect, it, vi } from 'vitest';
+import { RENAME_DETAIL } from '../browser-test/rename-data';
+import { createMacroDatabaseApi } from './editor-api';
+
+const service = vi.hoisted(() => ({ applyOps: vi.fn(), get: vi.fn() }));
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { databases: service },
+}));
+vi.mock('@queries/database-sql/create-database-sql-query', () => ({
+ readDatabaseSql: vi.fn(),
+}));
+vi.mock('@queries/client', async () => {
+ const { QueryClient } = await import('@tanstack/solid-query');
+ return {
+ queryClient: new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ }),
+ };
+});
+const KEY = databasesKeys.detail('db').queryKey;
+const OPS: DatabaseOp[] = [
+ {
+ kind: 'column',
+ table: 'tasks',
+ column: 'name',
+ change: { kind: 'rename', name: 'Task', previousName: 'Name' },
+ },
+];
+const cachedName = () =>
+ queryClient.getQueryData<DatabaseDetail>(KEY)?.tables[0].columns[0].column
+ .display_name;
+afterEach(() => {
+ queryClient.clear();
+ vi.resetAllMocks();
+});
+
+it('cancels an older schema read and shows the new column name before the response', async () => {
+ queryClient.setQueryData(KEY, RENAME_DETAIL);
+ let releaseRead!: (detail: DatabaseDetail) => void;
+ const reading = queryClient.fetchQuery({
+ queryKey: KEY,
+ staleTime: 0,
+ queryFn: () =>
+ new Promise<DatabaseDetail>((resolve) => {
+ releaseRead = resolve;
+ }),
+ });
+ let releaseWrite!: () => void;
+ const submitted = new Promise<void>((resolveSubmitted) => {
+ service.applyOps.mockImplementation(() => {
+ expect(cachedName()).toBe('Task');
+ resolveSubmitted();
+ return ResultAsync.fromSafePromise(
+ new Promise<void>((resolve) => {
+ releaseWrite = resolve;
+ })
+ ).map(() => ({ results: [], changes: [] }));
+ });
+ });
+ const api = createMacroDatabaseApi('db', queryClient);
+ const writing = api.applyOps({ ops: OPS });
+ await submitted;
+ expect(await reading).toEqual(RENAME_DETAIL);
+ releaseRead(RENAME_DETAIL);
+ releaseWrite();
+ expect((await writing).isOk()).toBe(true);
+ expect(cachedName()).toBe('Task');
+});
+
+it('restores the previous schema when a rename is refused', async () => {
+ queryClient.setQueryData(KEY, RENAME_DETAIL);
+ service.applyOps.mockImplementation(() => {
+ expect(cachedName()).toBe('Task');
+ return errAsync([{ code: 'FORBIDDEN', refusal: null, message: 'Refused' }]);
+ });
+ const result = await createMacroDatabaseApi('db', queryClient).applyOps({
+ ops: OPS,
+ });
+ expect(result.isErr()).toBe(true);
+ expect(cachedName()).toBeNull();
+});
+
+it('keeps a newer cached edit when an older rename is refused', async () => {
+ queryClient.setQueryData(KEY, RENAME_DETAIL);
+ service.applyOps.mockImplementation(() => {
+ queryClient.setQueryData(
+ KEY,
+ (current: DatabaseDetail | undefined) =>
+ current && {
+ ...current,
+ database: { ...current.database, name: 'Roadmap' },
+ }
+ );
+ return errAsync([{ code: 'CONFLICT', refusal: null, message: 'Refused' }]);
+ });
+ await createMacroDatabaseApi('db', queryClient).applyOps({ ops: OPS });
+ expect(queryClient.getQueryData<DatabaseDetail>(KEY)?.database.name).toBe(
+ 'Roadmap'
+ );
+ expect(cachedName()).toBeNull();
+});
+
+it('does not undo a newer column rename when an older request is refused', async () => {
+ queryClient.setQueryData(KEY, RENAME_DETAIL);
+ service.applyOps.mockImplementation(() => {
+ queryClient.setQueryData(
+ KEY,
+ (current: DatabaseDetail | undefined) =>
+ current && {
+ ...current,
+ tables: current.tables.map((table) => ({
+ ...table,
+ columns: table.columns.map((column) => ({
+ ...column,
+ column: { ...column.column, display_name: 'Latest' },
+ })),
+ })),
+ }
+ );
+ return errAsync([{ code: 'CONFLICT', refusal: null, message: 'Refused' }]);
+ });
+ await createMacroDatabaseApi('db', queryClient).applyOps({ ops: OPS });
+ expect(cachedName()).toBe('Latest');
+});
+
+it('sends other operations without cancelling schema reads', async () => {
+ const cancel = vi.spyOn(queryClient, 'cancelQueries');
+ service.applyOps.mockReturnValue(okAsync({ results: [], changes: [] }));
+ await createMacroDatabaseApi('db', queryClient).applyOps({ ops: [] });
+ expect(cancel).not.toHaveBeenCalled();
+ cancel.mockRestore();
+});
diff --git a/apps/web/src/features/block-database/queries/editor-api.ts b/apps/web/src/features/block-database/queries/editor-api.ts
index c963ff547d..dc6ebe9fa0 100644
--- a/apps/web/src/features/block-database/queries/editor-api.ts
+++ b/apps/web/src/features/block-database/queries/editor-api.ts
@@ -15,8 +15,9 @@ import type {
import { gridRows } from '../../database/core/grid-cells';
import { allRecordsView } from '../../database/core/views';
import type { DatabaseReadFailure } from '../../database/core/write-failure';
+import { toViewColumn } from '../../database/queries/column-detail';
import { rowsByIdStatement } from '../sql';
-import { toViewColumn } from './table-rows';
+import { patchDetail } from './detail-cache';
export function editorTable(table: TableDetail): DatabaseTableSchema {
return {
@@ -82,9 +83,77 @@ export function createMacroDatabaseApi(
);
}
),
- applyOps: ({ ops, baseVersions }) =>
- applyDatabaseOps(databaseId, ops, baseVersions).map((results) => ({
- results,
- })),
+ applyOps: ({ ops, baseVersions }) => {
+ const renames = ops.flatMap((op) =>
+ op.kind === 'column' && op.change.kind === 'rename'
+ ? [{ table: op.table, column: op.column, name: op.change.name }]
+ : []
+ );
+ const apply = () => applyDatabaseOps(databaseId, ops, baseVersions);
+ if (!renames.length) return apply().map((results) => ({ results }));
+ return ResultAsync.fromSafePromise(
+ patchDetail(
+ databaseId,
+ (detail) => ({
+ ...detail,
+ tables: detail.tables.map((table) => ({
+ ...table,
+ columns: table.columns.map((column) => {
+ let name = column.column.display_name;
+ for (const op of renames)
+ if (
+ op.table === table.table.id &&
+ op.column === column.column.id
+ )
+ name = op.name;
+ return name === column.column.display_name
+ ? column
+ : {
+ ...column,
+ column: { ...column.column, display_name: name },
+ };
+ }),
+ })),
+ }),
+ client,
+ (current, previous) => ({
+ ...current,
+ tables: current.tables.map((table) => ({
+ ...table,
+ columns: table.columns.map((column) => {
+ const rename = renames.findLast(
+ (op) =>
+ op.table === table.table.id &&
+ op.column === column.column.id
+ );
+ if (!rename || column.column.display_name !== rename.name)
+ return column;
+ const before = previous.tables
+ .find((entry) => entry.table.id === table.table.id)
+ ?.columns.find(
+ (entry) => entry.column.id === column.column.id
+ );
+ return before
+ ? {
+ ...column,
+ column: {
+ ...column.column,
+ display_name: before.column.display_name,
+ },
+ }
+ : column;
+ }),
+ })),
+ })
+ )
+ ).andThen((rollback) =>
+ apply()
+ .map((results) => ({ results }))
+ .mapErr((failure) => {
+ rollback();
+ return failure;
+ })
+ );
+ },
};
}
diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.md
index 1264bfe329..e6b51c1128 100644
--- a/docs/agent-guide/databases.md
+++ b/docs/agent-guide/databases.md
@@ -157,7 +157,10 @@ puts the typing cursor in that column's first cell, without waiting for creation
or renaming to finish. Escape keeps the default name.
There is no creation dialog. Double-click a header, press F2 while it is focused,
or choose **Rename column** from its arrow or right-click menu to rename it later.
-Its type icon stays in place while editing. SQL refers to tables and columns by
+Its type icon stays in place while editing. A rename updates the cached column
+label before the save finishes and keeps the same header mounted; the old name
+must not flash back while the schema refreshes. Reload to confirm it persisted.
+SQL refers to tables and columns by
their display names (double-quoted), so a rename changes the name a saved query
must use.