Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(documents): embed editable databases inline (#7866)
Wolf Mermelstein5be720173e63
diff --git a/apps/web/src/features/block-database/browser-test/document-data.ts b/apps/web/src/features/block-database/browser-test/document-data.tsnew file mode 100644index 0000000000..29feb73ae4--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/document-data.ts@@ -0,0 +1,64 @@+import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';++export const databaseId = '01990000-0000-7000-8000-00000000d001';+export const tableId = '01990000-0000-7000-8000-00000000a001';+export const columnId = '01990000-0000-7000-8000-00000000c001';+export const definitionId = '01990000-0000-7000-8000-00000000f001';+export const rowId = '01990000-0000-7000-8000-00000000e001';++export function documentDatabaseDetail(): DatabaseDetail {+ return {+ database: {+ id: databaseId,+ name: 'Launch tasks',+ owner_id: 'macro|[email protected]',+ created_at: '2026-10-09T00:00:00Z',+ trashed_at: null,+ },+ grant: 'owner',+ tables: [+ {+ table: {+ id: tableId,+ database_id: databaseId,+ name: 'Tasks',+ position: '80',+ version: 1,+ },+ sql_name: '"Launch tasks"."Tasks"',+ views: [],+ columns: [+ {+ column: {+ id: columnId,+ table_id: tableId,+ property_definition_id: definitionId,+ position: '80',+ config: null,+ display_name: null,+ infer_type: false,+ },+ sql_name: '"Name"',+ writable: true,+ shared_outside_database: false,+ definition: {+ definition: {+ id: definitionId,+ display_name: 'Name',+ data_type: 'STRING',+ owner: { scope: 'database', database_id: databaseId },+ is_multi_select: false,+ specific_entity_type: null,+ is_system: false,+ is_metadata: false,+ created_at: '',+ updated_at: '',+ },+ property_options: [],+ },+ },+ ],+ },+ ],+ };+}diff --git a/apps/web/src/features/block-database/browser-test/document.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/document.browser.e2e.tsnew file mode 100644index 0000000000..02c26e4cbe--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/document.browser.e2e.ts@@ -0,0 +1,357 @@+import { expect, type Page, test, type WebSocketRoute } from '@playwright/test';+import { allRecordsView } from '../../database/core/views';+import {+ columnId,+ databaseId,+ definitionId,+ documentDatabaseDetail,+ rowId,+ tableId,+} from './document-data';++test.afterEach(async ({ page }) => {+ await page.unrouteAll({ behavior: 'ignoreErrors' });+});++async function fixture(page: Page, multipleTables = false) {+ let storedName = 'Finish onboarding';+ let writes = 0;+ let creates = 0;+ const detail = documentDatabaseDetail();+ if (multipleTables) {+ const next = structuredClone(detail.tables[0]);+ next.table.id = tableId.replace(/1$/, '2');+ next.table.name = 'Contacts and customer research';+ next.views = [+ {+ ...allRecordsView(next.table),+ id: '01990000-0000-7000-8000-00000000b001',+ name: 'Research',+ },+ ];+ for (const column of next.columns) {+ column.column.id = column.column.id.replace(/1$/, '2');+ column.column.table_id = next.table.id;+ }+ detail.tables.push(next);+ }+ const externalRows: string[] = [];+ let gateway: WebSocketRoute | undefined;+ const tracking: { action: string; entity_id: string }[] = [];+ const errors: string[] = [];+ page.on('pageerror', (error) => {+ errors.push(error.message);+ console.error(error);+ });+ await page.routeWebSocket('**', (socket) => {+ if (!socket.url().includes('connection-gateway')) {+ socket.close();+ return;+ }+ gateway = socket;+ socket.onMessage((message) => {+ if (message === 'ping') socket.send('pong');+ else tracking.push(JSON.parse(message.toString()));+ });+ });+ await page.route('https://**', (route) => route.abort());+ // Serve the fixture's module graph through Playwright's request context.+ // Chromium otherwise cancels local module loads when host interfaces change.+ await page.route(/^http:\/\/localhost:\d+\//, async (route) => {+ await route.fulfill({ response: await route.fetch({ maxRetries: 2 }) });+ });+ await page.route('**/__macro_dev/**', async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ if (url.pathname.endsWith('/items/soup/graphql')) {+ await route.fulfill({+ json: {+ data: {+ user: {+ soup: {+ nextCursor: null,+ items: [storedName, ...externalRows].map((name, index) => ({+ __typename: 'GraphqlSoupDatabaseRow',+ id: index+ ? `${rowId.slice(0, -4)}${String(index + 1).padStart(4, '0')}`+ : rowId,+ tableId,+ position: '80',+ ownerId: detail.database.owner_id,+ createdAt: detail.database.created_at,+ updatedAt: detail.database.created_at,+ cacheProjection: null,+ notifications: [],+ properties: [+ {+ id: definitionId,+ propertyDefinitionId: definitionId,+ value: {+ __typename: 'GraphqlStringPropertyValue',+ stringValue: name,+ },+ },+ ],+ })),+ },+ },+ },+ },+ });+ return;+ }+ if (url.pathname.endsWith('/databases') && request.method() === 'POST') {+ creates++;+ await route.fulfill({ json: { id: databaseId } });+ return;+ }+ if (url.pathname.endsWith(`/databases/${databaseId}/ops`)) {+ const body = request.postDataJSON();+ const change = body.ops.find(+ (op: { kind: string }) => op.kind === 'rows'+ )?.change;+ if (change?.kind === 'update') {+ storedName = change.changes.rows[0].cells.find(+ (cell: { column: string }) => cell.column === columnId+ ).value.value;+ }+ writes++;+ detail.tables[0].table.version++;+ await route.fulfill({+ json: {+ results: [+ {+ kind: 'rows',+ table: tableId,+ tableVersion: detail.tables[0].table.version,+ change: { kind: 'updated', affected: 1 },+ },+ ],+ changes: [+ {+ table: tableId,+ version: detail.tables[0].table.version,+ change: writes,+ },+ ],+ },+ });+ return;+ }+ if (url.pathname.endsWith(`/databases/${databaseId}`)) {+ await route.fulfill({ json: detail });+ return;+ }+ await route.fulfill({ json: [] });+ });+ await page.goto('/src/features/block-database/browser-test/document.html');+ return {+ tracking,+ addExternalRows: (names: string[]) => {+ externalRows.push(...names);+ detail.tables[0].table.version++;+ gateway?.send(+ JSON.stringify({+ type: 'database_table_changed',+ data: {+ databaseId,+ tableId,+ version: detail.tables[0].table.version,+ },+ })+ );+ },+ storedName: () => storedName,+ writes: () => writes,+ creates: () => creates,+ errors,+ };+}++test('a compact database mention expands to the live editor, saves cells and collapses without losing the reference', async ({+ page,+}) => {+ const saved = await fixture(page);+ await page.getByRole('button', { name: 'Mention existing database' }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ const grid = page.getByRole('grid', { name: 'Tasks' });+ await expect(grid).toBeVisible();+ await page+ .getByRole('button', { name: /^Name: Finish onboarding\./ })+ .dblclick();+ const input = page.getByRole('textbox', { name: 'Edit Name' });+ await input.fill('Ready to launch');+ await input.press('Tab');+ await expect.poll(saved.storedName).toBe('Ready to launch');+ await expect.poll(saved.writes).toBe(1);+ await page.getByRole('button', { name: 'Collapse', exact: true }).click();+ await expect(grid).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: 'Expand database' })+ ).toBeVisible();+ await expect(page.getByLabel('Document state')).toContainText(+ 'document-mention'+ );+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(grid).toBeVisible();+ await expect(+ page.getByRole('button', { name: /^Name: Ready to launch\./ })+ ).toBeVisible();+ await expect(page.getByLabel('Document state')).toContainText('Launch plan');+ expect(saved.creates()).toBe(0);+ expect(saved.errors).toEqual([]);+});++test('embedded tables subscribe to the gateway and display externally added rows without reloading', async ({+ page,+}) => {+ const saved = await fixture(page);+ await page.getByRole('button', { name: 'Mention existing database' }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ await expect+ .poll(() => saved.tracking.filter((event) => event.action === 'open'))+ .toContainEqual(expect.objectContaining({ entity_id: databaseId }));+ saved.addExternalRows(['Alpha widget', 'Juliet flux capacitor']);+ await expect(+ page.getByRole('button', { name: /^Name: Alpha widget\./ })+ ).toBeVisible();+ await expect(+ page.getByRole('button', { name: /^Name: Juliet flux capacitor\./ })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Collapse', exact: true }).click();+ await expect+ .poll(() => saved.tracking.filter((event) => event.action === 'close'))+ .toContainEqual(expect.objectContaining({ entity_id: databaseId }));+ expect(saved.errors).toEqual([]);+});++test('the shared toolbar changes inline filters and sorting without writing the saved view', async ({+ page,+}) => {+ const saved = await fixture(page);+ await page.getByRole('button', { name: 'Mention existing database' }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ await page.getByRole('button', { name: 'Sort', exact: true }).click();+ await page.getByRole('button', { name: 'Add sort', exact: true }).click();+ await page.getByRole('button', { name: /^Sort direction/ }).click();+ await page.getByRole('option', { name: 'Descending', exact: true }).click();+ await page.getByRole('button', { name: 'Close sort' }).click();+ await expect(page.getByRole('button', { name: 'Sort 1' })).toBeFocused();+ await page.getByRole('button', { name: 'Filter', exact: true }).click();+ await page.getByRole('button', { name: 'Add condition' }).click();+ await page.getByRole('textbox', { name: 'Filter value' }).fill('Finish');+ await page.getByRole('button', { name: 'Close filter' }).click();+ await expect(page.getByRole('button', { name: 'Filter 1' })).toBeFocused();+ await page.getByRole('button', { name: 'Sort 1' }).click();+ await expect(+ page.getByRole('button', { name: /^Sort direction/ })+ ).toContainText('Descending');+ await page.getByRole('button', { name: 'Close sort' }).click();+ await page.setViewportSize({ width: 375, height: 800 });+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(+ 375+ );+ await page.screenshot({ path: '/tmp/database-shared-toolbar-mobile.png' });+ expect(saved.writes()).toBe(0);+ expect(saved.errors).toEqual([]);+});++test('the app table picker switches tables with the keyboard and restores focus when dismissed', async ({+ page,+}) => {+ const saved = await fixture(page, true);+ await page.getByRole('button', { name: 'Mention existing database' }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ const picker = page.getByRole('button', { name: /^Database table/ });+ await picker.click();+ await expect(page.getByRole('listbox')).toBeVisible();+ await picker.press('Escape');+ await expect(picker).toBeFocused();+ await picker.press('ArrowDown');+ await page+ .getByRole('option', { name: 'Tasks', exact: true })+ .press('ArrowDown');+ await page.keyboard.press('Enter');+ await expect(+ page.getByRole('grid', { name: 'Contacts and customer research' })+ ).toBeVisible();+ await expect(page.getByLabel('Document state')).toContainText(+ tableId.replace(/1$/, '2')+ );+ await expect(picker).toBeFocused();+ const views = page.getByRole('button', { name: /^Database view / });+ await views.click();+ await page.getByRole('option', { name: 'Research', exact: true }).click();+ await expect(views).toBeFocused();+ await expect(page.getByLabel('Document state')).toContainText(+ '01990000-0000-7000-8000-00000000b001'+ );+ await page.getByRole('button', { name: 'Collapse', exact: true }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(picker).toContainText('Contacts and customer research');+ await expect(views).toContainText('Research');+ expect(saved.errors).toEqual([]);+});++test('slash database creates an expanded editor and slash query inserts the existing query node', async ({+ page,+}) => {+ const saved = await fixture(page);+ await page.getByText('Launch plan', { exact: true }).click();+ await page.keyboard.press('Control+End');+ await page.keyboard.type('/database');+ await page.getByText('Database', { exact: true }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ expect(saved.creates()).toBe(1);+ await page.getByText('Launch plan', { exact: true }).click();+ await page.keyboard.press('Control+End');+ await page.keyboard.type('/query');+ await page.getByText('Query', { exact: true }).click();+ await expect(page.getByLabel('Document state')).toContainText(+ 'database-query'+ );+ expect(saved.creates()).toBe(1);+ expect(saved.errors).toEqual([]);+});++test('database permissions control edits independently of the document', async ({+ page,+}) => {+ const saved = await fixture(page);+ await page.getByRole('button', { name: 'Mention existing database' }).click();+ await page.getByRole('button', { name: 'Expand database' }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ await page.getByRole('button', { name: 'Toggle document editing' }).click();+ await page+ .getByRole('button', { name: /^Name: Finish onboarding\./ })+ .dblclick();+ const input = page.getByRole('textbox', { name: 'Edit Name' });+ await input.fill('Edited through a read-only document');+ await input.press('Tab');+ await expect+ .poll(saved.storedName)+ .toBe('Edited through a read-only document');+ await page.getByRole('button', { name: 'Collapse', exact: true }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toHaveCount(0);+ await expect(page.getByLabel('Document state')).toContainText(+ 'document-card'+ );+ await page.getByRole('button', { name: 'Expand', exact: true }).click();+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();+ await page.getByRole('button', { name: 'Database viewer' }).click();+ await expect(page.getByText('Read only', { exact: true })).toBeVisible();+ await expect(+ page.getByRole('button', { name: 'Add column', exact: true })+ ).toHaveCount(0);+ await page+ .getByRole('button', {+ name: /^Name: Edited through a read-only document$/,+ })+ .dblclick();+ await expect(page.getByRole('textbox', { name: 'Edit Name' })).toHaveCount(0);+ expect(saved.writes()).toBe(1);+ expect(saved.errors).toEqual([]);+});diff --git a/apps/web/src/features/block-database/browser-test/document.html b/apps/web/src/features/block-database/browser-test/document.htmlnew file mode 100644index 0000000000..9fcc085848--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/document.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8" /><title>Database in a document</title></head>+ <body><div id="root"></div><script type="module" src="./document.tsx"></script></body>+</html>diff --git a/apps/web/src/features/block-database/browser-test/document.tsx b/apps/web/src/features/block-database/browser-test/document.tsxnew file mode 100644index 0000000000..e02bdbbbd7--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/document.tsx@@ -0,0 +1,162 @@+import '@app/index.css';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';+import { DatabaseCard } from '@core/component/LexicalMarkdown/component/decorator/DatabaseCard';+import { DatabaseQuery } from '@core/component/LexicalMarkdown/component/decorator/DatabaseQuery';+import { DocumentMention } from '@core/component/LexicalMarkdown/component/decorator/DocumentMention';+import { ActionMenu } from '@core/component/LexicalMarkdown/component/menu/ActionsMenu';+import {+ createLexicalWrapper,+ LexicalWrapperContext,+} from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';+import { actionsPlugin } from '@core/component/LexicalMarkdown/plugins/actions/actionsPlugin';+import { blockDecoratorNavigationPlugin } from '@core/component/LexicalMarkdown/plugins/block-decorator-navigation';+import {+ INSERT_DOCUMENT_MENTION_COMMAND,+ mentionsPlugin,+} from '@core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin';+import { selectionDataPlugin } from '@core/component/LexicalMarkdown/plugins/selection-data/selectionDataPlugin';+import { createMenuOperations } from '@core/component/LexicalMarkdown/shared/inlineMenu';+import { UserContextProvider } from '@core/context/user';+import { registerRichText } from '@lexical/rich-text';+import {+ DatabaseQueryNode,+ DocumentCardNode,+ DocumentMentionNode,+ setDecorator,+} from '@macro-inc/lexical-core';+import { authKeys } from '@queries/auth/keys';+import { queryClient } from '@queries/client';+import { contactsKeys } from '@queries/contacts/keys';+import { databasesKeys } from '@queries/storage/keys';+import { QueryClientProvider } from '@tanstack/solid-query';+import { $createParagraphNode, $createTextNode, $getRoot } from 'lexical';+import { createSignal, onCleanup, onMount } from 'solid-js';+import { render } from 'solid-js/web';+import { databaseId, documentDatabaseDetail } from './document-data';++setDecorator(DocumentCardNode, DatabaseCard);+setDecorator(DocumentMentionNode, DocumentMention);+setDecorator(DatabaseQueryNode, DatabaseQuery);+queryClient.setDefaultOptions({+ queries: { retry: false, staleTime: Infinity },+});+queryClient.setQueryData(+ databasesKeys.detail(databaseId).queryKey,+ documentDatabaseDetail()+);+queryClient.setQueryData(contactsKeys.all.queryKey, { contacts: [] });+queryClient.setQueryData(authKeys.userInfo.queryKey, {+ id: 'macro|[email protected]',+ authenticated: true,+ permissions: [],+});++function DocumentFixture() {+ const wrapper = createLexicalWrapper({+ type: 'markdown',+ namespace: 'database-document-fixture',+ isInteractable: () => true,+ });+ const editor = wrapper.editor;+ const menu = createMenuOperations();+ const [state, setState] = createSignal('');+ const [readOnly, setReadOnly] = createSignal(false);+ let root!: HTMLDivElement;+ wrapper.plugins.use(selectionDataPlugin(wrapper));+ wrapper.plugins.use(mentionsPlugin({}));+ wrapper.plugins.use(actionsPlugin({ menu }));+ wrapper.plugins.use(blockDecoratorNavigationPlugin());+ const stopRichText = registerRichText(editor);+ const stopUpdate = editor.registerUpdateListener(({ editorState }) => {+ setState(JSON.stringify(editorState.toJSON()));+ });+ onCleanup(() => {+ stopRichText();+ stopUpdate();+ wrapper.cleanup();+ });+ onMount(() => {+ editor.setRootElement(root);+ editor.update(() => {+ $getRoot().append(+ $createParagraphNode().append($createTextNode('Launch plan')),+ $createParagraphNode()+ );+ $getRoot().selectEnd();+ });+ });+ return (+ <LexicalWrapperContext.Provider value={wrapper}>+ <main class="min-h-screen bg-page p-8 text-ink">+ <div class="mb-4 flex gap-3">+ <button+ onClick={() => {+ editor.focus(() =>+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: databaseId,+ documentName: 'Launch tasks',+ blockName: 'database',+ })+ );+ }}+ >+ Mention existing database+ </button>+ <button+ onClick={() => {+ setReadOnly(!readOnly());+ editor.setEditable(!readOnly());+ }}+ >+ Toggle document editing+ </button>+ <button+ onClick={() => {+ queryClient.setQueryData(+ databasesKeys.detail(databaseId).queryKey,+ { ...documentDatabaseDetail(), grant: 'view' }+ );+ }}+ >+ Database viewer+ </button>+ </div>+ <div class="relative mx-auto max-w-4xl">+ <div+ ref={root}+ contentEditable+ role="textbox"+ aria-label="Document"+ class="min-h-40 outline-none"+ />+ <DecoratorRenderer editor={editor} />+ <ActionMenu+ editor={editor}+ menu={menu}+ actionContext={{ disableMentionTracking: true }}+ />+ </div>+ <output aria-label="Document state" class="sr-only">+ {state()}+ </output>+ </main>+ </LexicalWrapperContext.Provider>+ );+}++render(+ () => (+ <AnalyticsContextProvider>+ <PosthogProvider>+ <QueryClientProvider client={queryClient}>+ <UserContextProvider>+ <DocumentFixture />+ </UserContextProvider>+ </QueryClientProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ ),+ document.getElementById('root')!+);diff --git a/apps/web/src/features/block-database/component/DatabaseGrid.tsx b/apps/web/src/features/block-database/component/DatabaseGrid.tsxindex eb6d7061b5..6eb4e10f3c 100644--- a/apps/web/src/features/block-database/component/DatabaseGrid.tsx+++ b/apps/web/src/features/block-database/component/DatabaseGrid.tsx@@ -58,6 +58,7 @@ import {} from '../queries/columns';import { createDatabaseRelations } from '../queries/database-relations';import { useRelatedDatabaseSync } from '../queries/database-relations-sync';+import { useDatabaseSubscription } from '../queries/database-subscription';import { createMacroDatabaseApi, editorTable } from '../queries/editor-api';import { useFormsAskingColumns } from '../queries/forms-usage';import { deleteDatabaseOption, updateDatabaseOption } from '../queries/options';@@ -71,6 +72,8 @@ import {} from '../queries/views';export type DatabaseGridProps = {+ /** Host framing for the records area, below the toolbar. */+ contentClass?: string;databaseId: string;table: TableDetail;canEdit: boolean;@@ -195,7 +198,11 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {tableChangesOf({ databaseId, tableId: props.tableId, readRows }),onTableChanged: (listener) => {useDatabaseTableChanges((change) => {- if (change.tableId !== props.tableId) return;+ if (+ change.databaseId !== databaseId ||+ change.tableId !== props.tableId+ )+ return;listener(change.version);if (props.stored && props.view.layout.kind === 'board')void refreshCardPositions(databaseId, props.view.id);@@ -232,6 +239,9 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {}),relations);+ // Embedded grids have no database BlockContainer to subscribe for them.+ // Tracking is reference-counted across grids and full database blocks.+ useDatabaseSubscription(databaseId, () => refreshInBackground(source));const boardViewId = () =>props.stored && props.view.layout.kind === 'board'? props.view.id@@ -314,7 +324,10 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {inferNewColumns><DatabaseRecords- contentClass="mx-4 mb-4 mt-1 rounded-xl border border-edge-muted"+ contentClass={+ props.contentClass ??+ 'mx-4 mb-4 mt-1 rounded-xl border border-edge-muted'+ }view={props.view}stored={props.stored}preparingView={props.preparingView}diff --git a/apps/web/src/features/block-database/document-database.tsx b/apps/web/src/features/block-database/document-database.tsxnew file mode 100644index 0000000000..f1ee8f442b--- /dev/null+++ b/apps/web/src/features/block-database/document-database.tsx@@ -0,0 +1,290 @@+import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';+import { toast } from '@core/component/Toast/Toast';+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';+import DatabaseIcon from '@phosphor/database.svg';+import {+ onDatabaseBatchCommitted,+ undoDatabaseChange,+ useDatabaseDetailQuery,+} from '@queries/storage/databases';+import { useDatabaseTableChangedSync } from '@queries/storage/databases-sync';+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import { getEntityGraphqlClient } from '@service-storage/graphql-soup';+import { Button, Tooltip } from '@ui';+import { createMemo, createSignal, onCleanup, Show } from 'solid-js';+import { DatabaseEditorToolbar } from '../database/components/database-editor-toolbar';+import { DatabaseTitle } from '../database/components/database-title';+import { ViewSelect } from '../database/components/view-select';+import type { DatabaseRelatedDestination } from '../database/core/database-relations';+import type { ViewChange } from '../database/core/view-state';+import { allRecordsView } from '../database/core/views';+import { databaseEntityMessage } from '../database/core/write-failure';+import { createDatabaseUndo } from '../database/primitives/undo-controller';+import type { DatabaseRecordsActions } from '../database/views/database-records-view';+import { DatabaseGrid } from './component/DatabaseGrid';+import { renameDatabase } from './queries/rename-database';+import { toViewColumn } from './queries/table-rows';++/** The Macro database editor hosted in markdown, without a nested app block. */+export function DocumentDatabase(props: {+ databaseId: string;+ name: string;+ params?: Record<string, string>;+ collapsed?: boolean;+ onToggle: () => void;+ onLocationChange?: (params: Record<string, string>) => void;+}) {+ const databaseId = props.databaseId;+ const [recordActions, setRecordActions] =+ createSignal<DatabaseRecordsActions>();+ useDatabaseTableChangedSync(() => databaseId);+ const detail = useDatabaseDetailQuery(() => databaseId);+ const location = () => props.params ?? {};+ const [changedViews, setChangedViews] = createSignal<+ Record<string, DatabaseView>+ >({});+ const tables = () => (detail.isSuccess ? detail.data.tables : []);+ const table = createMemo(() => {+ const id = location().tableId;+ return id ? tables().find((entry) => entry.table.id === id) : tables()[0];+ });+ const canEdit = createMemo(+ () =>+ detail.isSuccess &&+ (detail.data.grant === 'edit' || detail.data.grant === 'owner')+ );+ const name = () =>+ detail.isSuccess ? detail.data.database.name : props.name;+ const baseView = () => {+ const current = table();+ if (!current) return;+ return (+ current.views.find((view) => view.id === location().viewId) ??+ allRecordsView(current.table)+ );+ };+ const view = () => {+ const base = baseView();+ return base && (changedViews()[base.id] ?? base);+ };+ // Filters, sorting and column widths belong to this visit, not the shared view.+ const changeView = (change: ViewChange) => {+ const current = view();+ if (current)+ setChangedViews((views) => ({+ ...views,+ [current.id]: { ...current, ...change },+ }));+ };+ const selectLocation = (next: Record<string, string>) => {+ props.onLocationChange?.(next);+ };+ const open = (+ target: { databaseId: string } & Record<string, string> = {+ databaseId,+ ...location(),+ tableId: table()?.table.id ?? '',+ viewId: view()?.id ?? '',+ }+ ) => openDocument('database', target.databaseId, target, true);+ const openRelated = (target: DatabaseRelatedDestination) => open(target);+ const undo = createDatabaseUndo({+ undoChange: (change) => undoDatabaseChange(databaseId, change),+ onCommitted: (listener) =>+ onCleanup(+ onDatabaseBatchCommitted((batch) => {+ if (batch.databaseId === databaseId)+ listener({+ ops: batch.ops,+ changes: batch.changes.map(({ change }) => change),+ });+ })+ ),+ offer: (label, revert) =>+ toast.success(label, { actions: [{ label: 'Undo', onClick: revert }] }),+ });++ return (+ <section+ aria-label={`Database: ${name()}`}+ contentEditable={false}+ data-lexical-interactive+ class="@container/database my-2 flex min-w-0 flex-col overflow-hidden rounded-lg border border-edge-muted bg-panel text-ink"+ onKeyDown={(event) => {+ // The card's event boundary keeps these out of outer Lexical.+ event.stopPropagation();+ const target = event.target;+ const editable =+ target instanceof Element &&+ target.closest('[contenteditable="true"]');+ const typing =+ target instanceof Element &&+ (target.closest('input, textarea') ||+ (editable && event.currentTarget.contains(editable)));+ if (+ typing ||+ !(event.metaKey || event.ctrlKey) ||+ event.key.toLowerCase() !== 'z'+ )+ return;+ event.preventDefault();+ if (event.shiftKey) void undo.redo();+ else void undo.undo();+ }}+ >+ <div class="flex min-w-0 flex-wrap items-center gap-2 px-3 py-2">+ <DatabaseIcon class="size-4 shrink-0 text-ink-muted" />+ <div class="min-w-0 flex-1">+ <DatabaseTitle+ name={name()}+ canEdit={canEdit() && !props.collapsed}+ onRename={(next) =>+ void renameDatabase(+ getEntityGraphqlClient(),+ databaseId,+ next+ ).mapErr((failure) =>+ toast.failure(databaseEntityMessage(failure, 'rename'))+ )+ }+ />+ </div>+ <Show when={detail.isSuccess && !canEdit()}>+ <span class="text-xs text-ink-muted">Read only</span>+ </Show>+ <Button variant="ghost" size="sm" onClick={() => open()}>+ <ArrowSquareOut class="size-3.5" /> Open+ </Button>+ <Button variant="ghost" size="sm" onClick={props.onToggle}>+ {props.collapsed ? 'Expand' : 'Collapse'}+ </Button>+ </div>+ <Show when={!props.collapsed}>+ <Show+ when={detail.isSuccess}+ fallback={+ <div class="px-3 py-5 text-sm text-ink-muted">+ <Show+ when={detail.isError}+ fallback={<span role="status">Loading database…</span>}+ >+ <p role="alert">+ This database is unavailable. It may have been deleted or you+ may not have access.+ </p>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => void detail.refetch()}+ >+ Retry+ </Button>+ </Show>+ </div>+ }+ >+ <Show+ when={table()}+ fallback={+ <p role="alert" class="px-3 py-5 text-sm text-ink-muted">+ This table no longer exists. Open the database to choose another+ table.+ </p>+ }+ >+ {(shown) => (+ <Show when={view()}>+ {(currentView) => (+ <div class="flex h-96 min-h-0 flex-col border-t border-edge-muted">+ <div class="shrink-0 border-b border-edge-muted">+ <DatabaseEditorToolbar+ columns={shown().columns.map(toViewColumn)}+ view={currentView()}+ onChangeView={changeView}+ onCreateRecord={+ canEdit()+ ? () => void recordActions()?.createRecord()+ : undefined+ }+ canCreateRecord={!!recordActions()}+ creating={recordActions()?.pending()}+ createRecordLabel="New row"+ selection={+ <>+ <Tooltip+ label={shown().table.name}+ class="min-w-0 max-w-40"+ >+ <ViewSelect+ label="Database table"+ class="min-w-0 max-w-40"+ value={shown().table.id}+ options={tables().map(({ table }) => ({+ value: table.id,+ label: table.name,+ }))}+ onChange={(tableId) =>+ selectLocation({+ ...location(),+ tableId,+ viewId: '',+ })+ }+ />+ </Tooltip>+ <Show when={shown().views.length}>+ <Tooltip+ label={currentView().name}+ class="min-w-0 max-w-40"+ >+ <ViewSelect+ label="Database view"+ class="min-w-0 max-w-40"+ value={currentView().id}+ options={[+ allRecordsView(shown().table),+ ...shown().views,+ ].map((view) => ({+ value: view.id,+ label: view.name,+ }))}+ onChange={(viewId) =>+ selectLocation({+ ...location(),+ tableId: shown().table.id,+ viewId,+ })+ }+ />+ </Tooltip>+ </Show>+ </>+ }+ />+ </div>+ <DatabaseGrid+ contentClass="m-3 rounded-lg border border-edge-muted"+ databaseId={databaseId}+ table={shown()}+ canEdit={canEdit()}+ view={currentView()}+ stored={false}+ onViewChange={changeView}+ onClearConstraints={() =>+ changeView({+ query: { ...currentView().query, filter: null },+ })+ }+ onOpenRelated={openRelated}+ actionsRef={setRecordActions}+ />+ </div>+ )}+ </Show>+ )}+ </Show>+ </Show>+ </Show>+ </section>+ );+}diff --git a/apps/web/src/features/block-database/queries/database-relations-sync.ts b/apps/web/src/features/block-database/queries/database-relations-sync.tsindex 2bf22afbff..f58c7c5ddf 100644--- a/apps/web/src/features/block-database/queries/database-relations-sync.ts+++ b/apps/web/src/features/block-database/queries/database-relations-sync.ts@@ -1,6 +1,5 @@-import { invalidateDatabase } from '@queries/storage/databases';import { useDatabaseTableChangedSync } from '@queries/storage/databases-sync';-import { useEntitySubscription } from '@service-connection/client';+import { useDatabaseSubscription } from './database-subscription';/*** Related tables can live outside the open database; retain their gateway@@ -11,11 +10,5 @@ export function useRelatedDatabaseSync(refreshRows: () => void) {useDatabaseTableChangedSync(() => databaseId);- useEntitySubscription(- () => ({ entity_type: 'database', entity_id: databaseId }),- () => {- void invalidateDatabase(databaseId);- refreshRows();- }- );+ useDatabaseSubscription(databaseId, refreshRows);}diff --git a/apps/web/src/features/block-database/queries/database-subscription.ts b/apps/web/src/features/block-database/queries/database-subscription.tsnew file mode 100644index 0000000000..fe3f155fe2--- /dev/null+++ b/apps/web/src/features/block-database/queries/database-subscription.ts@@ -0,0 +1,19 @@+import { invalidateDatabase } from '@queries/storage/databases';+import { useEntitySubscription } from '@service-connection/client';++/**+ * Share gateway tracking and catch up on subscription, reconnect and refocus.+ * Live write notifications reach the source through useDatabaseTableChanges.+ */+export function useDatabaseSubscription(+ databaseId: string,+ refreshRows: () => void+) {+ useEntitySubscription(+ () => ({ entity_type: 'database', entity_id: databaseId }),+ () => {+ void invalidateDatabase(databaseId);+ refreshRows();+ }+ );+}diff --git a/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts b/apps/web/src/features/crm/browser-test/editor.browser.e2e.tsindex 8a31785adf..e5279801b9 100644--- a/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts+++ b/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts@@ -1,10 +1,17 @@import { expect, test } from '@playwright/test';+test.afterEach(async ({ page }) => {+ await page.unrouteAll({ behavior: 'ignoreErrors' });+});+test('the pipeline API powers the shared editor and respects column protections and grants', async ({page,}) => {await page.routeWebSocket('**', (socket) => socket.close());await page.route('https://**', (route) => route.abort());+ await page.route(/^http:\/\/localhost:\d+\//, async (route) => {+ await route.fulfill({ response: await route.fetch({ maxRetries: 2 }) });+ });await page.route('**/__macro_dev/**', (route) => route.abort());// Local container network changes can cancel Vite's initial module requests.// Retry only that startup failure, never an editor interaction.@@ -23,6 +30,10 @@ test('the pipeline API powers the shared editor and respects column protectionstimeout: 30000,});await expect(page.getByText('Acme', { exact: true })).toBeVisible();+ await page.getByRole('button', { name: 'Sort', exact: true }).click();+ await page.getByRole('button', { name: 'Add sort', exact: true }).click();+ await page.getByRole('button', { name: 'Close sort' }).click();+ await expect(page.getByRole('button', { name: 'Sort 1' })).toBeFocused();await page.getByRole('button', { name: /^Notes: Follow up\./ }).dblclick();const editor = page.getByRole('textbox', { name: 'Edit Notes' });await editor.fill('Renew in October');diff --git a/apps/web/src/features/crm/browser-test/editor.tsx b/apps/web/src/features/crm/browser-test/editor.tsxindex bca9ac5145..e3147a4c1d 100644--- a/apps/web/src/features/crm/browser-test/editor.tsx+++ b/apps/web/src/features/crm/browser-test/editor.tsx@@ -8,12 +8,31 @@ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { errAsync, okAsync } from 'neverthrow';import { createSignal } from 'solid-js';import { render } from 'solid-js/web';-import { DatabaseProvider } from '../../database/context/database';-import type { DatabaseViewState } from '../../database/core/view-state';+import { DatabaseEditorToolbar } from '../../database/components/database-editor-toolbar';+import { DatabaseProvider, useDatabase } from '../../database/context/database';+import type {+ DatabaseViewState,+ ViewChange,+} from '../../database/core/view-state';import { DatabaseRecords } from '../../database/views/database-records';import type { Pipeline } from '../core/pipeline';import { createPipelineApi } from '../queries/pipeline-data';+function FixtureToolbar(props: {+ view: DatabaseViewState;+ onChangeView: (change: ViewChange) => void;+}) {+ const database = useDatabase();+ return (+ <DatabaseEditorToolbar+ columns={database.data.rows.columns()}+ view={props.view}+ onChangeView={props.onChangeView}+ selection={<span>Renewals</span>}+ />+ );+}+const id = (n: number) =>`00000000-0000-0000-0000-${String(n).padStart(12, '0')}`;const pipeline: Pipeline = {@@ -201,6 +220,14 @@ function Fixture() {<DatabaseRecordsview={view()}stored={false}+ renderToolbar={() => (+ <FixtureToolbar+ view={view()}+ onChangeView={(change) =>+ setView((current) => ({ ...current, ...change }))+ }+ />+ )}onViewChange={(change) =>setView((view) => ({ ...view, ...change }))}diff --git a/apps/web/src/features/database/components/database-editor-toolbar.tsx b/apps/web/src/features/database/components/database-editor-toolbar.tsxnew file mode 100644index 0000000000..2267ad79e6--- /dev/null+++ b/apps/web/src/features/database/components/database-editor-toolbar.tsx@@ -0,0 +1,145 @@+import CheckIcon from '@phosphor/check.svg';+import FunnelIcon from '@phosphor/funnel.svg';+import PlusIcon from '@phosphor/plus.svg';+import SortAscendingIcon from '@phosphor/sort-ascending.svg';+import StackIcon from '@phosphor/stack.svg';+import { Button } from '@ui/components/Button';+import { Dropdown } from '@ui/components/Dropdown';+import { For, type JSX, Show } from 'solid-js';+import type { DatabaseViewColumn } from '../core/database-view';+import type { DatabaseViewState, ViewChange } from '../core/view-state';+import { boardGroupColumns } from '../core/views';+import { FilterPanel, filterConditionCount } from './database-view-filters';+import { SortPanel } from './sort-panel';+import { ToolbarPopover } from './view-control-popover';++/** Standard editor controls. Hosts supply selection and extra actions as slots. */+export function DatabaseEditorToolbar(props: {+ columns: DatabaseViewColumn[];+ view: DatabaseViewState;+ onChangeView: (change: ViewChange) => void;+ canChangeView?: boolean;+ selection: JSX.Element;+ search?: JSX.Element;+ actions?: JSX.Element;+ onCreateRecord?: () => void;+ canCreateRecord?: boolean;+ creating?: boolean;+ createRecordLabel?: string;+}) {+ const board = () => {+ const layout = props.view.layout;+ return layout.kind === 'board' ? layout : undefined;+ };+ const sort = () => props.view.query.sort ?? [];+ const groupColumns = () => boardGroupColumns(props.columns);+ return (+ <div+ class="@container/view-toolbar shrink-0 bg-canvas-base [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-ink/50"+ data-database-toolbar+ >+ <div class="flex items-center gap-2 px-4 py-1.5 @max-[520px]/view-toolbar:flex-wrap">+ <div class="flex min-w-0 flex-1 items-center gap-0.5 @max-[520px]/view-toolbar:basis-full">+ {props.selection}+ </div>+ <div class="flex shrink-0 items-center gap-0.5 @max-[520px]/view-toolbar:w-full @max-[520px]/view-toolbar:justify-end">+ <Show when={props.canChangeView !== false}>+ <Show when={board()}>+ {(current) => (+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ aria-label="Group board by"+ title="Group by"+ size="icon-md"+ variant="ghost"+ class="h-8 w-auto rounded-md px-2 text-ink-muted hover:bg-hover data-expanded:bg-hover"+ >+ <StackIcon class="size-3.5" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-48">+ <Dropdown.RadioGroup+ value={current().groupBy}+ onChange={(columnId) => {+ if (columnId !== current().groupBy)+ props.onChangeView({+ layout: {+ ...current(),+ groupBy: columnId,+ lanes: [],+ },+ });+ }}+ >+ <For each={groupColumns()}>+ {(column) => (+ <Dropdown.RadioItem closeOnSelect value={column.id}>+ <span class="flex-1">{column.name}</span>+ <Dropdown.ItemIndicator>+ <CheckIcon class="size-3.5 text-accent" />+ </Dropdown.ItemIndicator>+ </Dropdown.RadioItem>+ )}+ </For>+ </Dropdown.RadioGroup>+ </Dropdown.Content>+ </Dropdown>+ )}+ </Show>++ <ToolbarPopover+ label="Filter"+ compact+ count={filterConditionCount(props.view.query.filter)}+ icon={<FunnelIcon class="size-3.5" />}+ >+ <FilterPanel+ columns={props.columns}+ filter={props.view.query.filter}+ onChange={(filter) =>+ props.onChangeView({+ query: { ...props.view.query, filter },+ })+ }+ />+ </ToolbarPopover>+ <ToolbarPopover+ label="Sort"+ compact+ count={sort().length}+ icon={<SortAscendingIcon class="size-3.5" />}+ >+ <SortPanel+ columns={props.columns}+ view={props.view}+ onChange={props.onChangeView}+ />+ </ToolbarPopover>+ </Show>+ {props.search}+ <div class="ml-1 flex shrink-0 items-center">+ <Show when={props.onCreateRecord}>+ <Button+ size="sm"+ variant="outline"+ class="h-8 gap-1.5 px-2.5 text-xs"+ aria-label={+ props.creating+ ? 'Saving record'+ : (props.createRecordLabel ?? 'New record')+ }+ disabled={!props.canCreateRecord || props.creating}+ onClick={() => props.onCreateRecord?.()}+ >+ <PlusIcon class="size-3.5" />+ <Show when={!props.creating} fallback="Saving…">+ {props.createRecordLabel ?? 'New'}+ </Show>+ </Button>+ </Show>+ {props.actions}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/database/components/database-toolbar.tsx b/apps/web/src/features/database/components/database-toolbar.tsxindex 1df1a8f2be..41f1ee265f 100644--- a/apps/web/src/features/database/components/database-toolbar.tsx+++ b/apps/web/src/features/database/components/database-toolbar.tsx@@ -1,10 +1,6 @@import { ContextMenu } from '@kobalte/core/context-menu';-import CheckIcon from '@phosphor/check.svg';-import FunnelIcon from '@phosphor/funnel.svg';import KanbanIcon from '@phosphor/kanban.svg';import PlusIcon from '@phosphor/plus.svg';-import SortAscendingIcon from '@phosphor/sort-ascending.svg';-import StackIcon from '@phosphor/stack.svg';import TableIcon from '@phosphor/table.svg';import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';import { Key } from '@solid-primitives/keyed';@@ -15,7 +11,6 @@ import {DragDropSensors,SortableProvider,} from '@thisbeyond/solid-dnd';-import { Button } from '@ui/components/Button';import { DeleteDialog } from '@ui/components/DeleteDialog';import { Dropdown } from '@ui/components/Dropdown';import { Tooltip } from '@ui/components/Tooltip';@@ -36,10 +31,8 @@ import {type DatabaseOpFailure,databaseOpMessage,} from '../core/write-failure';-import { FilterPanel, filterConditionCount } from './database-view-filters';+import { DatabaseEditorToolbar } from './database-editor-toolbar';import { createInlineRename } from './inline-rename';-import { SortPanel } from './sort-panel';-import { ToolbarPopover } from './view-control-popover';/** A layout a stored view can be switched to from its tab's menu. */export type ShownLayout =@@ -92,7 +85,6 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {const current = layout();return current.kind === 'board' ? current : undefined;};- const sort = () => props.view.query.sort ?? [];const viewRename = createInlineRename({name: (view: DatabaseView) => view.name,rename: (view, name) => props.onRenameView(view, name),@@ -142,202 +134,117 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {props.onReorderViews?.(moved);}return (- <div- class="@container/view-toolbar shrink-0 bg-canvas-base [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-ink/50"- data-database-toolbar- >- <div class="flex items-center gap-2 px-4 py-1.5 @max-[520px]/view-toolbar:flex-wrap">- <div class="flex min-w-0 flex-1 items-center gap-0.5 @max-[520px]/view-toolbar:basis-full">- <div- ref={viewRail}- class="flex min-w-0 items-center gap-0.5 overflow-x-auto"- aria-label="Views"- >- <button- ref={allRecordsButton}- type="button"- aria-pressed={!props.selectedViewId}- onClick={() => props.onSelectView()}- class="flex h-8 max-w-40 shrink-0 items-center gap-1.5 rounded-full border border-transparent aria-pressed:border-edge-frame aria-pressed:bg-active aria-pressed:text-ink px-4 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus transition-colors duration-120 motion-reduce:transition-none"- >- <span class="truncate">All records</span>- </button>- <DragDropProvider- collisionDetector={closestCenter}- onDragEnd={({ draggable, droppable }) => {- if (droppable)- reorder(String(draggable.id), String(droppable.id));- }}+ <div class="shrink-0 bg-canvas-base">+ <DatabaseEditorToolbar+ columns={props.columns}+ view={props.view}+ onChangeView={props.onChangeView}+ canChangeView={canChangeView()}+ search={props.search}+ actions={props.actions}+ onCreateRecord={board() ? props.onCreateRecord : undefined}+ canCreateRecord={props.canCreateRecord}+ creating={props.creating}+ selection={+ <>+ <div+ ref={viewRail}+ class="flex min-w-0 items-center gap-0.5 overflow-x-auto"+ aria-label="Views">- <DragDropSensors />- <SortableProvider ids={props.views.map((view) => view.id)}>- <Key each={props.views} by="id">- {(view) => (- <ViewTab- view={view()}- selected={props.selectedViewId === view().id}- canEdit={props.canEdit}- canReorder={props.canEdit && !!props.onReorderViews}- renaming={viewRename.target()?.id === view().id}- renameDraft={viewRename.draft()}- renamePending={viewRename.pending()}- renameInput={(element) => {- renameInput = element;- }}- onRenameInput={viewRename.setDraft}- onRenameSave={(restoreFocus) =>- void viewRename.save(restoreFocus)- }- onRenameCancel={() => viewRename.cancel(true)}- onSelect={() => props.onSelectView(view().id)}- onRename={() => {- if (props.canEdit) viewRename.begin(view());- }}- onDelete={() => {- setViewError('');- setDeleting({ view: view() });- }}- columns={props.columns}- onShowAs={(shown) => {- setViewError('');- void props- .onShowViewAs(view(), shown)- .mapErr((failure) =>- setViewError(- databaseOpMessage(failure, 'this view')- )- );- }}- />- )}- </Key>- </SortableProvider>- </DragDropProvider>- </div>- <Show when={props.canEdit}>- <Dropdown placement="bottom-start">- <Dropdown.Trigger- size="icon-sm"- variant="ghost"- aria-label="New view"- class="ml-2 shrink-0"- disabled={creating()}+ <button+ ref={allRecordsButton}+ type="button"+ aria-pressed={!props.selectedViewId}+ onClick={() => props.onSelectView()}+ class="flex h-8 max-w-40 shrink-0 items-center gap-1.5 rounded-full border border-transparent aria-pressed:border-edge-frame aria-pressed:bg-active aria-pressed:text-ink px-4 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus transition-colors duration-120 motion-reduce:transition-none">- <PlusIcon class="size-3.5" />- </Dropdown.Trigger>- <Dropdown.Content class="min-w-40">- <Dropdown.Item- onSelect={() => void createView('table')}- disabled={creating()}- >- <TableIcon class="size-4" />- Table- </Dropdown.Item>- <Dropdown.Item- onSelect={() => void createView('board')}+ <span class="truncate">All records</span>+ </button>+ <DragDropProvider+ collisionDetector={closestCenter}+ onDragEnd={({ draggable, droppable }) => {+ if (droppable)+ reorder(String(draggable.id), String(droppable.id));+ }}+ >+ <DragDropSensors />+ <SortableProvider ids={props.views.map((view) => view.id)}>+ <Key each={props.views} by="id">+ {(view) => (+ <ViewTab+ view={view()}+ selected={props.selectedViewId === view().id}+ canEdit={props.canEdit}+ canReorder={props.canEdit && !!props.onReorderViews}+ renaming={viewRename.target()?.id === view().id}+ renameDraft={viewRename.draft()}+ renamePending={viewRename.pending()}+ renameInput={(element) => {+ renameInput = element;+ }}+ onRenameInput={viewRename.setDraft}+ onRenameSave={(restoreFocus) =>+ void viewRename.save(restoreFocus)+ }+ onRenameCancel={() => viewRename.cancel(true)}+ onSelect={() => props.onSelectView(view().id)}+ onRename={() => {+ if (props.canEdit) viewRename.begin(view());+ }}+ onDelete={() => {+ setViewError('');+ setDeleting({ view: view() });+ }}+ columns={props.columns}+ onShowAs={(shown) => {+ setViewError('');+ void props+ .onShowViewAs(view(), shown)+ .mapErr((failure) =>+ setViewError(+ databaseOpMessage(failure, 'this view')+ )+ );+ }}+ />+ )}+ </Key>+ </SortableProvider>+ </DragDropProvider>+ </div>+ <Show when={props.canEdit}>+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ size="icon-sm"+ variant="ghost"+ aria-label="New view"+ class="ml-2 shrink-0"disabled={creating()}>- <KanbanIcon class="size-4" />- Board- </Dropdown.Item>- </Dropdown.Content>- </Dropdown>- </Show>- </div>- <div class="flex shrink-0 items-center gap-0.5 @max-[520px]/view-toolbar:w-full @max-[520px]/view-toolbar:justify-end">- <Show when={canChangeView()}>- <Show when={board()}>- {(current) => (- <Dropdown placement="bottom-start">- <Dropdown.Trigger- aria-label="Group board by"- title="Group by"- size="icon-md"- variant="ghost"- class="h-8 w-auto rounded-md px-2 text-ink-muted hover:bg-hover data-expanded:bg-hover"+ <PlusIcon class="size-3.5" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-40">+ <Dropdown.Item+ onSelect={() => void createView('table')}+ disabled={creating()}>- <StackIcon class="size-3.5" />- </Dropdown.Trigger>- <Dropdown.Content class="min-w-48">- <Dropdown.RadioGroup- value={current().groupBy}- onChange={(columnId) => {- if (columnId !== current().groupBy)- props.onChangeView({- layout: {- ...current(),- groupBy: columnId,- lanes: [],- },- });- }}- >- <For each={groupColumns()}>- {(column) => (- <Dropdown.RadioItem closeOnSelect value={column.id}>- <span class="flex-1">{column.name}</span>- <Dropdown.ItemIndicator>- <CheckIcon class="size-3.5 text-accent" />- </Dropdown.ItemIndicator>- </Dropdown.RadioItem>- )}- </For>- </Dropdown.RadioGroup>- </Dropdown.Content>- </Dropdown>- )}- </Show>-- <ToolbarPopover- label="Filter"- compact- count={filterConditionCount(props.view.query.filter)}- icon={<FunnelIcon class="size-3.5" />}- >- <FilterPanel- columns={props.columns}- filter={props.view.query.filter}- onChange={(filter) =>- props.onChangeView({- query: { ...props.view.query, filter },- })- }- />- </ToolbarPopover>- <ToolbarPopover- label="Sort"- compact- count={sort().length}- icon={<SortAscendingIcon class="size-3.5" />}- >- <SortPanel- columns={props.columns}- view={props.view}- onChange={props.onChangeView}- />- </ToolbarPopover>- </Show>- {props.search}- <div class="ml-1 flex shrink-0 items-center">- <Show when={props.onCreateRecord && board()}>- <Button- size="sm"- variant="outline"- class="h-8 gap-1.5 px-2.5 text-xs"- aria-label={props.creating ? 'Saving record' : 'New record'}- disabled={!props.canCreateRecord || props.creating}- onClick={() => props.onCreateRecord?.()}- >- <PlusIcon class="size-3.5" />- <Show when={!props.creating} fallback="Saving…">- New- </Show>- </Button>+ <TableIcon class="size-4" />+ Table+ </Dropdown.Item>+ <Dropdown.Item+ onSelect={() => void createView('board')}+ disabled={creating()}+ >+ <KanbanIcon class="size-4" />+ Board+ </Dropdown.Item>+ </Dropdown.Content>+ </Dropdown></Show>- {props.actions}- </div>- </div>- </div>+ </>+ }+ /><Show when={viewError()}><p role="alert" class="px-4 pb-2 text-xs text-failure">{viewError()}diff --git a/apps/web/src/features/database/components/sort-panel.test.tsx b/apps/web/src/features/database/components/sort-panel.test.tsxindex e2415112da..6fa9b868e5 100644--- a/apps/web/src/features/database/components/sort-panel.test.tsx+++ b/apps/web/src/features/database/components/sort-panel.test.tsx@@ -28,11 +28,6 @@ describe('sort panel', () => {},]}view={{- id: 'work',- databaseId: 'database',- tableId: 'table',- name: 'My work',- position: 'a0',query: {filter: null,sort: [@@ -41,8 +36,6 @@ describe('sort panel', () => {],},layout: { kind: 'table', columns: [] },- createdAt: '2026-09-01T00:00:00Z',- updatedAt: '2026-09-01T00:00:00Z',}}onChange={change}/>diff --git a/apps/web/src/features/database/components/sort-panel.tsx b/apps/web/src/features/database/components/sort-panel.tsxindex 9cbfb210f9..79c6023020 100644--- a/apps/web/src/features/database/components/sort-panel.tsx+++ b/apps/web/src/features/database/components/sort-panel.tsx@@ -1,7 +1,6 @@import GripIcon from '@phosphor/dots-six-vertical.svg';import PlusIcon from '@phosphor/plus.svg';import XIcon from '@phosphor/x.svg';-import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';import { Key } from '@solid-primitives/keyed';import { DragDropProvider, DragOverlay } from '@thisbeyond/solid-dnd';import { Button } from '@ui/components/Button';@@ -14,13 +13,13 @@ import { VerticalInsertionLine } from '../../../components/drag-drop/insertion-limport type { SortKey } from '../../../lib/core/database-sql/generated/types';import type { DatabaseViewColumn } from '../core/database-view';import { withSort, withSortMoved } from '../core/view-query';-import type { ViewChange } from '../core/view-state';+import type { DatabaseViewState, ViewChange } from '../core/view-state';import { ViewSelect } from './view-select';/** A view's sort levels, first first; drag a level's handle to change its priority. */export function SortPanel(props: {columns: DatabaseViewColumn[];- view: DatabaseView;+ view: DatabaseViewState;onChange: (change: ViewChange) => void;}) {const [list, setList] = createSignal<HTMLElement>();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.tsxindex 840a57d29a..c9f46edd1b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.tsx@@ -14,6 +14,7 @@ const blockNamesWithLocations = ['task','email','chat',+ 'database','task',] as const;type BlockNameWithLocations = (typeof blockNamesWithLocations)[number];diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LexicalInteractiveBoundary.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LexicalInteractiveBoundary.tsxnew file mode 100644index 0000000000..bae0b77a8e--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LexicalInteractiveBoundary.tsx@@ -0,0 +1,26 @@+import { stopLexicalPropagation } from 'lexical';+import type { JSX } from 'solid-js';++/** Let embedded controls handle editing without sending their events to outer Lexical. */+export function LexicalInteractiveBoundary(props: { children: JSX.Element }) {+ return (+ <div+ data-lexical-interactive+ // Native listeners mark events before they reach Lexical's root, while+ // preserving browser defaults and Solid's delegated handlers.+ on:keydown={stopLexicalPropagation}+ on:beforeinput={stopLexicalPropagation}+ on:input={stopLexicalPropagation}+ on:compositionstart={stopLexicalPropagation}+ on:compositionend={stopLexicalPropagation}+ on:paste={stopLexicalPropagation}+ on:copy={stopLexicalPropagation}+ on:cut={stopLexicalPropagation}+ on:drop={stopLexicalPropagation}+ on:dragstart={stopLexicalPropagation}+ on:click={stopLexicalPropagation}+ >+ {props.children}+ </div>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.test.tsxnew file mode 100644index 0000000000..ec644d3007--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.test.tsx@@ -0,0 +1,58 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';+import { DatabaseCard } from './DatabaseCard';++const mocks = vi.hoisted(() => ({ enabled: false, mounted: 0 }));+vi.mock('@core/constant/featureFlags', () => ({ enableDatabases: {} }));+vi.mock('../../context/LexicalWrapperContext', async () => {+ const { createContext } = await import('solid-js');+ return { LexicalWrapperContext: createContext() };+});+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: mocks.enabled }),+}));+vi.mock('@app/features/block-database/document-database', () => ({+ DocumentDatabase: (props: { collapsed?: boolean; onToggle: () => void }) => {+ mocks.mounted++;+ return (+ <div>+ {!props.collapsed && <div>Database records</div>}+ <button onClick={props.onToggle}>+ {props.collapsed ? 'Expand' : 'Collapse'}+ </button>+ </div>+ );+ },+}));++afterEach(() => {+ cleanup();+ mocks.enabled = false;+ mocks.mounted = 0;+});++const card = () => (+ <DatabaseCard+ key="database-card"+ documentId="db-1"+ documentName="Tasks"+ blockName="database"+ theme={{}}+ />+);++it('keeps saved database cards inert when the feature is disabled', () => {+ render(card);+ expect(screen.getByText('Tasks')).toBeTruthy();+ expect(mocks.mounted).toBe(0);+});++it('allows a static document viewer to collapse and expand locally', async () => {+ mocks.enabled = true;+ render(card);+ await screen.findByText('Database records');+ fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));+ expect(screen.queryByText('Database records')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Expand' }));+ expect(screen.getByText('Database records')).toBeTruthy();+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.tsxnew file mode 100644index 0000000000..a0695298e4--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DatabaseCard.tsx@@ -0,0 +1,91 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableDatabases } from '@core/constant/featureFlags';+import {+ $convertCardToMention,+ $isDocumentCardNode,+ type DocumentCardDecoratorProps,+} from '@macro-inc/lexical-core';+import { $getNodeByKey, SKIP_DOM_SELECTION_TAG } from 'lexical';+import {+ createSignal,+ lazy,+ onCleanup,+ Show,+ Suspense,+ useContext,+} from 'solid-js';+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';+import { LexicalInteractiveBoundary } from '../core/LexicalInteractiveBoundary';++const DocumentDatabase = lazy(async () => ({+ default: (await import('@app/features/block-database/document-database'))+ .DocumentDatabase,+}));++/** Database cards use their own metadata and editor, never document previews. */+export function DatabaseCard(props: DocumentCardDecoratorProps) {+ const enabled = useFeatureFlag(enableDatabases);+ const wrapper = useContext(LexicalWrapperContext);+ const [collapsed, setCollapsed] = createSignal(false);+ const [params, setParams] = createSignal(props.blockParams ?? {});+ let savedParams = props.blockParams;+ if (wrapper)+ onCleanup(+ wrapper.editor.registerUpdateListener(({ editorState }) => {+ editorState.read(() => {+ const node = $getNodeByKey(props.key);+ if (!$isDocumentCardNode(node)) return;+ const next = node.getBlockParams();+ if (next !== savedParams) {+ savedParams = next;+ setParams(next);+ }+ });+ })+ );+ const changeLocation = (params: Record<string, string>) => {+ setParams(params);+ if (!wrapper?.editor.isEditable() || !wrapper.isInteractable()) return;+ wrapper.editor.update(+ () => {+ const node = $getNodeByKey(props.key);+ if ($isDocumentCardNode(node)) node.setBlockParams(params);+ },+ { tag: SKIP_DOM_SELECTION_TAG }+ );+ };+ const toggle = () => {+ if (!wrapper?.editor.isEditable() || !wrapper.isInteractable()) {+ setCollapsed(!collapsed());+ return;+ }+ wrapper.editor.update(() => {+ const node = $getNodeByKey(props.key);+ if ($isDocumentCardNode(node)) $convertCardToMention(node).selectEnd();+ });+ };+ const placeholder = () => (+ <div class="my-2 rounded-lg border border-edge-muted px-3 py-2 text-sm text-ink-muted">+ {props.documentName || 'Database'}+ </div>+ );+ return (+ <Show+ when={enabled().enabled && !wrapper?.skipPreviewFetch}+ fallback={placeholder()}+ >+ <Suspense fallback={placeholder()}>+ <LexicalInteractiveBoundary>+ <DocumentDatabase+ databaseId={props.documentId}+ name={props.documentName}+ params={params()}+ collapsed={collapsed()}+ onToggle={toggle}+ onLocationChange={changeLocation}+ />+ </LexicalInteractiveBoundary>+ </Suspense>+ </Show>+ );+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsxindex 10cc664242..e5e4c77e76 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx@@ -74,6 +74,7 @@ import { UPDATE_DOCUMENT_NAME_COMMAND } from '../../plugins';import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';import { dispatchInternalLayoutShift } from '../../plugins/shared/utils';import { BlockLink, openDocument } from '../core/BlockLink';+import { DatabaseCard } from './DatabaseCard';false && floatWithElement;@@ -89,6 +90,7 @@ const stringifyPreviewBox = ([width, height]: PreviewBox): [string, string] => {};export function DocumentCard(props: DocumentCardDecoratorProps) {+ if (props.blockName === 'database') return <DatabaseCard {...props} />;return (<Suspensefallback={diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsxindex 0b809db3c6..b86ad5297e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx@@ -38,6 +38,7 @@ import {DocumentCardNode,type DocumentMentionDecoratorProps,} from '@macro-inc/lexical-core';+import ArrowsOut from '@phosphor/arrows-out-simple.svg';import EyeSlashDuo from '@phosphor/eye-slash.svg';import TrashSimple from '@phosphor/trash-simple.svg';import {@@ -52,6 +53,7 @@ import { useFormDetailQuery } from '@queries/storage/forms';import { useSystemSkillsQuery } from '@queries/storage/system-skills';import { blockNameToItemType } from '@service-storage/client';import { createCallback } from '@solid-primitives/rootless';+import { Button } from '@ui';import {$getNodeByKey,COMMAND_PRIORITY_NORMAL,@@ -64,6 +66,7 @@ import {createMemo,createSignal,Match,+ onCleanup,Show,Suspense,Switch,@@ -411,6 +414,16 @@ export function DocumentMention(props: DocumentMentionDecoratorProps) {/** Databases have their own permission-checked metadata, not a document preview. */function DatabaseMention(props: DocumentMentionDecoratorProps) {+ const wrapper = useContext(LexicalWrapperContext);+ const [editable, setEditable] = createSignal(+ wrapper?.editor.isEditable() ?? false+ );+ if (wrapper)+ onCleanup(+ wrapper.editor.registerEditableListener((value) => {+ setEditable(value);+ })+ );const enabled = useFeatureFlag(enableDatabases);const detail = useDatabaseDetailQuery(() =>enabled().enabled ? props.documentId : undefined@@ -428,31 +441,60 @@ function DatabaseMention(props: DocumentMentionDecoratorProps) {openInNewSplitForMention(event.shiftKey, true));};+ const expand = (event: MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ if (!wrapper?.editor.isEditable() || !wrapper.isInteractable()) return;+ wrapper.editor.update(() => {+ const node = $getNodeByKey(props.key);+ if ($isDocumentMentionNode(node)) $convertMentionToCard(node);+ });+ };return (- <span- class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"- role="link"- tabIndex={0}- on:mousedown={(event) => event.preventDefault()}- on:click={open}- onKeyDown={(event) => {- if (event.key === 'Enter') open(event);- }}- >- <MentionContainer- icon={<EntityIcon targetType="database" size="fill" />}- collapsed={props.collapsed}- text={- <span- data-document-mention="true"- data-document-id={props.documentId}- data-block-name="database"- data-document-name={name()}- >- {detail.isError ? 'Database unavailable' : name() || 'Database'}- </span>+ <span class="inline-flex items-baseline gap-1">+ <span+ class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"+ role="link"+ tabIndex={0}+ on:mousedown={(event) => event.preventDefault()}+ on:click={open}+ onKeyDown={(event) => {+ if (event.key === 'Enter') open(event);+ }}+ >+ <MentionContainer+ icon={<EntityIcon targetType="database" size="fill" />}+ collapsed={props.collapsed}+ text={+ <span+ data-document-mention="true"+ data-document-id={props.documentId}+ data-block-name="database"+ data-document-name={name()}+ >+ {detail.isError ? 'Database unavailable' : name() || 'Database'}+ </span>+ }+ />+ </span>+ <Show+ when={+ enabled().enabled &&+ editable() &&+ wrapper?.isInteractable() &&+ !detail.isError}- />+ >+ <Button+ variant="ghost"+ size="icon-xs"+ label="Expand database"+ on:mousedown={(event) => event.preventDefault()}+ on:click={expand}+ >+ <ArrowsOut class="size-3.5" />+ </Button>+ </Show></span>);}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsxindex 5a30ee1f42..86ec2b5bca 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx@@ -253,7 +253,11 @@ export function ActionMenu(props: {onMount(() => {const focusOut = () => {- closeMenu();+ // A newly inserted decorator can focus a control during reconciliation.+ // Dispatch after that commit so closing the menu gets a writable state.+ queueMicrotask(() => {+ if (isOpen()) closeMenu();+ });};document.addEventListener('focusout', focusOut);onCleanup(() => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.tsindex 99eb82227a..0b5db3921b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts@@ -1,5 +1,6 @@import { globalSplitManager } from '@app/signal/splitLayout';import type { ComposeTaskSuccess } from '@block-md/component/ComposeTask';+import { toast } from '@core/component/Toast/Toast';import { enableDatabases, isFeatureEnabled } from '@core/constant/featureFlags';import { trackMention } from '@core/signal/mention';import { LinkNode } from '@lexical/link';@@ -12,12 +13,14 @@ import {AwaitNode,CustomCodeNode,DatabaseQueryNode,+ DocumentCardNode,DocumentMentionNode,EquationNode,HorizontalRuleNode,ImageNode,VideoNode,} from '@macro-inc/lexical-core';+import { Telemetry } from '@macro-inc/observability';import CheckSquare from '@phosphor/check-square.svg';import CodeBlock from '@phosphor/code-block.svg';import FileText from '@phosphor/file-text.svg';@@ -341,16 +344,8 @@ export const ACTIONS: Action[] = [},{id: 'database-query',- name: 'Database',- keywords: [- 'query',- 'query-database',- 'ask',- 'database',- 'live',- 'answer',- 'sql',- ],+ name: 'Query',+ keywords: ['query', 'query-database', 'ask', 'live', 'answer', 'sql'],category: ActionCategory.MEDIA,icon: LightningIcon,dependencies: [DatabaseQueryNode],@@ -369,4 +364,24 @@ export const ACTIONS: Action[] = [);},},+ {+ id: 'database',+ name: 'Database',+ keywords: ['database', 'new database', 'editable', 'records'],+ category: ActionCategory.MEDIA,+ icon: TableIcon,+ dependencies: [AwaitNode, DocumentMentionNode, DocumentCardNode],+ action: (editor, context) => {+ if (!isFeatureEnabled(enableDatabases)) return;+ queueMicrotask(async () => {+ try {+ const { insertNewDatabase } = await import('./insert-database');+ await insertNewDatabase(editor, context);+ } catch (error: unknown) {+ Telemetry.error('database.insert.failed', { error: String(error) });+ toast.failure('The database could not be inserted. Try again.');+ }+ });+ },+ },];diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.test.tsindex cd05a10058..75b7861024 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.test.ts@@ -1,4 +1,5 @@import { DatabaseQueryNode } from '@macro-inc/lexical-core/nodes/DatabaseQueryNode';+import { DocumentCardNode } from '@macro-inc/lexical-core/nodes/DocumentCardNode';import { describe, expect, it } from 'vitest';import { availableActions } from './available-actions';import type { Action } from './types';@@ -9,11 +10,20 @@ const run = () => {};const actions: Action[] = [{id: 'database-query',+ name: 'Query',+ keywords: ['query'],+ category: 'Media',+ icon,+ dependencies: [DatabaseQueryNode],+ action: run,+ },+ {+ id: 'database',name: 'Database',keywords: ['database'],category: 'Media',icon,- dependencies: [DatabaseQueryNode],+ dependencies: [DocumentCardNode],action: run,},{@@ -33,7 +43,7 @@ describe('slash menu actions', () => {databasesEnabled: true,hasNodes: () => true,}).map((action) => action.id)- ).toEqual(['database-query', 'paragraph']);+ ).toEqual(['database-query', 'database', 'paragraph']);});it('leaves the database answer out while databases are off', () => {@@ -58,6 +68,6 @@ describe('slash menu actions', () => {ignoreActionIds: ['paragraph'],hasNodes: () => true,}).map((action) => action.id)- ).toEqual(['database-query']);+ ).toEqual(['database-query', 'database']);});});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.tsindex f2df4b4c41..ba75a71c63 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/available-actions.ts@@ -10,7 +10,10 @@ export function availableActions(}): Action[] {return actions.filter((action) => {- if (action.id === 'database-query' && !options.databasesEnabled)+ if (+ (action.id === 'database-query' || action.id === 'database') &&+ !options.databasesEnabled+ )return false;if (options.ignoreActionIds?.includes(action.id)) return false;const { dependencies } = action;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.test.tsnew file mode 100644index 0000000000..4f40f8b5c5--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.test.ts@@ -0,0 +1,179 @@+import { registerRichText } from '@lexical/rich-text';+import {+ $isDocumentCardNode,+ SupportedNodeTypes,+} from '@macro-inc/lexical-core';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ createEditor,+} from 'lexical';+import { err, ok, type Result } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { insertNewDatabase } from './insert-database';++const mocks = vi.hoisted(() => ({+ create: vi.fn(),+ track: vi.fn(),+ untrack: vi.fn(),+ failure: vi.fn(),+}));+vi.mock('@queries/storage/databases', () => ({ createDatabase: mocks.create }));+vi.mock('@core/signal/mention', () => ({+ trackMention: mocks.track,+ untrackMention: mocks.untrack,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));++function documentEditor() {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError: (error) => {+ throw error;+ },+ });+ editor.setRootElement(document.createElement('div'));+ registerRichText(editor);+ editor.update(+ () => {+ const text = $createTextNode('Before. After.');+ $getRoot().append($createParagraphNode().append(text));+ text.select(8, 8);+ },+ { discrete: true }+ );+ return editor;+}++describe('creating a database in a document', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.create.mockResolvedValue(ok('db-1'));+ mocks.track.mockResolvedValue('mention-1');+ });++ it('creates once and anchors an expanded editor between the surrounding text', async () => {+ const editor = documentEditor();+ await insertNewDatabase(editor, {+ sourceDocumentId: 'doc-1',+ sourceBlockName: 'md',+ });+ expect(mocks.create).toHaveBeenCalledExactlyOnceWith({+ name: 'Untitled database',+ source: 'slash-menu',+ });+ expect(mocks.track).toHaveBeenCalledWith('doc-1', 'database', 'db-1');+ editor.read(() => {+ const children = $getRoot().getChildren();+ expect(children.map((node) => node.getType())).toEqual([+ 'paragraph',+ 'document-card',+ 'paragraph',+ ]);+ expect(children[0].getTextContent()).toBe('Before. ');+ expect(children[2].getTextContent()).toBe('After.');+ const card = children[1];+ expect($isDocumentCardNode(card)).toBe(true);+ if (!$isDocumentCardNode(card)) throw new Error('Missing card');+ expect(card.getDocumentId()).toBe('db-1');+ expect(card.getBlockName()).toBe('database');+ expect(card.getMentionUuid()).toBe('mention-1');+ });+ });++ it('does not insert elsewhere when the placeholder was removed during creation', async () => {+ let finish!: (result: Result<string, unknown>) => void;+ mocks.create.mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ })+ );+ const editor = documentEditor();+ const creating = insertNewDatabase(editor);+ editor.update(+ () =>+ $getRoot()+ .clear()+ .append(+ $createParagraphNode().append($createTextNode('Replacement'))+ ),+ { discrete: true }+ );+ finish(ok('db-1'));+ await creating;+ expect(editor.read(() => $getRoot().getTextContent())).toBe('Replacement');+ expect(mocks.track).not.toHaveBeenCalled();+ });++ it('cleans up tracking when the placeholder is removed while tracking runs', async () => {+ const editor = documentEditor();+ mocks.track.mockImplementation(async () => {+ editor.update(() => $getRoot().clear(), { discrete: true });+ return 'mention-1';+ });+ await insertNewDatabase(editor, { sourceDocumentId: 'doc-1' });+ expect(mocks.untrack).toHaveBeenCalledExactlyOnceWith('doc-1', 'mention-1');+ expect(editor.read(() => $getRoot().getChildrenSize())).toBe(0);+ });++ it('removes the placeholder and reports a failed create without retrying', async () => {+ mocks.create.mockResolvedValue(err([{ message: 'Refused' }]));+ const editor = documentEditor();+ await insertNewDatabase(editor);+ expect(mocks.create).toHaveBeenCalledTimes(1);+ expect(mocks.failure).toHaveBeenCalledTimes(1);+ expect(editor.read(() => $getRoot().getTextContent())).toBe(+ 'Before. After.'+ );+ expect(mocks.track).not.toHaveBeenCalled();+ });++ it('does not create from a read-only editor', async () => {+ const editor = documentEditor();+ editor.setEditable(false);+ await insertNewDatabase(editor);+ expect(mocks.create).not.toHaveBeenCalled();+ });++ it.each(['create', 'track'] as const)(+ 'removes the placeholder when %s rejects and lets the action report the failure',+ async (boundary) => {+ const editor = documentEditor();+ const failure = new Error('Service unavailable');+ mocks[boundary].mockRejectedValueOnce(failure);+ await expect(+ insertNewDatabase(editor, { sourceDocumentId: 'doc-1' })+ ).rejects.toBe(failure);+ expect(editor.read(() => $getRoot().getTextContent())).toBe(+ 'Before. After.'+ );+ expect(editor.getEditorState().toJSON().root.children).not.toEqual(+ expect.arrayContaining([expect.objectContaining({ type: 'await' })])+ );+ }+ );++ it.each(['create', 'track'] as const)(+ 'cleans up when the document becomes read-only during %s',+ async (boundary) => {+ const editor = documentEditor();+ mocks[boundary].mockImplementationOnce(async () => {+ editor.setEditable(false);+ return boundary === 'create' ? ok('db-1') : 'mention-1';+ });+ await insertNewDatabase(editor, { sourceDocumentId: 'doc-1' });+ expect(editor.read(() => $getRoot().getTextContent())).toBe(+ 'Before. After.'+ );+ expect(editor.isEditable()).toBe(false);+ if (boundary === 'track')+ expect(mocks.untrack).toHaveBeenCalledExactlyOnceWith(+ 'doc-1',+ 'mention-1'+ );+ }+ );+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.tsnew file mode 100644index 0000000000..d694b69cf7--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/insert-database.ts@@ -0,0 +1,97 @@+import { toast } from '@core/component/Toast/Toast';+import { trackMention, untrackMention } from '@core/signal/mention';+import {+ $convertMentionToCard,+ $createAwaitNode,+ $createDocumentMentionNode,+ $isAwaitNode,+} from '@macro-inc/lexical-core';+import { createDatabase } from '@queries/storage/databases';+import {+ $createParagraphNode,+ $getNodeByKey,+ $getSelection,+ $insertNodes,+ $isRangeSelection,+ type LexicalEditor,+ type NodeKey,+} from 'lexical';+import { nanoid } from 'nanoid';+import type { ActionContext } from './types';++/** Keep the insertion anchored while creation runs, even if the caret moves. */+export async function insertNewDatabase(+ editor: LexicalEditor,+ context?: ActionContext+) {+ if (!editor.isEditable()) return;+ let placeholderKey: NodeKey | undefined;+ editor.update(() => {+ const placeholder = $createAwaitNode({+ awaitId: nanoid(),+ text: 'Creating database…',+ });+ $insertNodes([placeholder]);+ placeholderKey = placeholder.getKey();+ });++ let mentionUuid: string | undefined;+ let inserted = false;+ try {+ const name = 'Untitled database';+ const created = await createDatabase({ name, source: 'slash-menu' });+ if (created.isErr()) {+ toast.failure('Your database could not be created. Try again.');+ return;+ }++ // A successful create remains a database even when its placeholder was removed.+ const present = editor.read(() =>+ placeholderKey ? $isAwaitNode($getNodeByKey(placeholderKey)) : false+ );+ if (!present || !editor.isEditable()) return;+ mentionUuid =+ context?.sourceDocumentId &&+ !context.disableMentionTracking &&+ context.sourceBlockName !== 'channel' &&+ context.sourceBlockName !== 'chat'+ ? await trackMention(+ context.sourceDocumentId,+ 'database',+ created.value+ )+ : undefined;++ editor.update(() => {+ const placeholder = placeholderKey ? $getNodeByKey(placeholderKey) : null;+ if (!$isAwaitNode(placeholder) || !editor.isEditable()) return;+ const selection = $getSelection();+ const focused =+ $isRangeSelection(selection) &&+ selection.getNodes().some((node) => node.getKey() === placeholderKey);+ const mention = $createDocumentMentionNode({+ documentId: created.value,+ documentName: name,+ blockName: 'database',+ mentionUuid,+ });+ placeholder.replace(mention);+ const card = $convertMentionToCard(mention);+ inserted = true;+ if (!card.getNextSibling()) {+ const paragraph = $createParagraphNode();+ card.insertAfter(paragraph);+ if (focused) paragraph.selectStart();+ }+ });+ } finally {+ // Programmatic cleanup also runs when editability changes during either await.+ if (!inserted) {+ editor.update(() => {+ if (placeholderKey) $getNodeByKey(placeholderKey)?.remove();+ });+ if (mentionUuid && context?.sourceDocumentId)+ await untrackMention(context.sourceDocumentId, mentionUuid);+ }+ }+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-navigation/blockDecoratorNavigationPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-navigation/blockDecoratorNavigationPlugin.tsindex c2d6a15711..44a235ca7a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-navigation/blockDecoratorNavigationPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-navigation/blockDecoratorNavigationPlugin.ts@@ -27,6 +27,7 @@ const STOPPING_BLOCK_TYPES = new Set(['video','horizontalrule','database-query',+ 'document-card',]);type Direction = 'up' | 'down';diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.tsindex fb34a994f9..ceca820af8 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts@@ -1,20 +1,28 @@import { authoredMentions } from '@channel/Input/message-payload';+import { untrackMention } from '@core/signal/mention';import {+ $convertCardToMention,$convertMentionToCard,$createDocumentCardNode,$createDocumentMentionNode,+ $isDocumentCardNode,$isDocumentMentionNode,SupportedNodeTypes,} from '@macro-inc/lexical-core';import {$createParagraphNode,+ $createTextNode,$getRoot,$isElementNode,createEditor,type LexicalEditor,} from 'lexical';import { describe, expect, it, vi } from 'vitest';-import { type ItemMention, mentionsPlugin } from './mentionsPlugin';+import {+ INSERT_DOCUMENT_MENTION_COMMAND,+ type ItemMention,+ mentionsPlugin,+} from './mentionsPlugin';// The plugin's imports reach the realtime connection, which opens a socket on load.vi.hoisted(() => {@@ -47,6 +55,7 @@ function composer() {const created: ItemMention[] = [];const removed: ItemMention[] = [];mentionsPlugin({+ sourceDocumentId: 'doc-1',onCreateMention: (mention) => created.push(mention),onRemoveMention: (mention) => removed.push(mention),})(editor);@@ -58,6 +67,91 @@ function discrete(editor: LexicalEditor, change: () => void) {}describe('mentionsPlugin', () => {+ it('inserts a compact database mention and preserves surrounding text', () => {+ const { editor, created } = composer();+ discrete(editor, () => {+ const text = $createTextNode('Before. After.');+ $getRoot().append($createParagraphNode().append(text));+ text.select(8, 8);+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: 'db-1',+ documentName: 'Tasks',+ blockName: 'database',+ });+ });+ editor.read(() => {+ const children = $getRoot().getChildren();+ expect(children.map((child) => child.getType())).toEqual(['paragraph']);+ expect(children[0].getTextContent()).toBe('Before. TasksAfter.');+ const paragraph = children[0];+ if (!$isElementNode(paragraph)) throw new Error('Missing paragraph');+ expect(paragraph.getChildren().map((child) => child.getType())).toContain(+ 'document-mention'+ );+ });+ expect(created).toContainEqual(+ expect.objectContaining({+ itemType: 'database',+ itemId: 'db-1',+ documentName: 'Tasks',+ })+ );+ });++ it('keeps database mentions compact in composers', () => {+ const { editor } = composer();+ discrete(editor, () => {+ $getRoot().append($createParagraphNode()).selectEnd();+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: 'db-1',+ documentName: 'Tasks',+ blockName: 'database',+ });+ });+ editor.read(() =>+ expect($getRoot().getFirstDescendant()?.getType()).toBe(+ 'document-mention'+ )+ );+ });++ it('keeps the tracked database reference through collapse/expand and untracks only its removal', () => {+ vi.mocked(untrackMention).mockClear();+ const { editor, created, removed } = composer();+ discrete(editor, () => {+ $getRoot().append(+ $createDocumentCardNode({+ documentId: 'db-1',+ documentName: 'Tasks',+ blockName: 'database',+ mentionUuid: 'reference-1',+ blockParams: { tableId: 'table-1', viewId: 'view-1' },+ })+ );+ });+ discrete(editor, () => {+ const card = $getRoot().getFirstChild();+ if (!$isDocumentCardNode(card)) throw new Error('Missing card');+ const mention = $convertCardToMention(card);+ expect(mention.getBlockParams()).toEqual({+ tableId: 'table-1',+ viewId: 'view-1',+ });+ });+ discrete(editor, () => {+ const mention = $getRoot().getFirstDescendant();+ if (!$isDocumentMentionNode(mention)) throw new Error('Missing mention');+ const card = $convertMentionToCard(mention);+ expect(card.getMentionUuid()).toBe('reference-1');+ });+ expect(untrackMention).not.toHaveBeenCalled();+ expect(created.length - removed.length).toBe(1);+ discrete(editor, () => $getRoot().clear());+ expect(untrackMention).toHaveBeenCalledExactlyOnceWith(+ 'doc-1',+ 'reference-1'+ );+ });it('sends an inline form mention as a form reference, and drops it when the mention is removed', () => {const editor = createEditor({nodes: SupportedNodeTypes,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex 18f69cdace..bd5e82c2a6 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -223,6 +223,9 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {// A form reference: posting it grants the channel View on the form.fileType = 'form';itemType = 'form';+ } else if (blockName === 'database') {+ fileType = 'database';+ itemType = 'database';} else if (blockName === 'initiative') {// A task project, never a document id.fileType = 'initiative';@@ -405,14 +408,40 @@ function registerMentionsPlugin($traverseNodes($getRoot(), (node) => {if ($isMentionNode(node) && !$isUntrackedPullRequestMention(node)) {mentions.push($mentionItemFromNode(node));+ } else if (+ node instanceof DocumentCardNode &&+ node.getBlockName() === 'database'+ ) {+ mentions.push({+ itemType: 'database',+ itemId: node.getDocumentId(),+ documentName: node.getDocumentName(),+ });}});});props.setMentions(mentions);}+ // Expansion/collapse replaces the node but preserves its tracked reference UUID.+ // Untrack only when neither representation remains in the committed editor state.+ function databaseReferenceRemains(mentionUuid: string) {+ return editor.read(() => {+ let remains = false;+ $traverseNodes($getRoot(), (node) => {+ if (+ (node instanceof DocumentCardNode || $isDocumentMentionNode(node)) &&+ node.getBlockName() === 'database' &&+ node.getMentionUuid() === mentionUuid+ )+ remains = true;+ });+ return remains;+ });+ }+return mergeRegister(- // A form's card references the form exactly as its mention did;+ // A form or database card references its entity exactly as its mention did;// converting one to the other removes one reference and creates the other.editor.registerMutationListener(DocumentCardNode,@@ -425,19 +454,33 @@ function registerMentionsPlugin(: editor.getEditorState(),nodeKey);- // Only a form's card is a reference here (RFC 03); other cards'+ // Form and database cards are references; other cards'// sharing stays as it was.if (!(node instanceof DocumentCardNode)) continue;- if (node.getBlockName() !== 'form') continue;+ if (+ node.getBlockName() !== 'form' &&+ node.getBlockName() !== 'database'+ )+ continue;const card = {itemType: blockItemType(node.getBlockName()),itemId: node.getDocumentId(),documentName: node.getDocumentName(),};if (mutation === 'created') onCreateMention?.(card);- else+ else {+ const uuid = node.getMentionUuid();+ if (+ node.getBlockName() === 'database' &&+ uuid &&+ sourceDocumentId &&+ !databaseReferenceRemains(uuid)+ )+ void untrackMention(sourceDocumentId, uuid);onRemoveMention?.({ itemType: card.itemType, itemId: card.itemId });+ }}+ updateMentionsSignal();}),editor.registerCommand(@@ -464,10 +507,9 @@ function registerMentionsPlugin(if ($isRangeSelection(selection) && !selection.isCollapsed()) {$collapseSelection(selection);$insertNodes([$createTextNode(' '), mentionNode]);- mentionNode.selectEnd();- return true;+ } else {+ $insertNodes([mentionNode]);}- $insertNodes([mentionNode]);if ($isRootOrShadowRoot(mentionNode.getParentOrThrow())) {$wrapNodeInElement(mentionNode, $createParagraphNode);}@@ -867,7 +909,12 @@ function registerMentionsPlugin(// unsetDocumenentionPreviewCache(nodeId);}const mentionUuid = node.getMentionUuid();- if (mentionUuid && sourceDocumentId) {+ if (+ mentionUuid &&+ sourceDocumentId &&+ (node.getBlockName() !== 'database' ||+ !databaseReferenceRemains(mentionUuid))+ ) {untrackMention(sourceDocumentId, mentionUuid);}if (onRemoveMention) {diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 8730945199..fd71f693fc 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -1130,7 +1130,7 @@ Members see the picture without editing controls. One-to-one direct messagescontinue to show the other person's user picture.Opening the slash menu with `/` lists Normal Text, headings, and the other-Markdown options before Database. Typing `/database` filters to the Database-action.+Markdown options before Query and Database. Typing `/query` filters to the Query+action; `/database` creates a new database and inserts its editable card.-When Databases is enabled, type `/database` in a channel message or thread reply and choose **Database** to insert a live question. Ask with Enter or the Ask button, then accept the answer before sending the message. Enter in the question box belongs to the question and must not send the channel draft. Recipients can read the live answer subject to their database access.+When Databases is enabled, type `/query` in a channel message or thread reply and choose **Query** to insert a live question. Ask with Enter or the Ask button, then accept the answer before sending the message. Enter in the question box belongs to the question and must not send the channel draft. Recipients can read the live answer subject to their database access. Database @ mentions in message composers remain compact; **Expand** turns one into an editable database card.diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.mdindex 071fcbe288..88b121046d 100644--- a/docs/AGENT_GUIDE/databases.md+++ b/docs/AGENT_GUIDE/databases.md@@ -44,7 +44,7 @@ PostHog unless the variable was set when it was built. With the flag off:- `/app/database/<uuid>` and a `~/database/<uuid>` split show the 404 view. Thedatabase block's code is never fetched and no database request is made.- **Create → Database**, its **C → L** shortcut, the command palette entry and- the slash menu's **Database** action are absent, and no starter database is+ the slash menu's **Database** and **Query** actions are absent, and no starter database iscreated.- The sidebar, mentions, search and Quick Access list no databases; Activityand the ReadActivity tool leave out database rows.@@ -473,7 +473,7 @@ offers **Open view**, which opens that database/table and selects the created viThe same tools are exposed to agent sessions through the Macro MCP server.In a document, channel composer, or the task/document creation composer,-`/database` → **Database** opens the question box with the AI prompt focused+`/query` → **Query** opens the question box with the AI prompt focusedimmediately. The empty input rotates through example questions; a selected databaseuses its actual table and column names. Typing hides these hints, and reduced-motionpreferences keep them static. Use the searchable source picker below the question to@@ -578,6 +578,13 @@ A slow or failed refresh is not a reason to resend a successful mutation.### Embedded database editors+In a document, `/database` creates a database and inserts its expanded editor.+Selecting an existing database from `@` inserts a compact chip. Its expand icon+opens the editor. **Collapse** returns it to a small mention. Cell and schema+edits use the same database grid and authorization as the standalone app. The+document stores only the database reference and selected table/view, never a+copy of its rows. See [Databases in documents](documents.md#databases-in-documents).+The shared editor also runs under a host's `DatabaseProvider`, using schema reads,row queries and operation batches from that host's API. Verify cell edits andcolumn edits on the host surface, not only in the Macro database block. A hostdiff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 3e053c24e2..1e6a98278e 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -96,13 +96,39 @@ Markdown also needs a successful `/sync/document/.../connect` WebSocket upgrade.A 403 there indicates the sync origin check, which the local proxy handles forHTTPS machine hostnames; verify the proxy configuration before retrying.-## Live database answers+## Databases in documentsOpening the slash menu with `/` lists Normal Text, headings, and the other-Markdown options before Database. Typing `/database` filters to the Database-action.+Markdown options before Query and Database. Typing `/database` selects+**Database**: it creates an Untitled database with its first table and Name+column, then inserts its live editor at the command's position. Rename the+database in the embedded header. A failed create clears its pending placeholder;+removing the placeholder while creation runs does not insert elsewhere.++Selecting a database from `@` inserts a compact mention. Use its **Expand database**+icon to open the inline editor. Databases created with `/database` start expanded.+Edit cells, add rows or columns, select a table with the **Database table** picker,+choose a saved view with **Database view** when the table has views, filter, and+sort in the document using the same toolbar controls as the full database app.+The **Filter** and **Sort** icons open their panels. The pickers support keyboard+navigation and mark the selected table. Rows added or edited elsewhere, including+by AI, appear through the database's gateway subscription. The editor catches up after+reconnecting or returning to the tab after a long absence.+Edits write to the original database. **Open** opens the full database.+**Collapse** converts the editor to a small mention; **Expand** brings it back.+Removing either reference leaves the database and its rows intact.++Document permission controls changing the reference. Database permission controls+editing its rows, columns and name, independently of document permission. An+expanded editor in a read-only document can still edit a writable database;+its collapse/expand is local to that reader. A database viewer sees read-only+records. Sharing the document does not itself grant database access. Filters,+sort order and widths are local to this visit; the selected table and view are+saved in the Lexical node when the document is editable and sync to other readers.++## Live database answers-With Databases on, type `/database` and choose **Database** to insert a live answer+With Databases on, type `/query` and choose **Query** to insert a live answerto a question about a database. Answers run with each reader's database access andrefresh when referenced tables change. See[Databases](databases.md#ai-questions-and-live-answers) for the question box, sourcediff --git a/packages/lexical-core/nodes/DocumentCardNode.ts b/packages/lexical-core/nodes/DocumentCardNode.tsindex eab52c5a2e..2edff64c71 100644--- a/packages/lexical-core/nodes/DocumentCardNode.ts+++ b/packages/lexical-core/nodes/DocumentCardNode.ts@@ -337,7 +337,13 @@ export class DocumentCardNode extends DecoratorBlockNode<decorate(_: LexicalEditor, config: EditorConfig) {const componentProps = this.exportComponentProps();- const signature = JSON.stringify(componentProps);+ // Database editors observe their node's location through the editor. A+ // table/view change must preserve the live decorator and its focused menu.+ const signature = JSON.stringify(+ this.__blockName === 'database'+ ? { ...componentProps, blockParams: undefined }+ : componentProps+ );if (this.__cachedDecoratorComponent &&this.__cachedDecoratorSignature === signaturediff --git a/packages/lexical-core/tests/channel-mentions.test.ts b/packages/lexical-core/tests/channel-mentions.test.tsindex d95b6734a0..a92f997fdb 100644--- a/packages/lexical-core/tests/channel-mentions.test.ts+++ b/packages/lexical-core/tests/channel-mentions.test.ts@@ -6,6 +6,15 @@ function documentMention(id: string, blockName: string): string {}describe('extractChannelMentionsFromMarkdown', () => {+ it('keeps an expanded database referenced and deduplicates its compact mention', () => {+ const card =+ '<m-document-card>{"documentId":"db-1","documentName":"Tasks","blockName":"database"}</m-document-card>';+ expect(+ extractChannelMentionsFromMarkdown(+ `${card}\n\n${documentMention('db-1', 'database')}`+ )+ ).toEqual([{ entityType: 'database', entityId: 'db-1' }]);+ });it('returns no mentions for plain text', () => {expect(extractChannelMentionsFromMarkdown('just some text')).toEqual([]);});diff --git a/packages/lexical-core/tests/document-reference-decorator-stability.test.ts b/packages/lexical-core/tests/document-reference-decorator-stability.test.tsindex c297665949..17245c3f89 100644--- a/packages/lexical-core/tests/document-reference-decorator-stability.test.ts+++ b/packages/lexical-core/tests/document-reference-decorator-stability.test.ts@@ -88,3 +88,40 @@ it.each(['mention', 'card'] as const)();});++it('keeps a database editor mounted when its serialized table and view change', () => {+ setDecorator(DocumentCardNode, () => null);+ const editor = createHeadlessEditor({ nodes: SupportedNodeTypes });+ let key = '';+ let original: unknown;+ editor.update(+ () => {+ const node = $createDocumentCardNode({+ documentId: 'db-1',+ documentName: 'Tasks',+ blockName: 'database',+ blockParams: { tableId: 'table-1' },+ });+ $getRoot().append(node);+ key = node.getKey();+ original = node.decorate(editor, editor._config);+ },+ { discrete: true }+ );+ editor.update(+ () => {+ const node = $getNodeByKey<DocumentCardNode>(key)!;+ node.setBlockParams({ tableId: 'table-2', viewId: 'view-2' });+ expect(node.getLatest().decorate(editor, editor._config)).toBe(original);+ },+ { discrete: true }+ );+ editor.read(() => {+ expect(+ $getNodeByKey<DocumentCardNode>(key)!.exportJSON().blockParams+ ).toEqual({+ tableId: 'table-2',+ viewId: 'view-2',+ });+ });+});diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.tsindex dfe167a436..0f2a6318d5 100644--- a/packages/lexical-core/utils/mentions.ts+++ b/packages/lexical-core/utils/mentions.ts@@ -97,7 +97,15 @@ function documentMentionEntityType(blockName: string): string {return (match(blockName).with(- P.union('channel', 'project', 'chat', 'call', 'automation', 'form'),+ P.union(+ 'channel',+ 'project',+ 'chat',+ 'call',+ 'automation',+ 'form',+ 'database'+ ),(kind) => kind)// A routine is still referenced under its old item type.@@ -137,7 +145,8 @@ export function $extractChannelMentions(): ChannelMention[] {for (const { node } of $dfsIterator($getRoot())) {if ($isDocumentMentionNode(node) ||- ($isDocumentCardNode(node) && node.getBlockName() === 'form')+ ($isDocumentCardNode(node) &&+ (node.getBlockName() === 'form' || node.getBlockName() === 'database'))) {push({entityType: documentMentionEntityType(node.getBlockName()),diff --git a/packages/lexical-core/utils/message-references.ts b/packages/lexical-core/utils/message-references.tsindex 1fab3083d3..97b6facf59 100644--- a/packages/lexical-core/utils/message-references.ts+++ b/packages/lexical-core/utils/message-references.ts@@ -6,6 +6,7 @@ export type MessageReferenceKind =| 'bot'| 'document'| 'form'+ | 'database'| 'channel'| 'thread'| 'call'@@ -38,6 +39,7 @@ export function messageReference('bot','document','form',+ 'database','channel','thread','call',