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
fix(database): polish editing and keyboard navigation (#8153)
Wolf Mermelsteindb2c8b77aeba
diff --git a/apps/web/src/components/drag-drop/create-reorder.ts b/apps/web/src/components/drag-drop/create-reorder.tsindex 320f0b6bfb..08f4c3b371 100644--- a/apps/web/src/components/drag-drop/create-reorder.ts+++ b/apps/web/src/components/drag-drop/create-reorder.ts@@ -106,6 +106,11 @@ export function createReorderItem(if (!options.canDrag() ||event.button !== 0 ||+ // Solid portals bubble through their component owner, even when the+ // menu is physically outside the handle. Those presses must not drag.+ !(event.currentTarget instanceof Element) ||+ !(event.target instanceof Node) ||+ !event.currentTarget.contains(event.target) ||(event.target instanceof Element &&event.target.closest(options.ignore)))diff --git a/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/api.browser.e2e.tsindex 23b1901cbf..2b870f0711 100644--- a/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts+++ b/apps/web/src/features/block-database/browser-test/api.browser.e2e.ts@@ -1,12 +1,129 @@import { expect, test } from '@playwright/test';+import { openFixture } from './open-fixture';++test('holding a column type menu item never starts a column drag', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(page, '/src/features/block-database/browser-test/api.html');+ await page+ .getByRole('button', { name: 'Name column menu', exact: true })+ .click();+ await page.getByRole('menuitem', { name: 'Change type' }).hover();+ const checkbox = page.getByRole('menuitem', {+ name: 'Checkbox',+ exact: true,+ });+ await expect(checkbox).toBeVisible();+ await checkbox.hover();+ await page.mouse.down();+ const destination = await page+ .getByRole('columnheader', { name: 'Status', exact: true })+ .boundingBox();+ if (!destination) throw new Error('Missing destination column');+ await page.mouse.move(+ destination.x + destination.width - 10,+ destination.y + 15,+ { steps: 8 }+ );+ await expect(page.locator('[data-column-drag-preview]')).toHaveCount(0);+ await expect(page.locator('[data-column-drop-indicator]')).toHaveCount(0);+ await page.mouse.up();+ await expect(page.getByLabel('API writes')).toHaveText('0');+ await page.keyboard.press('Escape');+ await page.keyboard.press('Escape');+ // The header itself remains draggable.+ await page+ .getByRole('columnheader', { name: 'Name', exact: true })+ .getByText('Name', { exact: true })+ .hover();+ await page.mouse.down();+ await page.mouse.move(+ destination.x + destination.width - 10,+ destination.y + 15,+ { steps: 8 }+ );+ await expect(page.locator('[data-column-drag-preview]')).toHaveCount(1);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ await expect(page.getByLabel('API writes')).toHaveText('0');+});++test('database titles stay static until Rename is requested and save without entering the grid', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(page, '/src/features/block-database/browser-test/api.html');+ await expect(+ page.getByText('Untitled database', { exact: true })+ ).toBeVisible();+ await expect(+ page.getByRole('textbox', { name: 'Database name' })+ ).toHaveCount(0);+ await page+ .getByRole('button', { name: 'Rename database', exact: true })+ .click();+ const title = page.getByRole('textbox', { name: 'Database name' });+ await expect(title).toBeFocused();+ await title.fill('Projects');+ await title.press('Enter');+ await expect(title).toHaveCount(0);+ await expect(page.getByText('Projects', { exact: true })).toBeVisible();+ await expect(page.getByRole('textbox', { name: 'Edit Name' })).toHaveCount(0);+ await page+ .getByRole('button', { name: 'Rename database', exact: true })+ .click();+ await title.fill('Discarded');+ await title.press('Escape');+ await expect(title).toHaveCount(0);+ await expect(page.getByText('Projects', { exact: true })).toBeVisible();+});++test('adds a column and starts naming it while creation is still saving', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(+ page,+ '/src/features/block-database/browser-test/api.html?holdColumnWrites'+ );+ await page.getByRole('button', { name: 'Add column', exact: true }).click();+ const name = page.getByRole('textbox', { name: 'Column name', exact: true });+ await expect(name).toBeFocused();+ await expect(page.getByLabel('API writes')).toHaveText('0');+ await name.fill('Tasks');+ await name.press('Enter');+ await expect(name).toHaveCount(0);+ await expect(+ page.getByRole('columnheader', { name: 'Tasks', exact: true })+ ).toBeVisible();+ // The schema may still show its previous name while the rename is queued.+ const editor = page.getByRole('textbox', { name: /^Edit (Unnamed|Tasks)$/ });+ await expect(editor).toBeFocused();+ await expect(page.getByLabel('API writes')).toHaveText('0');+ await editor.fill('First task');+ await editor.press('Enter');+ await expect(editor).toBeFocused();+ await expect(page.getByLabel('API writes')).toHaveText('0');+ await page.getByRole('button', { name: 'Release column saves' }).click();+ await expect(+ page.getByRole('columnheader', { name: 'Tasks', exact: true })+ ).toBeVisible();+ await expect(page.getByLabel('API writes')).toHaveText('3');+ await expect(+ page.getByRole('button', { name: /^Tasks: First task\./ })+ ).toBeVisible();+});test('an API-only host pages rows, writes cells and creates columns through the shared controller', async ({page,}) => {- await page.routeWebSocket('**', (socket) => socket.close());await page.route('https://**', (route) => route.abort());await page.route('**/__macro_dev/**', (route) => route.abort());- await page.goto('/src/features/block-database/browser-test/api.html');+ await openFixture(page, '/src/features/block-database/browser-test/api.html');await expect(page.getByRole('grid', { name: 'API records' })).toBeVisible();await expect(page.getByRole('button', { name: /^Name: Second\./ })diff --git a/apps/web/src/features/block-database/browser-test/api.tsx b/apps/web/src/features/block-database/browser-test/api.tsxindex 50925bf54a..380ac3e72f 100644--- a/apps/web/src/features/block-database/browser-test/api.tsx+++ b/apps/web/src/features/block-database/browser-test/api.tsx@@ -1,9 +1,10 @@import '@app/index.css';import type { OpResult } from '@core/database-sql/generated/types';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';-import { errAsync, okAsync } from 'neverthrow';+import { errAsync, okAsync, ResultAsync } from 'neverthrow';import { createSignal } from 'solid-js';import { render } from 'solid-js/web';+import { DatabaseTitle } from '../../database/components/database-title';import { DatabaseProvider } from '../../database/context/database';import type { DatabaseApi, DatabaseTableSchema } from '../../database/core/api';import type { DatabaseRow } from '../../database/core/table';@@ -16,8 +17,14 @@ const statusId = '00000000-0000-0000-0000-000000000003';const optionId = '00000000-0000-0000-0000-000000000004';function ApiFixture() {+ const [name, setName] = createSignal('Untitled database');+ let editTitle: (() => void) | undefined;const [editable, setEditable] = createSignal(true);const [writes, setWrites] = createSignal(0);+ let releaseColumnWrites!: () => void;+ const columnWriteGate = new Promise<void>((resolve) => {+ releaseColumnWrites = resolve;+ });const [view, setView] = createSignal<DatabaseViewState>({query: { filter: null },layout: { kind: 'table', columns: [] },@@ -65,95 +72,111 @@ function ApiFixture() {tableVersion: table.version,});},- applyOps: ({ ops }) => {- const results: OpResult[] = [];- const version = table.version + 1;- for (const op of ops) {- if (- op.kind === 'column' &&- op.change.kind === 'create' &&- op.change.definition.source === 'new'- ) {- table = {- ...table,- version,- columns: [- ...table.columns,- {- id: op.column,- name: op.change.definition.name,- dataType: 'STRING',- writable: true,- isMultiSelect: false,- options: [],+ applyOps: ({ ops }) =>+ ResultAsync.fromSafePromise(+ ops.some((op) => op.kind === 'column' && op.change.kind === 'create')+ ? new URLSearchParams(location.search).has('holdColumnWrites')+ ? columnWriteGate+ : new Promise<void>((resolve) =>+ setTimeout(+ resolve,+ Number(+ new URLSearchParams(location.search).get('columnDelay') ?? 0+ )+ )+ )+ : Promise.resolve()+ ).andThen(() => {+ const results: OpResult[] = [];+ const version = table.version + 1;+ for (const op of ops) {+ if (+ op.kind === 'column' &&+ op.change.kind === 'create' &&+ op.change.definition.source === 'new'+ ) {+ table = {+ ...table,+ version,+ columns: [+ ...table.columns,+ {+ id: op.column,+ name: op.change.definition.name,+ dataType: 'STRING',+ writable: true,+ isMultiSelect: false,+ options: [],+ },+ ],+ };+ results.push({+ kind: 'column',+ table: tableId,+ column: op.column,+ tableVersion: version,+ change: { kind: 'created' },+ });+ } else if (op.kind === 'column' && op.change.kind === 'rename') {+ const name = op.change.name;+ table = {+ ...table,+ version,+ columns: table.columns.map((column) =>+ column.id === op.column ? { ...column, name } : column+ ),+ };+ results.push({+ kind: 'column',+ table: tableId,+ column: op.column,+ tableVersion: version,+ change: { kind: 'renamed' },+ });+ } else if (+ op.kind === 'rows' &&+ op.change.kind === 'update' &&+ op.change.changes.kind === 'per_row'+ ) {+ for (const change of op.change.changes.rows)+ rows = rows.map((row) =>+ row.rowId === change.row+ ? {+ ...row,+ cells: {+ ...row.cells,+ ...Object.fromEntries(+ change.cells.map((cell) => [+ cell.column,+ cell.value.type === 'text'+ ? cell.value.value+ : null,+ ])+ ),+ },+ }+ : row+ );+ table = { ...table, version };+ results.push({+ kind: 'rows',+ table: tableId,+ tableVersion: version,+ change: {+ kind: 'updated',+ affected: op.change.changes.rows.length,},- ],- };- results.push({- kind: 'column',- table: tableId,- column: op.column,- tableVersion: version,- change: { kind: 'created' },- });- } else if (op.kind === 'column' && op.change.kind === 'rename') {- const name = op.change.name;- table = {- ...table,- version,- columns: table.columns.map((column) =>- column.id === op.column ? { ...column, name } : column- ),- };- results.push({- kind: 'column',- table: tableId,- column: op.column,- tableVersion: version,- change: { kind: 'renamed' },- });- } else if (- op.kind === 'rows' &&- op.change.kind === 'update' &&- op.change.changes.kind === 'per_row'- ) {- for (const change of op.change.changes.rows)- rows = rows.map((row) =>- row.rowId === change.row- ? {- ...row,- cells: {- ...row.cells,- ...Object.fromEntries(- change.cells.map((cell) => [- cell.column,- cell.value.type === 'text' ? cell.value.value : null,- ])- ),- },- }- : row- );- table = { ...table, version };- results.push({- kind: 'rows',- table: tableId,- tableVersion: version,- change: {- kind: 'updated',- affected: op.change.changes.rows.length,- },- });- } else- return errAsync({- code: 'INVALID_OP',- refusal: null,- message: 'Unsupported fixture operation',- });- }- setWrites((count) => count + 1);- return okAsync({ results });- },+ });+ } else+ return errAsync({+ code: 'INVALID_OP' as const,+ refusal: null,+ message: 'Unsupported fixture operation',+ });+ }+ setWrites((count) => count + 1);+ return okAsync({ results });+ }),};return (<QueryClientProvider@@ -163,6 +186,15 @@ function ApiFixture() {><main class="flex h-screen flex-col bg-panel text-ink"><div class="flex gap-4 p-4">+ <DatabaseTitle+ name={name()}+ canEdit={editable()}+ onRename={setName}+ onEditReady={(edit) => {+ editTitle = edit;+ }}+ />+ <button onClick={() => editTitle?.()}>Rename database</button><button onClick={() => setEditable((value) => !value)}>Toggle editing</button>@@ -184,6 +216,13 @@ function ApiFixture() {Show board</button><output aria-label="API writes">{writes()}</output>+ <button+ type="button"+ onMouseDown={(event) => event.preventDefault()}+ onClick={releaseColumnWrites}+ >+ Release column saves+ </button></div><DatabaseProviderapi={api}diff --git a/apps/web/src/features/block-database/browser-test/open-fixture.ts b/apps/web/src/features/block-database/browser-test/open-fixture.tsnew file mode 100644index 0000000000..fe367eaeff--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/open-fixture.ts@@ -0,0 +1,22 @@+import type { Page } from '@playwright/test';++/** Retry canceled startup module requests when the devbox's container network changes. */+export async function openFixture(page: Page, url: string) {+ let networkChanged = false;+ const failed = (request: import('@playwright/test').Request) => {+ if (request.failure()?.errorText === 'net::ERR_NETWORK_CHANGED')+ networkChanged = true;+ };+ page.on('requestfailed', failed);+ try {+ for (let attempt = 0; attempt < 3; attempt++) {+ networkChanged = false;+ await page.goto(url);+ await page.waitForLoadState('networkidle');+ if (!networkChanged) return;+ }+ throw new Error('The devbox network kept canceling fixture startup.');+ } finally {+ page.off('requestfailed', failed);+ }+}diff --git a/apps/web/src/features/block-database/browser-test/rapid.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/rapid.browser.e2e.tsnew file mode 100644index 0000000000..9d86a2d946--- /dev/null+++ b/apps/web/src/features/block-database/browser-test/rapid.browser.e2e.ts@@ -0,0 +1,122 @@+import { expect, test } from '@playwright/test';+import { openFixture } from './open-fixture';++test('Enter moves down immediately before any pending save completes', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(+ page,+ '/src/features/block-database/browser-test/records.html?rapid&holdWrites'+ );+ await page.getByRole('button', { name: /^Name: First record\./ }).click();+ await page.keyboard.type('Saved first');+ await page.keyboard.press('Enter');+ const editor = page.getByRole('textbox', { name: 'Edit Name' });+ await expect(editor).toBeFocused();+ await expect(editor).toHaveText('');+ expect(+ await editor.evaluate((element) => {+ const selection = document.getSelection();+ return selection?.isCollapsed && element.contains(selection.anchorNode);+ })+ ).toBe(true);+ await expect(page.getByLabel('Stored name')).toHaveText('First record');+ await page.keyboard.type('Saved second');+ await page.keyboard.press('Enter');+ await expect(editor).toBeFocused();+ await expect(editor).toHaveText('');+ await page.keyboard.press('Shift+Enter');+ await expect(editor).toHaveText('Saved second');+ expect(+ await editor.evaluate((element) => {+ const selection = document.getSelection();+ return (+ selection?.isCollapsed &&+ element.contains(selection.anchorNode) &&+ selection.anchorOffset === 'Saved second'.length+ );+ })+ ).toBe(true);+ await page.keyboard.type('!');+ await page.keyboard.press('Enter');+ expect(+ JSON.parse(await page.getByLabel('Stored records').innerText())+ ).toHaveLength(1);+ await page.getByRole('button', { name: 'Release saves' }).click();+ await expect+ .poll(async () =>+ JSON.parse(await page.getByLabel('Stored records').innerText()).map(+ (row: { cells: Record<string, string> }) => row.cells.name+ )+ )+ .toEqual(['Saved first', 'Saved second!']);+});++test('a column inference response keeps the current draft focused and Tab saves into the same column', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(+ page,+ '/src/features/block-database/browser-test/records.html?rapid'+ );+ await page+ .getByRole('button', { name: 'notes: Empty. Click to edit' })+ .first()+ .click();+ const editor = page.getByRole('textbox', { name: 'Edit notes' });+ await page.keyboard.type('456');+ const original = await editor.elementHandle();+ await page.getByRole('button', { name: 'Infer numbers' }).click();+ expect(+ await editor.evaluate((element, original) => element === original, original)+ ).toBe(true);+ await expect(editor).toBeFocused();+ await page.keyboard.type('7');+ await page.keyboard.press('Tab');+ await expect(+ page.getByRole('textbox', { name: 'Edit detail' })+ ).toBeFocused();+ await page.keyboard.type('Next column');+ await page.keyboard.press('Tab');+ await expect+ .poll(+ async () =>+ JSON.parse(await page.getByLabel('Stored records').innerText())[0].cells+ )+ .toEqual({ name: 'First record', notes: 4567, detail: 'Next column' });+});++test('rapid typing and Tab keep values in their own cells while row saves arrive', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(+ page,+ '/src/features/block-database/browser-test/records.html?rapid'+ );+ await page.getByRole('button', { name: /^Name: First record\./ }).click();+ const expected = Array.from({ length: 6 }, (_, index) => ({+ name: `name-${index}`,+ notes: `notes-${index}`,+ detail: `detail-${index}`,+ }));+ for (const row of expected) {+ for (const value of Object.values(row)) {+ await page.keyboard.type(value);+ await page.keyboard.press('Tab');+ }+ }+ await expect+ .poll(async () =>+ JSON.parse(await page.getByLabel('Stored records').innerText()).map(+ (row: { cells: Record<string, string> }) => row.cells+ )+ )+ .toEqual(expected);+ await expect(page.getByRole('textbox', { name: 'Edit Name' })).toBeFocused();+});diff --git a/apps/web/src/features/block-database/browser-test/records.browser.e2e.ts b/apps/web/src/features/block-database/browser-test/records.browser.e2e.tsindex e192aecea0..4a11ada1eb 100644--- a/apps/web/src/features/block-database/browser-test/records.browser.e2e.ts+++ b/apps/web/src/features/block-database/browser-test/records.browser.e2e.ts@@ -1,14 +1,59 @@import { expect, test } from '@playwright/test';+import { openFixture } from './open-fixture';++test('Enter continues down the column and creates successive records from the blank row', async ({+ page,+}) => {+ await page.route('https://**', (route) => route.abort());+ await page.route('**/__macro_dev/**', (route) => route.abort());+ await openFixture(+ page,+ '/src/features/block-database/browser-test/records.html'+ );+ await page.getByRole('button', { name: /^Name: First record\./ }).click();+ const editor = page.getByRole('textbox', { name: 'Edit Name' });+ await editor.fill('Updated first');+ await editor.press('Enter');+ await expect(editor).toBeFocused();+ await expect(editor).toHaveValue('');+ await expect(page.getByLabel('Stored name')).toHaveText('Updated first');+ await editor.fill('Second record');+ await editor.press('Enter');+ await expect(editor).toBeFocused();+ await expect(editor).toHaveValue('');+ await expect(+ page.getByRole('button', { name: /^Name: Second record\./ })+ ).toBeVisible();+ await editor.fill('Third record');+ await editor.press('Enter');+ await expect(editor).toHaveValue('');+ await expect(+ page.getByRole('button', { name: /^Name: Third record\./ })+ ).toBeVisible();+ await expect(editor).toBeFocused();+ expect(+ await editor.evaluate((element) => ({+ border: getComputedStyle(element).borderWidth,+ shadow: getComputedStyle(element).boxShadow,+ }))+ ).toEqual({ border: '0px', shadow: 'none' });+ await editor.press('Shift+Enter');+ await expect(editor).toHaveValue('Third record');+ await editor.press('Enter');+ await expect(editor).toHaveValue('');+ await editor.press('Enter');+ await expect(page.locator('[data-grid-row-id]')).toHaveCount(4);+});test('edits embedded records without entity metadata or schema controls', async ({page,}) => {- await page.routeWebSocket('**', (socket) => socket.close());await page.route('https://**', (route) => route.abort());await page.route('**/__macro_dev/**', (route) => route.abort());- await page.goto('/src/features/block-database/browser-test/records.html', {- waitUntil: 'domcontentloaded',- });+ await openFixture(+ page,+ '/src/features/block-database/browser-test/records.html'+ );const grid = page.getByRole('grid', { name: 'Embedded records' });await expect(grid).toBeVisible();await expect(grid).toHaveAttribute('aria-colcount', '2');diff --git a/apps/web/src/features/block-database/browser-test/records.tsx b/apps/web/src/features/block-database/browser-test/records.tsxindex 9a0486951c..f1dfeedef8 100644--- a/apps/web/src/features/block-database/browser-test/records.tsx+++ b/apps/web/src/features/block-database/browser-test/records.tsx@@ -1,7 +1,8 @@import '@app/index.css';-import { okAsync } from 'neverthrow';+import { okAsync, ResultAsync } from 'neverthrow';import { createSignal } from 'solid-js';import { render } from 'solid-js/web';+import { CellMentionEditor } from '../../../components/cell-text-editor/CellMentionEditor';import type {DatabaseRowsSnapshot,DatabaseRowsSource,@@ -12,7 +13,15 @@ import { DatabaseRecordsView } from '../../database/views/database-records-view'// A host owns the records and writes. No database entity, saved view, or app provider.function RecordsFixture() {- const columns: DatabaseViewColumn[] = [+ const rapid = new URLSearchParams(location.search).has('rapid');+ const holdWrites = new URLSearchParams(location.search).has('holdWrites');+ let releaseWrites!: () => void;+ const writeGate = holdWrites+ ? new Promise<void>((resolve) => {+ releaseWrites = resolve;+ })+ : Promise.resolve();+ const initialColumns: DatabaseViewColumn[] = [{id: 'name',name: 'Name',@@ -22,6 +31,15 @@ function RecordsFixture() {options: [],},];+ if (rapid)+ initialColumns.push(+ ...['notes', 'detail'].map((id) => ({+ ...initialColumns[0],+ id,+ name: id,+ }))+ );+ const [columns, setColumns] = createSignal(initialColumns);const [snapshot, setSnapshot] = createSignal<DatabaseRowsSnapshot>({rows: [{ rowId: 'one', cells: { name: 'First record' } }],retained: [],@@ -30,7 +48,7 @@ function RecordsFixture() {const [canEdit, setCanEdit] = createSignal(true);let nextRow = 0;const source: DatabaseRowsSource = {- columns: () => columns,+ columns,snapshot,read: () => undefined,loading: () => false,@@ -39,34 +57,79 @@ function RecordsFixture() {refresh: () => okAsync(undefined),addOption: () => okAsync(undefined),retain: () => {},- write: (mutation) => {- const current = snapshot();- const version = (current.version ?? 0) + 1;- const insertedRowIds =- mutation.kind === 'create' ? [`created-${++nextRow}`] : [];- const rows =- mutation.kind === 'create'- ? [- ...current.rows,- { rowId: insertedRowIds[0], cells: mutation.values },- ]- : optimisticRows(current.rows, [mutation]);- setSnapshot({ rows, retained: [], version });- return okAsync({ version, insertedRowIds });- },+ write: (mutation) =>+ ResultAsync.fromSafePromise(+ holdWrites+ ? writeGate+ : rapid+ ? new Promise<void>((resolve) => setTimeout(resolve, 80))+ : Promise.resolve()+ ).andThen(() => {+ const current = snapshot();+ const version = (current.version ?? 0) + 1;+ const insertedRowIds =+ mutation.kind === 'create' ? [`created-${++nextRow}`] : [];+ const rows =+ mutation.kind === 'create'+ ? [+ ...current.rows,+ { rowId: insertedRowIds[0], cells: mutation.values },+ ]+ : optimisticRows(current.rows, [mutation]);+ setSnapshot({ rows, retained: [], version });+ return okAsync({ version, insertedRowIds });+ }),};return (<main class="flex h-screen flex-col bg-panel text-ink"><div class="flex gap-4 p-4"><button onClick={() => setCanEdit(false)}>Read only</button>+ {holdWrites && (+ <button+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => releaseWrites()}+ >+ Release saves+ </button>+ )}+ {rapid && (+ <button+ onMouseDown={(event) => event.preventDefault()}+ onClick={() =>+ setColumns((columns) =>+ columns.map((column) =>+ column.id === 'notes'+ ? { ...column, dataType: 'NUMBER' }+ : column+ )+ )+ }+ >+ Infer numbers+ </button>+ )}<output aria-label="Stored name">{snapshot().rows[0]?.cells.name}</output>+ <output aria-label="Stored records" class="sr-only">+ {JSON.stringify(snapshot().rows)}+ </output></div><DatabaseRecordsViewname="Embedded records"source={source}canEdit={canEdit()}+ renderTextEditor={+ rapid+ ? (props) => (+ <CellMentionEditor+ {...props}+ convertPaste={(text) => text}+ renderMenu={() => null}+ />+ )+ : undefined+ }view={{query: { filter: null },layout: { kind: 'table', columns: [] },diff --git a/apps/web/src/features/block-database/component/Block.tsx b/apps/web/src/features/block-database/component/Block.tsxindex 7b4a491ac3..c3ad34b1e4 100644--- a/apps/web/src/features/block-database/component/Block.tsx+++ b/apps/web/src/features/block-database/component/Block.tsx@@ -5,10 +5,8 @@ import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';import { useSplitLayout } from '@components/app/split-layout/layout';import {returnSplitToRecentListView,- useCanAutofocusSplitContent,useSplitPanelOrThrow,} from '@components/app/split-layout/layoutUtils';-import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';import { useHasPaidAccess } from '@core/auth/license';import { useBlockId } from '@core/block';import { DATABASE_MODEL, modelsForPlan } from '@core/component/AI/constant';@@ -76,8 +74,6 @@ const Block: Component = () => {const { replaceOrInsertSplit } = useSplitLayout();const orchestrator = useGlobalBlockOrchestrator();let requestedRecord: DatabaseRelatedDestination | undefined;- const canAutofocus = useCanAutofocusSplitContent();- const { navigatedFromJK } = useNavigatedFromJK();const userId = useUserId();const storage = createUserScopedStorage(`database-view-selection:${databaseId}`@@ -91,7 +87,6 @@ const Block: Component = () => {let gridEntry:| {tableId: string;- focus: () => Promise<void>;openRecord: (rowId: string) => void;}| undefined;@@ -142,15 +137,6 @@ const Block: Component = () => {});},});- let requestedGridEntry = false;- const enterFirstCell = () => {- if (!gridEntry || gridEntry.tableId !== activeTableId()) {- requestedGridEntry = true;- return;- }- requestedGridEntry = false;- void gridEntry.focus();- };const [openingChat, setOpeningChat] = createSignal(false);const hasPaidAccess = useHasPaidAccess();const { showPaywall } = usePaywallState();@@ -332,12 +318,6 @@ const Block: Component = () => {detail={detail()}canEdit={canEdit()}activeTable={activeTable()}- autoFocusTitle={- canAutofocus &&- !navigatedFromJK() &&- detail()?.database.name === 'Untitled database'- }- onTitleConfirm={enterFirstCell}onSelectTable={(tableId) =>setSelection((current) => ({ ...current, tableId }))}@@ -466,11 +446,9 @@ const Block: Component = () => {actionsRef={(actions) => {gridEntry = {tableId: table().table.id,- focus: actions.focusFirstCell,openRecord: actions.openRecord,};openRequestedRecord();- if (requestedGridEntry) enterFirstCell();}}renderToolbar={(actions) => (<DatabaseToolbardiff --git a/apps/web/src/features/block-database/component/TopBar.tsx b/apps/web/src/features/block-database/component/TopBar.tsxindex 7132c11961..75ea651208 100644--- a/apps/web/src/features/block-database/component/TopBar.tsx+++ b/apps/web/src/features/block-database/component/TopBar.tsx@@ -42,9 +42,6 @@ export function TopBar(props: {detail: DatabaseDetail | undefined;canEdit: boolean;activeTable: TableDetail | undefined;- /** Opens the title for typing, as for a freshly created database. */- autoFocusTitle: boolean;- onTitleConfirm: () => void;onSelectTable: (tableId: string) => void;onDelete: () => ResultAsync<void, DatabaseEntityFailure>;openingChat: boolean;@@ -90,8 +87,6 @@ export function TopBar(props: {<DatabaseTitlename={name()}canEdit={props.canEdit}- autoFocus={props.autoFocusTitle}- onConfirm={props.onTitleConfirm}onEditReady={(edit) => (editTitle = edit)}onRename={rename}/>diff --git a/apps/web/src/features/database/components/add-column-button.tsx b/apps/web/src/features/database/components/add-column-button.tsxindex 6ada7e4437..2a594208b1 100644--- a/apps/web/src/features/database/components/add-column-button.tsx+++ b/apps/web/src/features/database/components/add-column-button.tsx@@ -2,13 +2,13 @@ import PlusIcon from '@phosphor/plus.svg';import { Button } from '@ui/components/Button';import { createSignal, Show } from 'solid-js';import {+ type CreateDatabaseColumn,columnSchemaMessage,- type DatabaseSchemaChange,} from '../core/column-schema';/** Shared add-column control; the host owns schema persistence. */export function AddColumnButton(props: {- create(): DatabaseSchemaChange<string>;+ create: CreateDatabaseColumn;label?: string;onCreated?: (columnId: string) => boolean;}) {@@ -18,10 +18,16 @@ export function AddColumnButton(props: {if (pending()) return;setPending(true);setError('');- const created = await props.create();+ let announced = false;+ const created = await props.create((id) => {+ announced = true;+ props.onCreated?.(id);+ });setPending(false);created.match(- (id) => props.onCreated?.(id),+ (id) => {+ if (!announced) props.onCreated?.(id);+ },(error) => setError(columnSchemaMessage(error)));}diff --git a/apps/web/src/features/database/components/database-column-header.tsx b/apps/web/src/features/database/components/database-column-header.tsxindex 4d76a72c14..2bed939511 100644--- a/apps/web/src/features/database/components/database-column-header.tsx+++ b/apps/web/src/features/database/components/database-column-header.tsx@@ -50,6 +50,8 @@ import { OptionPill } from './select-pill';export type DatabaseColumnHeaderProps = {column: DatabaseViewColumn;registerRename?: (rename: (() => void) | undefined) => void;+ /** Enter accepts the name and starts editing this column's first cell. */+ onEnter?: () => void;onChangeType?: (columnId: string,change: DatabaseColumnTypeChange@@ -136,13 +138,21 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {const error = columnRename.error;const setError = columnRename.setError;const pending = () => operating() || columnRename.pending();+ const columnName = () =>+ columnRename.pending() && !columnRename.target()+ ? columnRename.draft().trim()+ : props.column.name;const rename = () => {if (!canRename() || pending()) return;setMenuOpen(false);columnRename.begin({ id: props.column.id, name: props.column.name });};const save = (restoreFocus: boolean) => {- if (canRename()) void columnRename.save(restoreFocus);+ if (canRename())+ void columnRename.save(+ restoreFocus,+ restoreFocus ? props.onEnter : undefined+ );};props.registerRename?.(rename);async function changeType(change: DatabaseColumnTypeChange) {@@ -314,7 +324,7 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {'opacity-40': props.dragging,}}role="columnheader"- aria-label={props.column.name}+ aria-label={columnName()}aria-sort={match(props.sortDirection).with('asc', () => 'ascending' as const).with('desc', () => 'descending' as const)@@ -378,7 +388,7 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {type={props.column.dataType}entityType={props.column.specificEntityType}/>- <span class="min-w-0 flex-1 truncate">{props.column.name}</span>+ <span class="min-w-0 flex-1 truncate">{columnName()}</span><Show when={props.sortDirection}><Showwhen={props.sortDirection === 'asc'}@@ -393,7 +403,7 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {<Dropdown.Triggervariant="ghost"size="icon-sm"- aria-label={`${props.column.name} column menu`}+ aria-label={`${columnName()} column menu`}><CaretDownIcon class="size-3" /></Dropdown.Trigger>diff --git a/apps/web/src/features/database/components/database-table.test.tsx b/apps/web/src/features/database/components/database-table.test.tsxindex 55fddae941..1dfb59ffb9 100644--- a/apps/web/src/features/database/components/database-table.test.tsx+++ b/apps/web/src/features/database/components/database-table.test.tsx@@ -865,39 +865,61 @@ describe('sort and column widths', () => {});});-it('selects a rectangle with Shift-click, announces both corners and clears the cells together', async () => {- const { onClearCells, onCellFocus, onWrite } = setup();- const first = document.querySelector<HTMLElement>(- '[data-grid-row-id="one"] [data-grid-column="1"]'- )!;- const last = document.querySelector<HTMLElement>(- '[data-grid-row-id="two"] [data-grid-column="3"]'- )!;- first.dispatchEvent(- new MouseEvent('pointerdown', { bubbles: true, button: 0 })- );- document.dispatchEvent(- new MouseEvent('pointerup', { bubbles: true, button: 0 })- );- last.dispatchEvent(- new MouseEvent('pointerdown', { bubbles: true, button: 0, shiftKey: true })- );- expect(document.querySelectorAll('[aria-selected="true"]')).toHaveLength(6);- expect(onCellFocus).toHaveBeenLastCalledWith({- rowId: 'one',- columnId: 'name',- endRowId: 'two',- endColumnId: 'notes',- editing: false,- });- fireEvent.keyDown(last, { key: 'Delete' });- await waitFor(() =>- expect(onClearCells).toHaveBeenCalledExactlyOnceWith(- ['one', 'two'],- ['name', 'computed', 'notes']- )- );- expect(onWrite).not.toHaveBeenCalled();- fireEvent.keyDown(last, { key: 'Escape' });- expect(document.querySelectorAll('[aria-selected="true"]')).toHaveLength(0);-});+it.each(['Delete', 'Backspace'])(+ 'selects a rectangle with Shift-click and clears it with %s',+ async (key) => {+ const { onClearCells, onCellFocus, onWrite } = setup();+ const first = document.querySelector<HTMLElement>(+ '[data-grid-row-id="one"] [data-grid-column="1"]'+ )!;+ const last = document.querySelector<HTMLElement>(+ '[data-grid-row-id="two"] [data-grid-column="3"]'+ )!;+ first.dispatchEvent(+ new MouseEvent('pointerdown', { bubbles: true, button: 0 })+ );+ document.dispatchEvent(+ new MouseEvent('pointerup', { bubbles: true, button: 0 })+ );+ last.dispatchEvent(+ new MouseEvent('pointerdown', {+ bubbles: true,+ button: 0,+ shiftKey: true,+ })+ );+ expect(document.querySelectorAll('[aria-selected="true"]')).toHaveLength(6);+ expect(onCellFocus).toHaveBeenLastCalledWith({+ rowId: 'one',+ columnId: 'name',+ endRowId: 'two',+ endColumnId: 'notes',+ editing: false,+ });+ fireEvent.keyDown(last, { key });+ await waitFor(() =>+ expect(onClearCells).toHaveBeenCalledExactlyOnceWith(+ ['one', 'two'],+ ['name', 'computed', 'notes']+ )+ );+ expect(onWrite).not.toHaveBeenCalled();+ fireEvent.keyDown(last, { key: 'Escape' });+ expect(document.querySelectorAll('[aria-selected="true"]')).toHaveLength(0);+ }+);++it.each(['Delete', 'Backspace'])(+ 'clears the focused grid cell with %s',+ async (key) => {+ const { onClearCells } = setup();+ const cell = document.querySelector<HTMLElement>(+ '[data-grid-row-id="one"] [data-grid-column="1"]'+ )!;+ cell.focus();+ fireEvent.keyDown(cell, { key });+ await waitFor(() =>+ expect(onClearCells).toHaveBeenCalledExactlyOnceWith(['one'], ['name'])+ );+ }+);diff --git a/apps/web/src/features/database/components/database-table.tsx b/apps/web/src/features/database/components/database-table.tsxindex bd2681a439..a25561ffa1 100644--- a/apps/web/src/features/database/components/database-table.tsx+++ b/apps/web/src/features/database/components/database-table.tsx@@ -177,15 +177,18 @@ export function DatabaseTable(props: DatabaseTableProps) {}};const controls = new Map<string, Map<string, GridCellControl>>();- let pendingEdit: { rowId: string; columnId: string } | undefined;+ let pendingEdit:+ | { rowId: string; columnId: string; selectAll?: boolean }+ | undefined;const control = (rowId: string, columnId: string) =>controls.get(rowId)?.get(columnId);const editRequestedCell = () => {if (!pendingEdit || !props.canEdit) return;const editor = control(pendingEdit.rowId, pendingEdit.columnId);if (!editor) return;+ const { selectAll } = pendingEdit;pendingEdit = undefined;- editor.edit();+ editor.edit(undefined, { selectAll });};props.controlsRef?.({editCell: (rowId, columnId) => {@@ -241,7 +244,7 @@ export function DatabaseTable(props: DatabaseTableProps) {const rowIndex = rows().findIndex((row) => row.id === rowId);const row = rows()[rowIndex + direction];if (rowIndex < 0 || !row || !column || !canEditCell(column)) return false;- pendingEdit = { rowId: row.id, columnId };+ pendingEdit = { rowId: row.id, columnId, selectAll: false };editRequestedCell();return true;};@@ -363,6 +366,19 @@ export function DatabaseTable(props: DatabaseTableProps) {const cell = target.closest<HTMLElement>('[data-grid-cell]');const grid = cell?.closest<HTMLElement>('[data-grid]');if (!cell || !grid) return;+ if (+ (event.key === 'Delete' || event.key === 'Backspace') &&+ props.canEdit &&+ props.onClearCells+ ) {+ const row = rows()[Number(cell.dataset.gridRow)];+ const column = columns()[Number(cell.dataset.gridColumn) - 1];+ if (!row || !column || !canEditCell(column)) return;+ event.preventDefault();+ event.stopPropagation();+ void props.onClearCells([row.id], [column.id]);+ return;+ }if (event.key === 'ContextMenu' ||(event.shiftKey && event.key === 'F10')@@ -544,6 +560,16 @@ export function DatabaseTable(props: DatabaseTableProps) {const column = () => header().column.columnDef.meta!;return (<DraggableColumnHeader+ onEnter={() => {+ const row = rows()[0];+ if (!row || !canEditCell(column())) return;+ pendingEdit = {+ rowId: row.id,+ columnId: column().id,+ selectAll: false,+ };+ editRequestedCell();+ }}registerRename={(rename) => {if (rename) headerRenames.set(column().id, rename);else headerRenames.delete(column().id);@@ -695,7 +721,7 @@ export function DatabaseTable(props: DatabaseTableProps) {)}aria-colindex={columnIndex() + 2}tabindex={-1}- class="relative min-w-0 border-r border-edge-muted/40 px-0.5 py-0.5 outline-none focus-within:ring-1 focus-within:ring-inset focus-within:ring-ink/40 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ink/50"+ class="relative min-w-0 border-r border-edge-muted/40 px-0.5 py-0.5 outline-none focus-within:ring-1 focus-within:ring-inset focus-within:ring-ink/30 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ink/30"classList={{'bg-accent/15 ring-1 ring-inset ring-accent/50':selection.contains(index(), columnIndex()),diff --git a/apps/web/src/features/database/components/database-title.test.tsx b/apps/web/src/features/database/components/database-title.test.tsxindex be0e807f3e..3b10d04b27 100644--- a/apps/web/src/features/database/components/database-title.test.tsx+++ b/apps/web/src/features/database/components/database-title.test.tsx@@ -4,16 +4,31 @@ import { DatabaseTitle } from './database-title';afterEach(cleanup);+function setup(name = 'Untitled database', canEdit = true) {+ let edit: (() => void) | undefined;+ const rename = vi.fn();+ render(() => (+ <DatabaseTitle+ name={name}+ canEdit={canEdit}+ onRename={rename}+ onEditReady={(start) => (edit = start)}+ />+ ));+ return { rename, edit: () => edit?.() };+}+describe('database title', () => {- it('focuses and selects a new database title without another click', () => {- render(() => (- <DatabaseTitle- name="Untitled database"- canEdit- autoFocus- onRename={vi.fn()}- />- ));+ it('shows a static title without taking focus on open', () => {+ setup();+ expect(screen.getByText('Untitled database')).toBeTruthy();+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(document.activeElement).toBe(document.body);+ });++ it('focuses and selects the title only when Rename is requested', () => {+ const { edit } = setup();+ edit();const input = screen.getByRole('textbox', {name: 'Database name',}) as HTMLInputElement;@@ -22,91 +37,45 @@ describe('database title', () => {expect(input.selectionEnd).toBe('Untitled database'.length);});- it('saves on Enter and then enters the grid', async () => {- const rename = vi.fn();- const enterGrid = vi.fn();- render(() => (- <DatabaseTitle- name="Untitled database"- canEdit- autoFocus- onRename={rename}- onConfirm={enterGrid}- />- ));+ it('saves on Enter and returns to a static label', () => {+ const { rename, edit } = setup();+ edit();const input = screen.getByRole('textbox', { name: 'Database name' });fireEvent.input(input, { target: { value: ' Summer offsite ' } });fireEvent.keyDown(input, { key: 'Enter' });expect(rename).toHaveBeenCalledExactlyOnceWith('Summer offsite');- await Promise.resolve();- expect(enterGrid).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('textbox')).toBeNull();});it('does not save Enter while composing the title', () => {- const rename = vi.fn();- const enterGrid = vi.fn();- render(() => (- <DatabaseTitle- name="Untitled database"- canEdit- autoFocus- onRename={rename}- onConfirm={enterGrid}- />- ));+ const { rename, edit } = setup();+ edit();const input = screen.getByRole('textbox', { name: 'Database name' });fireEvent.input(input, { target: { value: '計画' } });fireEvent.keyDown(input, { key: 'Enter', isComposing: true });expect(rename).not.toHaveBeenCalled();- expect(enterGrid).not.toHaveBeenCalled();expect(document.activeElement).toBe(input);});- it('discards the draft on Escape without entering the grid', async () => {- const rename = vi.fn();- const enterGrid = vi.fn();- render(() => (- <DatabaseTitle- name="Projects"- canEdit- autoFocus- onRename={rename}- onConfirm={enterGrid}- />- ));- const input = screen.getByRole('textbox') as HTMLInputElement;+ it('discards the draft on Escape and can reopen Rename', () => {+ const { rename, edit } = setup('Projects');+ edit();+ const input = screen.getByRole('textbox');fireEvent.input(input, { target: { value: 'Draft title' } });fireEvent.keyDown(input, { key: 'Escape' });- await Promise.resolve();expect(rename).not.toHaveBeenCalled();- expect(enterGrid).not.toHaveBeenCalled();- expect(input.value).toBe('Projects');- });-- it('focuses the title when the host asks to rename', () => {- let edit: (() => void) | undefined;- render(() => (- <DatabaseTitle- name="Projects"- canEdit- onRename={vi.fn()}- onEditReady={(start) => (edit = start)}- />- ));- edit?.();- expect(document.activeElement).toBe(- screen.getByRole('textbox', { name: 'Database name' })+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.getByText('Projects')).toBeTruthy();+ edit();+ expect(document.activeElement).toBe(screen.getByRole('textbox'));+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(+ 'Projects');});- it('shows a plain name without edit access', () => {- render(() => (- <DatabaseTitle- name="Shared database"- canEdit={false}- onRename={vi.fn()}- />- ));+ it('keeps the title read-only without edit access', () => {+ const { edit } = setup('Shared database', false);+ edit();expect(screen.getByText('Shared database')).toBeTruthy();expect(screen.queryByRole('textbox')).toBeNull();});diff --git a/apps/web/src/features/database/components/database-title.tsx b/apps/web/src/features/database/components/database-title.tsxindex 999282337b..5e86eb1605 100644--- a/apps/web/src/features/database/components/database-title.tsx+++ b/apps/web/src/features/database/components/database-title.tsx@@ -1,48 +1,37 @@-import { onCleanup, onMount, Show } from 'solid-js';+import { createSignal, onCleanup, onMount, Show } from 'solid-js';import { InlineTitleEditor } from '../../../lib/core/component/InlineTitleEditor';/** The split header's database name, edited in place by editors. */export function DatabaseTitle(props: {name: string;canEdit: boolean;- autoFocus?: boolean;- /** Runs after Enter commits the title. */- onConfirm?: () => void;onEditReady?: (edit: (() => void) | undefined) => void;onRename: (name: string) => void;}) {- let container: HTMLSpanElement | undefined;+ const [editing, setEditing] = createSignal(false);onMount(() =>props.onEditReady?.(() => {- const input = container?.querySelector('input');- input?.focus();- input?.select();+ if (props.canEdit) setEditing(true);}));onCleanup(() => props.onEditReady?.(undefined));return (<Show- when={props.canEdit}+ when={props.canEdit && editing()}fallback={<span class="inline-block truncate text-sm font-semibold">{props.name}</span>}>- <span- ref={container}- class="flex min-w-0"- onKeyDown={(event) => {- if (event.key === 'Enter' && !event.isComposing && props.onConfirm)- queueMicrotask(props.onConfirm);- }}- >+ <span class="flex min-w-0"><InlineTitleEditorvalue={props.name}placeholder="Untitled database"ariaLabel="Database name"class="text-sm"- autofocus={props.autoFocus}+ autofocus+ onExit={() => setEditing(false)}onRename={props.onRename}/></span>diff --git a/apps/web/src/features/database/components/grid-cell.test.tsx b/apps/web/src/features/database/components/grid-cell.test.tsxindex 78a5c25f07..fdec069f9e 100644--- a/apps/web/src/features/database/components/grid-cell.test.tsx+++ b/apps/web/src/features/database/components/grid-cell.test.tsx@@ -8,6 +8,7 @@ import {import userEvent from '@testing-library/user-event';import { createSignal, onMount } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CellMentionEditor } from '../../../components/cell-text-editor/CellMentionEditor';import type { DatabaseMention } from '../core/column-inference';import type {DatabaseCellValue,@@ -119,6 +120,96 @@ describe('grid cell', () => {fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' });});+ it('keeps the active text editor and draft when an earlier save infers the column type', () => {+ const [schema, setSchema] = createSignal({ ...column, inferType: true });+ const onWrite = vi.fn(async () => true);+ const onNavigate = vi.fn(() => true);+ render(() => (+ <GridCell+ column={schema()}+ value={null}+ canEdit+ renderTextEditor={(props) => (+ <CellMentionEditor+ {...props}+ convertPaste={(text) => text}+ renderMenu={() => null}+ />+ )}+ onWrite={onWrite}+ onAddOption={vi.fn(async () => true)}+ onNavigate={onNavigate}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));+ const editor = screen.getByRole('textbox', { name: 'Edit Name' });+ editor.textContent = '456';+ fireEvent.input(editor);+ setSchema({ ...column, dataType: 'NUMBER', inferType: false });+ expect(screen.getByRole('textbox', { name: 'Edit Name' })).toBe(editor);+ expect(document.activeElement).toBe(editor);+ expect(editor.textContent).toBe('456');+ fireEvent.keyDown(editor, { key: 'Tab' });+ expect(onWrite).toHaveBeenCalledExactlyOnceWith(456);+ expect(onNavigate).toHaveBeenCalledExactlyOnceWith(1);+ });+ it.each(['STRING', 'NUMBER', 'BOOLEAN', 'SELECT_STRING'] as const)(+ 'clears a selected %s cell with either Delete key',+ async (dataType) => {+ const onWrite = vi.fn(async () => true);+ render(() => (+ <GridCell+ column={{+ ...column,+ dataType,+ options: [{ id: 'open', label: 'Open', color: null }],+ }}+ value={+ dataType === 'STRING' || dataType === 'SELECT_STRING' ? 'Open' : 12+ }+ canEdit+ onWrite={onWrite}+ onAddOption={vi.fn(async () => true)}+ />+ ));+ const trigger =+ dataType === 'BOOLEAN'+ ? screen.getByRole('checkbox')+ : screen.getByRole('button');+ trigger.focus();+ for (const key of ['Delete', 'Backspace']) {+ fireEvent.keyDown(trigger, { key });+ await waitFor(() => expect(onWrite).toHaveBeenLastCalledWith(null));+ }+ expect(onWrite).toHaveBeenCalledTimes(2);+ expect(screen.queryByRole('textbox')).toBeNull();+ }+ );++ it('keeps an empty cell visually blank when the host supplies no placeholder', () => {+ const onWrite = vi.fn(async () => true);+ render(() => (+ <GridCell+ column={column}+ value={null}+ emptyLabel=""+ canEdit+ onWrite={onWrite}+ onAddOption={vi.fn(async () => true)}+ />+ ));+ const cell = screen.getByRole('button', {+ name: 'Name: Empty. Click to edit',+ });+ expect(cell.textContent).toBe('');+ fireEvent.click(cell);+ const input = screen.getByRole('textbox', {+ name: 'Edit Name',+ }) as HTMLInputElement;+ expect(input.placeholder).toBe('');+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onWrite).not.toHaveBeenCalled();+ });it.each(['STRING', 'SELECT_STRING'] as const)('lets Tab leave a %s editor at a grid boundary',async (dataType) => {diff --git a/apps/web/src/features/database/components/grid-cell.tsx b/apps/web/src/features/database/components/grid-cell.tsxindex 7b4d998aeb..03239d437a 100644--- a/apps/web/src/features/database/components/grid-cell.tsx+++ b/apps/web/src/features/database/components/grid-cell.tsx@@ -187,7 +187,7 @@ export function GridCell(props: GridCellProps) {? { width: `${size.width}px`, height: `${size.height}px` }: undefined;};- const updateEditor = (seed?: string) => {+ const updateEditor = (seed?: string, selectAll = true) => {if (!editable()) return;setSelectedMention(undefined);if (isEntity()) {@@ -198,7 +198,7 @@ export function GridCell(props: GridCellProps) {setMentionOpen(true);return;}- setSelectAll(seed === undefined);+ setSelectAll(seed === undefined && selectAll);setDraft(seed !== undefined? seed@@ -216,13 +216,13 @@ export function GridCell(props: GridCellProps) {setMentionOpen(true);}};- const beginEdit = (seed?: string, event?: Event) => {+ const beginEdit = (seed?: string, event?: Event, selectAll = true) => {if (!editable()) return;if (props.preserveSize && !editing() && trigger) {const { width, height } = trigger.getBoundingClientRect();setEditorSize({ width, height });}- opening.measure(() => updateEditor(seed), event, !editing());+ opening.measure(() => updateEditor(seed, selectAll), event, !editing());};const updateDraft = (value: string) => {setDraft(value);@@ -284,12 +284,12 @@ export function GridCell(props: GridCellProps) {else if (isBoolean() && !editable()) booleanWrapper?.focus();else trigger?.focus();},- edit: (seed) => {+ edit: (seed, options) => {if (!editable()) return;if (hasPopupEditor()) popupControl?.edit(seed);else if (props.column.dataType === 'BOOLEAN') trigger?.focus();else if (editing()) focusEditor?.();- else beginEdit(seed);+ else beginEdit(seed, undefined, options?.selectAll);},}));@@ -421,7 +421,7 @@ export function GridCell(props: GridCellProps) {onNavigate={props.onNavigate}onOpen={openMention()}onBeginEdit={beginEdit}- onClearEntity={() => {+ onClear={() => {setSelectedMention(undefined);void write(null);}}@@ -472,6 +472,16 @@ function navigateOnTab(}}+function isClearCellKey(event: KeyboardEvent) {+ return (+ (event.key === 'Delete' || event.key === 'Backspace') &&+ !event.ctrlKey &&+ !event.metaKey &&+ !event.altKey &&+ !isComposingKey(event)+ );+}+function BooleanCell(props: {column: DatabaseViewColumn;value: DatabaseCellValue;@@ -501,6 +511,12 @@ function BooleanCell(props: {disabled={!props.editable}onChange={(checked) => void props.onWrite(checked ? 1 : 0)}onKeyDown={(event: KeyboardEvent) => {+ if (props.editable && isClearCellKey(event)) {+ event.preventDefault();+ event.stopPropagation();+ void props.onWrite(null);+ return;+ }if (!isComposingKey(event)) navigateOnTab(event, props.onNavigate);}}>@@ -530,7 +546,7 @@ function TextCell(props: {onNavigate?: (direction: 1 | -1) => boolean;onOpen?: () => void;onBeginEdit: (seed?: string, event?: Event) => void;- onClearEntity: () => void;+ onClear: () => void;}) {// Refreshes rebuild row objects; only a changed value may rerun renderers and remount previews.const value = createMemo(() => props.value);@@ -593,22 +609,15 @@ function TextCell(props: {event.altKey)return;- if (- props.isEntity &&- (event.key === 'Backspace' || event.key === 'Delete')- ) {+ if (isClearCellKey(event)) {event.preventDefault();event.stopPropagation();- props.onClearEntity();+ props.onClear();} else if (event.key === 'Enter' || event.key === 'F2') {event.preventDefault();event.stopPropagation();props.onBeginEdit(undefined, event);- } else if (- event.key.length === 1 ||- event.key === 'Backspace' ||- event.key === 'Delete'- ) {+ } else if (event.key.length === 1) {event.preventDefault();event.stopPropagation();props.onBeginEdit(event.key.length === 1 ? event.key : '', event);@@ -626,7 +635,7 @@ function TextCell(props: {props.renderTextValue? props.renderTextValue(String(value())): formatted()) || (- <span class="opacity-40">{props.emptyLabel || '—'}</span>+ <span class="opacity-40">{props.emptyLabel ?? '—'}</span>)}>@@ -679,6 +688,10 @@ function InlineEditor(props: {props.column.dataType === 'ENTITY' &&props.originalValue !== null &&props.draft === '';+ // An earlier row's save can settle this column's type while this editor is+ // focused. Keep its DOM for this edit; use the latest type when committing.+ const renderTextEditor =+ props.column.dataType === 'STRING' ? props.renderTextEditor : undefined;const initialDraft =props.originalValue === null ? '' : String(props.originalValue);const focus = () => {@@ -728,7 +741,8 @@ function InlineEditor(props: {}if (event.key === 'Enter') {event.preventDefault();- commit();+ if (commit(!props.onNavigateRow))+ props.onNavigateRow?.(event.shiftKey ? -1 : 1);}if (event.key === 'Escape') {event.preventDefault();@@ -763,7 +777,7 @@ function InlineEditor(props: {><Tooltip.Trigger as="div" tabindex={-1} class="relative min-w-0"><Show- when={props.column.dataType === 'STRING' && props.renderTextEditor}+ when={renderTextEditor}fallback={<inputref={(element) => {@@ -794,9 +808,9 @@ function InlineEditor(props: {if (!props.mentionOpen) commit(false);}}onKeyDown={onKeyDown}- class="min-h-9 w-full min-w-0 rounded border border-ink/40 px-2.5 py-1.5 text-[13px] text-ink outline-none ring-2 ring-ink/10 aria-invalid:border-failure aria-invalid:ring-failure"+ class="min-h-9 w-full min-w-0 px-2.5 py-1.5 text-[13px] text-ink outline-none"classList={{- 'bg-input-focus': !showingReference(),+ 'bg-transparent': !showingReference(),'bg-transparent caret-transparent': showingReference(),}}/>@@ -809,7 +823,7 @@ function InlineEditor(props: {return props.draft;},class:- 'min-h-9 w-full min-w-0 rounded border border-ink/40 bg-input-focus px-2.5 py-1.5 text-[13px] text-ink outline-none ring-2 ring-ink/10',+ 'min-h-9 w-full min-w-0 bg-transparent px-2.5 py-1.5 text-[13px] text-ink outline-none',autoFocus: true,selectAll: props.selectAll,inferType: props.column.inferType,@@ -924,7 +938,9 @@ function SelectCell(props: GridCellProps) {edit: (event) => edit(undefined, event),close: () => setOpen(false),});- onMount(() => props.onReady?.({ focus: keys.focus, edit }));+ onMount(() =>+ props.onReady?.({ focus: keys.focus, edit: (seed) => edit(seed) })+ );onCleanup(() => props.onReady?.(undefined));function tabAway(event: KeyboardEvent, chosen: string | undefined) {if (event.key !== 'Tab' || !props.onNavigate) return;@@ -971,6 +987,12 @@ function SelectCell(props: GridCellProps) {return;}if (keys.tabFromTrigger(event)) return;+ if (isClearCellKey(event)) {+ event.preventDefault();+ event.stopPropagation();+ void props.onWrite(null);+ return;+ }if (event.key.length === 1 &&!event.ctrlKey &&@@ -1094,7 +1116,9 @@ function DateCell(props: GridCellProps) {edit: (event) => edit(undefined, event),close: () => setOpen(false),});- onMount(() => props.onReady?.({ focus: keys.focus, edit }));+ onMount(() =>+ props.onReady?.({ focus: keys.focus, edit: (seed) => edit(seed) })+ );onCleanup(() => props.onReady?.(undefined));const trigger = {'data-cell-display': '',@@ -1110,7 +1134,7 @@ function DateCell(props: GridCellProps) {},onKeyDown: (event: KeyboardEvent) => {if (isComposingKey(event) || keys.tabFromTrigger(event)) return;- if (event.key === 'Backspace' || event.key === 'Delete') {+ if (isClearCellKey(event)) {event.preventDefault();event.stopPropagation();void props.onWrite(null);diff --git a/apps/web/src/features/database/components/inline-rename.test.ts b/apps/web/src/features/database/components/inline-rename.test.tsindex 45374bb068..3682c3081f 100644--- a/apps/web/src/features/database/components/inline-rename.test.ts+++ b/apps/web/src/features/database/components/inline-rename.test.ts@@ -11,6 +11,44 @@ afterEach(() => {});describe('createInlineRename', () => {+ it('hands off focus before saving finishes and reports a refusal without taking focus back', async () => {+ let refuse!: (reason: string) => void;+ const restoreFocus = vi.fn();+ const onSubmit = vi.fn();+ const rename = createRoot((disposeRoot) => {+ dispose = disposeRoot;+ return createInlineRename({+ name: (target: { name: string }) => target.name,+ rename: () =>+ ResultAsync.fromPromise(+ new Promise<void>((_resolve, reject) => {+ refuse = reject;+ }),+ (failure) => String(failure)+ ),+ failureMessage: (failure) => failure,+ emptyName: { message: 'Enter a name.', onBlur: 'cancel' },+ input: () => undefined,+ restoreFocus,+ });+ });+ rename.begin({ name: 'Unnamed' });+ rename.setDraft('');+ await rename.save(true, onSubmit);+ expect(onSubmit).not.toHaveBeenCalled();+ expect(rename.target()).toEqual({ name: 'Unnamed' });+ rename.setDraft('Tasks');+ const saving = rename.save(true, onSubmit);+ expect(onSubmit).toHaveBeenCalledOnce();+ expect(rename.target()).toBeUndefined();+ expect(rename.pending()).toBe(true);+ refuse('Connection lost');+ await saving;+ expect(rename.error()).toBe('Connection lost');+ expect(rename.pending()).toBe(false);+ expect(restoreFocus).not.toHaveBeenCalled();+ });+it('begins with the current name as a selected, focused draft', async () => {const input = document.createElement('input');document.body.append(input);diff --git a/apps/web/src/features/database/components/inline-rename.ts b/apps/web/src/features/database/components/inline-rename.tsindex 50ad5a5f73..07ae4ec807 100644--- a/apps/web/src/features/database/components/inline-rename.ts+++ b/apps/web/src/features/database/components/inline-rename.ts@@ -56,7 +56,8 @@ export function createInlineRename<Target, Failure>(options: {cancel: (restoreFocus: boolean) => {if (!pending()) finish(restoreFocus);},- save: async (restoreFocus: boolean) => {+ /** With onSubmit, close and hand off focus as soon as validation passes. */+ save: async (restoreFocus: boolean, onSubmit?: () => void) => {const current = target();if (current === undefined || pending()) return;const name = draft().trim();@@ -72,17 +73,24 @@ export function createInlineRename<Target, Failure>(options: {return;}if (name === options.name(current)) {- finish(restoreFocus);+ finish(onSubmit ? false : restoreFocus);+ onSubmit?.();return;}const renaming = options.rename(current, name);setPending(true);setError('');+ if (onSubmit) {+ finish(false);+ onSubmit();+ }const renamed = await renaming;if (disposed) return;setPending(false);renamed.match(- () => finish(restoreFocus),+ () => {+ if (!onSubmit) finish(restoreFocus);+ },(failure) => setError(options.failureMessage(failure)));},diff --git a/apps/web/src/features/database/core/column-schema.ts b/apps/web/src/features/database/core/column-schema.tsindex 67ced04d67..805762bed9 100644--- a/apps/web/src/features/database/core/column-schema.ts+++ b/apps/web/src/features/database/core/column-schema.ts@@ -55,6 +55,11 @@ export type DatabaseSchemaChange<Value = void> = ResultAsync<DatabaseOpsError>;+/** Announces the new column as soon as it can be edited, before persistence finishes. */+export type CreateDatabaseColumn = (+ onCreated?: (columnId: string) => void+) => DatabaseSchemaChange<string>;+/** What the grid says when the service refused a schema change. */export function columnSchemaMessage(error: DatabaseOpsError): string {return match(error)diff --git a/apps/web/src/features/database/core/grid-cell-editor.ts b/apps/web/src/features/database/core/grid-cell-editor.tsindex 4eca6b61fc..39d7f8bd47 100644--- a/apps/web/src/features/database/core/grid-cell-editor.ts+++ b/apps/web/src/features/database/core/grid-cell-editor.ts@@ -1,6 +1,6 @@export type GridCellControl = {focus: () => void;- edit: (seed?: string) => void;+ edit: (seed?: string, options?: { selectAll?: boolean }) => void;};export type GridCellEditorOptions = {diff --git a/apps/web/src/features/database/primitives/column-layout.ts b/apps/web/src/features/database/primitives/column-layout.tsindex ac7dba3fc1..ecaae0b298 100644--- a/apps/web/src/features/database/primitives/column-layout.ts+++ b/apps/web/src/features/database/primitives/column-layout.ts@@ -3,6 +3,7 @@ import { Mutex } from 'async-mutex';import { type Accessor, createSignal, onCleanup } from 'solid-js';import { reorderDatabaseColumns } from '../core/column-order';import {+ type CreateDatabaseColumn,columnSchemaMessage,type DatabaseSchemaChange,} from '../core/column-schema';@@ -30,7 +31,7 @@ export function createColumnLayout(options: {/** Saves the table's own column order, which All records follows. */saveColumnOrder?: (columnIds: string[]) => DatabaseSchemaChange;/** Creates a column at the table's end and returns its id. */- createColumn?: () => DatabaseSchemaChange<string>;+ createColumn?: CreateDatabaseColumn;/** Opens a header's rename, as for a column just inserted. */renameColumn: (columnId: string) => void;}) {diff --git a/apps/web/src/features/database/primitives/database-controller.test.ts b/apps/web/src/features/database/primitives/database-controller.test.tsindex 2113d90008..9f4eb161a2 100644--- a/apps/web/src/features/database/primitives/database-controller.test.ts+++ b/apps/web/src/features/database/primitives/database-controller.test.ts@@ -1,14 +1,20 @@-import { errAsync, okAsync } from 'neverthrow';-import { describe, expect, it, vi } from 'vitest';+import { err, errAsync, ok, okAsync, ResultAsync } from 'neverthrow';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';import type { DatabaseRowsSource } from '../context/table-source';import type { DatabaseApi, DatabaseCapabilities } from '../core/api';+import type { DatabaseViewColumn } from '../core/database-view';import { createDatabaseController } from './database-controller';+const disposers: (() => void)[] = [];+afterEach(() => disposers.splice(0).forEach((dispose) => dispose()));+function fixture(capabilities: DatabaseCapabilities = { editRows: true, editColumns: true }) {+ const [columns, setColumns] = createSignal<DatabaseViewColumn[]>([]);const rows: DatabaseRowsSource = {- columns: () => [],+ columns,snapshot: () => ({ rows: [], retained: [], version: 7 }),loading: () => false,refreshing: () => false,@@ -16,7 +22,7 @@ function fixture(refresh: () => okAsync(undefined),retain: () => {},addOption: () => okAsync(undefined),- write: () => okAsync({ insertedRowIds: [], version: 7 }),+ write: vi.fn(() => okAsync({ insertedRowIds: [], version: 7 })),};const applyOps = vi.fn<DatabaseApi['applyOps']>(() =>okAsync({ results: [] })@@ -30,22 +36,25 @@ function fixture(const refresh = vi.fn(() =>errAsync({ kind: 'fetch' as const, message: 'offline' }));- const controller = createDatabaseController({- api,- tableId: 'table',- capabilities: () => capabilities,- data: {- rows: { ...rows, refresh },- table: () => ({- id: 'table',- databaseId: 'db',- name: 'Table',- columns: [],- version: 7,- }),- },+ const controller = createRoot((dispose) => {+ disposers.push(dispose);+ return createDatabaseController({+ api,+ tableId: 'table',+ capabilities: () => capabilities,+ data: {+ rows: { ...rows, refresh },+ table: () => ({+ id: 'table',+ databaseId: 'db',+ name: 'Table',+ columns: columns(),+ version: 7,+ }),+ },+ });});- return { controller, applyOps, refresh, capabilities };+ return { controller, applyOps, refresh, capabilities, rows, setColumns };}describe('shared database controller', () => {@@ -55,6 +64,75 @@ describe('shared database controller', () => {expect(result.isOk()).toBe(true);expect(applyOps).toHaveBeenCalledTimes(1);expect(refresh).toHaveBeenCalledTimes(1);+ expect(controller.data.rows.columns().map((column) => column.id)).toEqual([+ result._unsafeUnwrap(),+ ]);+ });+ it('shows and focuses a column immediately, and saves its rename after creation', async () => {+ const { controller, applyOps } = fixture();+ let finish!: (result: Awaited<ReturnType<DatabaseApi['applyOps']>>) => void;+ applyOps.mockReturnValueOnce(+ new ResultAsync(+ new Promise((resolve) => {+ finish = resolve;+ })+ )+ );+ const onCreated = vi.fn();+ const created = controller.schemaEditing()!.createDefaultColumn(onCreated);+ const column = controller.data.rows.columns()[0];+ expect(column.name).toBe('Unnamed');+ expect(onCreated).toHaveBeenCalledExactlyOnceWith(column.id);+ const rename = controller+ .schemaEditing()!+ .rename(column.id, 'Tasks', 'Unnamed');+ await vi.waitFor(() => expect(applyOps).toHaveBeenCalledTimes(1));+ finish(ok({ results: [] }));+ expect((await created).isOk()).toBe(true);+ expect((await rename).isOk()).toBe(true);+ expect(applyOps.mock.calls[1][0].ops[0]).toMatchObject({+ column: column.id,+ change: { kind: 'rename', name: 'Tasks' },+ });+ });+ it('rolls back a refused column and rejects dependent cell writes', async () => {+ const { controller, applyOps, rows } = fixture();+ let finish!: (result: Awaited<ReturnType<DatabaseApi['applyOps']>>) => void;+ applyOps.mockReturnValueOnce(+ new ResultAsync(+ new Promise((resolve) => {+ finish = resolve;+ })+ )+ );+ const created = controller.schemaEditing()!.createDefaultColumn();+ const column = controller.data.rows.columns()[0];+ const write = controller.data.rows.write(+ { kind: 'cell', rowId: 'row', columnId: column.id, value: 'Draft' },+ 7,+ false+ );+ const failure = {+ code: 'FORBIDDEN' as const,+ refusal: null,+ message: 'Denied',+ };+ await vi.waitFor(() => expect(applyOps).toHaveBeenCalledTimes(1));+ expect(rows.write).not.toHaveBeenCalled();+ finish(err(failure));+ expect((await created).isErr()).toBe(true);+ expect(await write).toEqual(err({ kind: 'ops', error: failure }));+ expect(controller.data.rows.columns()).toEqual([]);+ expect(rows.write).not.toHaveBeenCalled();+ });+ it('does not duplicate an acknowledged column or resurrect it after deletion', async () => {+ const { controller, setColumns } = fixture();+ await controller.schemaEditing()!.createDefaultColumn();+ const column = controller.data.rows.columns()[0];+ setColumns([column]);+ expect(controller.data.rows.columns()).toEqual([column]);+ setColumns([]);+ expect(controller.data.rows.columns()).toEqual([]);});it('preserves a version refusal without retrying the mutation', async () => {const { controller, applyOps, refresh } = fixture();diff --git a/apps/web/src/features/database/primitives/database-controller.ts b/apps/web/src/features/database/primitives/database-controller.tsindex 0c29f06f2f..cc46d1ca50 100644--- a/apps/web/src/features/database/primitives/database-controller.ts+++ b/apps/web/src/features/database/primitives/database-controller.ts@@ -1,12 +1,23 @@import type { DatabaseOp } from '@core/database-sql/generated/types';-import { errAsync, ok } from 'neverthrow';-import type { Accessor } from 'solid-js';+import { errAsync, ok, ResultAsync } from 'neverthrow';+import {+ type Accessor,+ createEffect,+ createMemo,+ createSignal,+ on,+} from 'solid-js';import { v7 as uuidv7 } from 'uuid';import type { FormulaEditing } from '../context/formula-editing';import type { OptionEditing } from '../context/option-editing';import type { DatabaseApi, DatabaseCapabilities } from '../core/api';import { mergeDatabaseColumnOrder } from '../core/column-order';-import type { DatabaseColumnTypeChange } from '../core/column-schema';+import type {+ CreateDatabaseColumn,+ DatabaseColumnTypeChange,+ DatabaseSchemaChange,+} from '../core/column-schema';+import type { DatabaseViewColumn } from '../core/database-view';import { defaultDatabaseColumnName } from '../core/property-creation';import type { DatabaseDataSource } from '../queries/api-source';@@ -19,6 +30,56 @@ export function createDatabaseController(args: {inferNewColumns?: boolean;}) {const { api, data, tableId } = args;+ const [createdColumns, setCreatedColumns] = createSignal<+ DatabaseViewColumn[]+ >([]);+ const creating = new Map<string, DatabaseSchemaChange<string>>();+ const columns = createMemo(() => {+ const read = data.rows.columns();+ const added = createdColumns().filter(+ (column) => !read.some((received) => received.id === column.id)+ );+ return added.length ? [...read, ...added] : read;+ });+ // Drop local previews once the external schema acknowledges them, so a+ // subsequent deletion cannot resurrect a column from the preview.+ createEffect(+ on(data.rows.columns, (received) => {+ setCreatedColumns((columns) =>+ columns.filter(+ (column) => !received.some((read) => read.id === column.id)+ )+ );+ })+ );+ const ready = () =>+ ResultAsync.combine([...creating.values()]).map(() => undefined);+ const shownData: DatabaseDataSource = {+ table: () => {+ const table = data.table();+ return table ? { ...table, columns: columns() } : undefined;+ },+ rows: {+ ...data.rows,+ columns,+ write: (mutation, baseVersion, createOptions) => {+ const waitingForColumn = creating.size > 0;+ return ready()+ .mapErr((error) => ({ kind: 'ops' as const, error }))+ .andThen(() =>+ data.rows.write(+ mutation,+ waitingForColumn+ ? (data.table()?.version ?? baseVersion)+ : baseVersion,+ createOptions+ )+ );+ },+ addOption: (columnId, label) =>+ ready().andThen(() => data.rows.addOption(columnId, label)),+ },+ };const apply = (ops: DatabaseOp[], baseVersion?: number) =>api.applyOps({@@ -35,7 +96,7 @@ export function createDatabaseController(args: {);const schemaApply: typeof apply = (ops, version) =>args.capabilities().editColumns- ? apply(ops, version)+ ? ready().andThen(() => apply(ops, version)): errAsync({code: 'FORBIDDEN',refusal: null,@@ -51,20 +112,54 @@ export function createDatabaseController(args: {version).map(() => undefined);const schemaEditing = {- createDefaultColumn: () => {+ createDefaultColumn: ((onCreated?: (columnId: string) => void) => {+ if (!args.capabilities().editColumns)+ return errAsync({+ code: 'FORBIDDEN',+ refusal: null,+ message: 'You cannot edit columns.',+ });const column = uuidv7();- return change(column, {+ const name = defaultDatabaseColumnName(+ columns().map((column) => column.name)+ );+ const inferType = args.inferNewColumns ?? false;+ setCreatedColumns((columns) => [+ ...columns,+ {+ id: column,+ name,+ dataType: 'STRING',+ writable: true,+ isMultiSelect: false,+ options: [],+ inferType,+ },+ ]);+ const created = change(column, {kind: 'create',definition: {source: 'new',- name: defaultDatabaseColumnName(- data.rows.columns().map((column) => column.name)- ),+ name,type: { type: 'text' },- inferType: args.inferNewColumns ?? false,+ inferType,},- }).map(() => column);- },+ })+ .map(() => {+ creating.delete(column);+ return column;+ })+ .mapErr((error) => {+ creating.delete(column);+ setCreatedColumns((columns) =>+ columns.filter((current) => current.id !== column)+ );+ return error;+ });+ creating.set(column, created);+ onCreated?.(column);+ return created;+ }) satisfies CreateDatabaseColumn,rename: (column: string, name: string, previousName: string) =>change(column, { kind: 'rename', name, previousName }),remove: (column: string) =>@@ -158,7 +253,7 @@ export function createDatabaseController(args: {})),};return {- data,+ data: shownData,optionEditing: () =>args.capabilities().editColumns ? optionEditing : undefined,formulaEditing: () =>diff --git a/apps/web/src/features/database/views/database-records-view.test.tsx b/apps/web/src/features/database/views/database-records-view.test.tsxindex 0df1607aa8..e760e19661 100644--- a/apps/web/src/features/database/views/database-records-view.test.tsx+++ b/apps/web/src/features/database/views/database-records-view.test.tsx@@ -310,7 +310,7 @@ describe('database table view', () => {boardPositions={unplacedCards}/>));- fireEvent.click(screen.getByRole('button', { name: /Name: Unnamed/ }));+ fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));const input = screen.getByRole('textbox', { name: 'Edit Name' });fireEvent.input(input, { target: { value: 'Saved once' } });fireEvent.keyDown(input, { key: 'Enter' });@@ -887,7 +887,7 @@ describe('database table view', () => {boardPositions={unplacedCards}/>));- fireEvent.click(screen.getByRole('button', { name: /Name: Unnamed/ }));+ fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));const name = screen.getByRole('textbox', { name: 'Edit Name' });fireEvent.input(name, { target: { value: 'Created from draft' } });fireEvent.keyDown(name, { key: 'Enter' });@@ -982,7 +982,7 @@ describe('database table view', () => {boardPositions={unplacedCards}/>));- fireEvent.click(screen.getByRole('button', { name: /Name: Unnamed/ }));+ fireEvent.click(screen.getByRole('button', { name: /Name: Empty/ }));const name = screen.getByRole('textbox', { name: 'Edit Name' });fireEvent.input(name, { target: { value: 'Created from draft' } });fireEvent.keyDown(name, { key: 'Enter' });@@ -1442,7 +1442,7 @@ describe('database table view', () => {/>));fireEvent.click(- screen.getByRole('button', { name: 'Name: Unnamed. Click to edit' })+ screen.getByRole('button', { name: 'Name: Empty. Click to edit' }));const draft = await screen.findByRole('textbox', { name: 'Edit Name' });fireEvent.input(draft, { target: { value: 'Outside view' } });@@ -2439,7 +2439,7 @@ describe('database table view', () => {fireEvent.click(within(screen.getByRole('grid', { name: 'Playground' })).getByRole('button',- { name: 'Name: Unnamed. Click to edit' }+ { name: 'Name: Empty. Click to edit' }));const name = await screen.findByRole('textbox', { name: 'Edit Name' });@@ -2457,9 +2457,9 @@ describe('database table view', () => {screen.getAllByRole('button', { name: /Name: First record/ })).toHaveLength(1));- expect(- screen.getByRole('button', { name: 'Name: Unnamed. Click to edit' })- ).toBeTruthy();+ const next = screen.getByRole('textbox', { name: 'Edit Name' });+ expect(document.activeElement).toBe(next);+ expect((next as HTMLInputElement).value).toBe('');expect(fixture.source.write).toHaveBeenCalledExactlyOnceWith({ kind: 'create', values: { title: 'First record' } },1,diff --git a/apps/web/src/features/database/views/database-records-view.tsx b/apps/web/src/features/database/views/database-records-view.tsxindex b1a8fdeaa7..eda3d6e034 100644--- a/apps/web/src/features/database/views/database-records-view.tsx+++ b/apps/web/src/features/database/views/database-records-view.tsx@@ -37,6 +37,7 @@ import type {DatabaseEntityType,} from '../core/column-inference';import type {+ CreateDatabaseColumn,DatabaseColumnCastsSource,DatabaseColumnConversion,DatabaseColumnTypeChange,@@ -139,7 +140,7 @@ export type DatabaseRecordsViewProps = {actionsRef?: (actions: DatabaseRecordsActions) => void;renderToolbar?: (actions: DatabaseRecordsActions) => JSX.Element;/** Create a new column at the end of the table and return its id. */- createColumn?: () => DatabaseSchemaChange<string>;+ createColumn?: CreateDatabaseColumn;addColumn?: (label?: string,onCreated?: (columnId: string) => boolean@@ -293,7 +294,7 @@ export function DatabaseRecordsView(props: DatabaseRecordsViewProps) {<GridCell{...options}column={column()}- emptyLabel={isTitle() ? 'Unnamed' : undefined}+ emptyLabel=""value={rowValue(row(), column().id)}canEdit={props.canEdit}renderTextEditor={props.renderTextEditor}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsxindex 18e8c6596e..199f4589c0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx@@ -1,3 +1,4 @@+import ArrowRightIcon from '@phosphor/arrow-right.svg';import { cn } from '@ui';import type { Accessor, ParentProps } from 'solid-js';import { Show } from 'solid-js';@@ -48,7 +49,8 @@ export function ItemBin(<Show when={showViewAllButton()}><buttontype="button"- class="text-xs font-medium hover:text-ink hover:underline flex items-center gap-1"+ class="inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md px-1.5 text-xs font-normal text-ink-muted outline-none hover:bg-hover hover:text-ink focus-visible:ring-1 focus-visible:ring-ink/30"+ aria-keyshortcuts={props.isSelected ? 'ArrowRight' : undefined}onMouseDown={(e) => {e.preventDefault();e.stopPropagation();@@ -59,12 +61,10 @@ export function ItemBin(props.onViewAll?.(props.binType);}}>- <Show when={props.isSelected && showViewAllButton()}>- <div class="p-0.5 px-1 -my-2 bg-surface text-ink border border-edge-muted rounded-xs text-xs">- →- </div>- </Show>{viewAllText()}+ <Show when={props.isSelected}>+ <ArrowRightIcon class="size-3 text-ink-extra-muted" />+ </Show></button></Show></div>diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex 95f8ca3fbc..e79eb8b25d 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -136,6 +136,7 @@"auth.getSubscriptionStatus": "Get Subscription Status","auth.changePlan": "Change Plan","auth.createPortalSession": "Create Portal Session",+ "auth.getTrialEligibility": "Get Trial Eligibility","auth.patchUserTutorial": "Patch User Tutorial","calendar.getAvailabilityCalendars": "Get Availability Calendars","calendar.setAvailabilityCalendar": "Set Availability Calendar",diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex e7288a3dbc..a5170f6784 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -9,7 +9,7 @@ async function VO($,O,x){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=k.pop()??"";for(let a of k){let i=a.split(``),_=[],y;for(let R of i)if(R.startsWith("data:"))_.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))Q=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let v=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(v))J=v}let D,h=!1;if(_.length){let R=_.join(`-`);try{D=JSON.parse(R),h=!0}catch{D=R}}if(h){if(S)await S(D);if(j)D=await j(D)}if(x?.({data:D,event:y,id:Q,retry:J}),_.length)yield D}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(A){if(O?.(A),G!==void 0&&B>=G)break;let C=Math.min(J*2**(B-1),Z??30000);await T(C)}}}()}}var A2=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C2=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},D2=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},aO=({allowReserved:$,explode:O,name:x,style:j,value:S})=>{if(!O){let Z=($?S:S.map((X)=>encodeURIComponent(X))).join(C2(j));switch(j){case"label":return`.${Z}`;case"matrix":return`;${x}=${Z}`;case"simple":return Z;default:return`${x}=${Z}`}}let K=A2(j),G=S.map((Z)=>{if(j==="label"||j==="simple")return $?Z:encodeURIComponent(Z);return $O({allowReserved:$,name:x,value:Z})}).join(K);return j==="label"||j==="matrix"?K+G:G},$O=({allowReserved:$,name:O,value:x})=>{if(x===void 0||x===null)return"";if(typeof x==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?x:encodeURIComponent(x)}`},iO=({allowReserved:$,explode:O,name:x,style:j,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${x}=${S.toISOString()}`;if(j!=="deepObject"&&!O){let X=[];Object.entries(S).forEach(([Y,Q])=>{X=[...X,Y,$?Q:encodeURIComponent(Q)]});let L=X.join(",");switch(j){case"form":return`${x}=${L}`;case"label":return`.${L}`;case"matrix":return`;${x}=${L}`;default:return L}}let G=D2(j),Z=Object.entries(S).map(([X,L])=>$O({allowReserved:$,name:j==="deepObject"?`${x}[${X}]`:X,value:L})).join(G);return j==="label"||j==="matrix"?G+Z:Z};var M2=/\{[^{}]+\}/g,P2=({path:$,url:O})=>{let x=O,j=O.match(M2);if(j)for(let S of j){let K=!1,G=S.substring(1,S.length-1),Z="simple";if(G.endsWith("*"))K=!0,G=G.substring(0,G.length-1);if(G.startsWith("."))G=G.substring(1),Z="label";else if(G.startsWith(";"))G=G.substring(1),Z="matrix";let X=$[G];if(X===void 0||X===null)continue;if(Array.isArray(X)){x=x.replace(S,aO({explode:K,name:G,style:Z,value:X}));continue}if(typeof X==="object"){x=x.replace(S,iO({explode:K,name:G,style:Z,value:X,valueOnly:!0}));continue}if(Z==="matrix"){x=x.replace(S,`;${$O({name:G,value:X})}`);continue}let L=encodeURIComponent(Z==="label"?`.${X}`:X);x=x.replace(S,L)}return x},g0=({baseUrl:$,path:O,query:x,querySerializer:j,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,G=($??"")+K;if(O)G=P2({path:O,url:G});let Z=x?j(x):"";if(Z.startsWith("?"))Z=Z.substring(1);if(Z)G+=`?${Z}`;return G};function Cj($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var k0=async($,O)=>{let x=typeof O==="function"?await O($):O;if(!x)return;if($.scheme==="bearer")return`Bearer ${x}`;if($.scheme==="basic")return`Basic ${btoa(x)}`;return x};var y0={bodySerializer:($)=>JSON.stringify($,(O,x)=>typeof x==="bigint"?x.toString():x)};var h0=({parameters:$={},...O}={})=>{return(j)=>{let S=[];if(j&&typeof j==="object")for(let K in j){let G=j[K];if(G===void 0||G===null)continue;let Z=$[K]||O;if(Array.isArray(G)){let X=aO({allowReserved:Z.allowReserved,explode:!0,name:K,style:"form",value:G,...Z.array});if(X)S.push(X)}else if(typeof G==="object"){let X=iO({allowReserved:Z.allowReserved,explode:!0,name:K,style:"deepObject",value:G,...Z.object});if(X)S.push(X)}else{let X=$O({allowReserved:Z.allowReserved,name:K,value:G});if(X)S.push(X)}}return S.join("&")}},v0=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((x)=>O.startsWith(x)))return"blob";if(O.startsWith("text/"))return"text";return},_2=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function m0($){for(let O of $.security??[]){if(_2($,O.name))continue;let x=await k0(O,$.auth);if(!x)continue;let j=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[j]=x;break;case"cookie":$.headers.append("Cookie",`${j}=${x}`);break;case"header":default:$.headers.set(j,x);break}}}var Dj=($)=>g0({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:h0($.querySerializer),url:$.url}),Mj=($,O)=>{let x={...$,...O};if(x.baseUrl?.endsWith("/"))x.baseUrl=x.baseUrl.substring(0,x.baseUrl.length-1);return x.headers=sO($.headers,O.headers),x},F2=($)=>{let O=[];return $.forEach((x,j)=>{O.push([j,x])}),O},sO=(...$)=>{let O=new Headers;for(let x of $){if(!x)continue;let j=x instanceof Headers?F2(x):Object.entries(x);for(let[S,K]of j)if(K===null)O.delete(S);else if(Array.isArray(K))for(let G of K)O.append(S,G);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class nO{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let x=this.getInterceptorIndex($);if(this.fns[x])return this.fns[x]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var c0=()=>({error:new nO,request:new nO,response:new nO}),E2=h0({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),w2={"Content-Type":"application/json"},IO=($={})=>({...y0,headers:w2,parseAs:"auto",querySerializer:E2,...$});var Pj=($={})=>{let O=Mj(IO(),$),x=()=>({...O}),j=(Y)=>{return O=Mj(O,Y),x()},S=c0(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:sO(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await m0(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=Dj(T);return{opts:T,url:z}},G=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:J,url:B}=await K(Y),I={redirect:"follow",...J,body:Cj(J)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,J);let P=J.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,J);let A={request:z,response:W};if(W.ok){let N=(J.parseAs==="auto"?v0(W.headers.get("Content-Type")):J.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return J.responseStyle==="data"?U:{data:U,...A}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return J.responseStyle==="data"?W.body:{data:W.body,...A}}if(N==="json"){if(J.responseValidator)await J.responseValidator(H);if(J.responseTransformer)H=await J.responseTransformer(H)}return J.responseStyle==="data"?H:{data:H,...A}}let C=await W.text(),F;try{F=JSON.parse(C)}catch{}throw F??C}catch(J){let B=J;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},Z=(Y)=>(Q)=>G({...Q,method:Y}),X=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return b0({...T,body:T.body,method:Y,onRequest:async(W,J)=>{let B=new Request(W,J);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:Cj(T),url:z})};return{buildUrl:(Y)=>Dj({...O,...Y}),connect:Z("CONNECT"),delete:Z("DELETE"),get:Z("GET"),getConfig:x,head:Z("HEAD"),interceptors:S,options:Z("OPTIONS"),patch:Z("PATCH"),post:Z("POST"),put:Z("PUT"),request:G,setConfig:j,sse:{connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),head:X("HEAD"),options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),trace:X("TRACE")},trace:Z("TRACE")}};var d0=Pj(IO());class u0{client;constructor($){this.client=$?.client??d0}}class l0{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class eO extends u0{static __registry=new l0;constructor($){super($);eO.__registry.set(this,$?.key)}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function r0({onRequest:$,onSseError:O,onSseEvent:x,responseTransformer:j,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:G,sseMaxRetryDelay:Z,sseSleepFn:X,url:L,...Y}){let Q,T=X??((J)=>new Promise((B)=>setTimeout(B,J)));return{stream:async function*(){let J=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let A={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,A);if($)C=await $(L,A);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{D=JSON.parse(R),h=!0}catch{D=R}}if(h){if(S)await S(D);if(j)D=await j(D)}if(x?.({data:D,event:y,id:Q,retry:J}),_.length)yield D}}}finally{I.removeEventListener("abort",g),H.releaseLock()}break}catch(A){if(O?.(A),G!==void 0&&B>=G)break;let C=Math.min(J*2**(B-1),Z??30000);await T(C)}}}()}}var A2=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C2=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},D2=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},aO=({allowReserved:$,explode:O,name:x,style:j,value:S})=>{if(!O){let Z=($?S:S.map((X)=>encodeURIComponent(X))).join(C2(j));switch(j){case"label":return`.${Z}`;case"matrix":return`;${x}=${Z}`;case"simple":return Z;default:return`${x}=${Z}`}}let K=A2(j),G=S.map((Z)=>{if(j==="label"||j==="simple")return $?Z:encodeURIComponent(Z);return $O({allowReserved:$,name:x,value:Z})}).join(K);return j==="label"||j==="matrix"?K+G:G},$O=({allowReserved:$,name:O,value:x})=>{if(x===void 0||x===null)return"";if(typeof x==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?x:encodeURIComponent(x)}`},iO=({allowReserved:$,explode:O,name:x,style:j,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${x}=${S.toISOString()}`;if(j!=="deepObject"&&!O){let X=[];Object.entries(S).forEach(([Y,Q])=>{X=[...X,Y,$?Q:encodeURIComponent(Q)]});let L=X.join(",");switch(j){case"form":return`${x}=${L}`;case"label":return`.${L}`;case"matrix":return`;${x}=${L}`;default:return L}}let G=D2(j),Z=Object.entries(S).map(([X,L])=>$O({allowReserved:$,name:j==="deepObject"?`${x}[${X}]`:X,value:L})).join(G);return j==="label"||j==="matrix"?G+Z:Z};var M2=/\{[^{}]+\}/g,P2=({path:$,url:O})=>{let x=O,j=O.match(M2);if(j)for(let S of j){let K=!1,G=S.substring(1,S.length-1),Z="simple";if(G.endsWith("*"))K=!0,G=G.substring(0,G.length-1);if(G.startsWith("."))G=G.substring(1),Z="label";else if(G.startsWith(";"))G=G.substring(1),Z="matrix";let X=$[G];if(X===void 0||X===null)continue;if(Array.isArray(X)){x=x.replace(S,aO({explode:K,name:G,style:Z,value:X}));continue}if(typeof X==="object"){x=x.replace(S,iO({explode:K,name:G,style:Z,value:X,valueOnly:!0}));continue}if(Z==="matrix"){x=x.replace(S,`;${$O({name:G,value:X})}`);continue}let L=encodeURIComponent(Z==="label"?`.${X}`:X);x=x.replace(S,L)}return x},g0=({baseUrl:$,path:O,query:x,querySerializer:j,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,G=($??"")+K;if(O)G=P2({path:O,url:G});let Z=x?j(x):"";if(Z.startsWith("?"))Z=Z.substring(1);if(Z)G+=`?${Z}`;return G};function Cj($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var k0=async($,O)=>{let x=typeof O==="function"?await O($):O;if(!x)return;if($.scheme==="bearer")return`Bearer ${x}`;if($.scheme==="basic")return`Basic ${btoa(x)}`;return x};var y0={bodySerializer:($)=>JSON.stringify($,(O,x)=>typeof x==="bigint"?x.toString():x)};var h0=({parameters:$={},...O}={})=>{return(j)=>{let S=[];if(j&&typeof j==="object")for(let K in j){let G=j[K];if(G===void 0||G===null)continue;let Z=$[K]||O;if(Array.isArray(G)){let X=aO({allowReserved:Z.allowReserved,explode:!0,name:K,style:"form",value:G,...Z.array});if(X)S.push(X)}else if(typeof G==="object"){let X=iO({allowReserved:Z.allowReserved,explode:!0,name:K,style:"deepObject",value:G,...Z.object});if(X)S.push(X)}else{let X=$O({allowReserved:Z.allowReserved,name:K,value:G});if(X)S.push(X)}}return S.join("&")}},v0=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((x)=>O.startsWith(x)))return"blob";if(O.startsWith("text/"))return"text";return},_2=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function m0($){for(let O of $.security??[]){if(_2($,O.name))continue;let x=await k0(O,$.auth);if(!x)continue;let j=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[j]=x;break;case"cookie":$.headers.append("Cookie",`${j}=${x}`);break;case"header":default:$.headers.set(j,x);break}}}var Dj=($)=>g0({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:h0($.querySerializer),url:$.url}),Mj=($,O)=>{let x={...$,...O};if(x.baseUrl?.endsWith("/"))x.baseUrl=x.baseUrl.substring(0,x.baseUrl.length-1);return x.headers=sO($.headers,O.headers),x},F2=($)=>{let O=[];return $.forEach((x,j)=>{O.push([j,x])}),O},sO=(...$)=>{let O=new Headers;for(let x of $){if(!x)continue;let j=x instanceof Headers?F2(x):Object.entries(x);for(let[S,K]of j)if(K===null)O.delete(S);else if(Array.isArray(K))for(let G of K)O.append(S,G);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class nO{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let x=this.getInterceptorIndex($);if(this.fns[x])return this.fns[x]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var c0=()=>({error:new nO,request:new nO,response:new nO}),E2=h0({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),w2={"Content-Type":"application/json"},IO=($={})=>({...y0,headers:w2,parseAs:"auto",querySerializer:E2,...$});var Pj=($={})=>{let O=Mj(IO(),$),x=()=>({...O}),j=(Y)=>{return O=Mj(O,Y),x()},S=c0(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:sO(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await m0(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=Dj(T);return{opts:T,url:z}},G=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:J,url:B}=await K(Y),I={redirect:"follow",...J,body:Cj(J)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,J);let P=J.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,J);let A={request:z,response:W};if(W.ok){let N=(J.parseAs==="auto"?v0(W.headers.get("Content-Type")):J.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return J.responseStyle==="data"?U:{data:U,...A}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return J.responseStyle==="data"?W.body:{data:W.body,...A}}if(N==="json"){if(J.responseValidator)await J.responseValidator(H);if(J.responseTransformer)H=await J.responseTransformer(H)}return J.responseStyle==="data"?H:{data:H,...A}}let C=await W.text(),F;try{F=JSON.parse(C)}catch{}throw F??C}catch(J){let B=J;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},Z=(Y)=>(Q)=>G({...Q,method:Y}),X=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return b0({...T,body:T.body,method:Y,onRequest:async(W,J)=>{let B=new Request(W,J);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:Cj(T),url:z})};return{buildUrl:(Y)=>Dj({...O,...Y}),connect:Z("CONNECT"),delete:Z("DELETE"),get:Z("GET"),getConfig:x,head:Z("HEAD"),interceptors:S,options:Z("OPTIONS"),patch:Z("PATCH"),post:Z("POST"),put:Z("PUT"),request:G,setConfig:j,sse:{connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),head:X("HEAD"),options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),trace:X("TRACE")},trace:Z("TRACE")}};var d0=Pj(IO());class u0{client;constructor($){this.client=$?.client??d0}}class l0{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class eO extends u0{static __registry=new l0;constructor($){super($);eO.__registry.set(this,$?.key)}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function r0({onRequest:$,onSseError:O,onSseEvent:x,responseTransformer:j,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:G,sseMaxRetryDelay:Z,sseSleepFn:X,url:L,...Y}){let Q,T=X??((J)=>new Promise((B)=>setTimeout(B,J)));return{stream:async function*(){let J=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let A={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,A);if($)C=await $(L,A);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let k=U.split(``);U=k.pop()??"";for(let a of k){let i=a.split(`diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.mdindex 3464c0ac95..301f6dd4d4 100644--- a/docs/agent-guide/databases.md+++ b/docs/agent-guide/databases.md@@ -1,8 +1,8 @@# DatabasesChoose **Create → Database** to create a database and its first table with a Name-column. **C → L** opens a new database with its title selected and ready to type.-Enter saves the title and focuses A1, ready to type without another click.+column. **C → L** opens a new database with the normal static split-header title;+opening or creating it does not start renaming or move focus into a cell.Opening **Ctrl-K** refreshes database discovery so a database created by AI oranother client appears without reloading. **All** and **Documents** categoriesmatch its name, including databases with no view history.@@ -19,8 +19,9 @@ Databases open atthey open inline at `/app/drive/database/<uuid>` with Drive's sidebar in place.A database contains tables; records belong to a table andits properties describe each record. The database name in the split header is an-inline input for editors: click it to rename. Enter or leaving it saves; Escape-cancels, and a failed rename shows a toast. Viewers without edit access see the+static label, matching other blocks. Choose **Rename** in Database actions to+edit it. Enter or leaving the input saves and closes it; Escape cancels. Saving+a title does not enter the grid, and a failed rename shows a toast. Viewers without edit access see thesplit header's `viewer` badge instead.Reopening a loaded table or view shows its cached rows while a background read@@ -140,7 +141,11 @@ editing still works. The standalone database app keeps its full column controls.Use **Add column** immediately after the table’s headers. It creates an **Unnamed**Text column (**Unnamed 2**, and so on if that name exists), selects its name in the-header, and lets you type immediately. Enter saves; Escape keeps the default name.+header, and lets you type immediately while creation saves in the background.+Renaming or editing the new column waits for creation to finish; a refused+creation removes the preview and shows an error. Enter saves the name and immediately+puts the typing cursor in that column's first cell, without waiting for creation+or renaming to finish. Escape keeps the default name.There is no creation dialog. Double-click a header, press F2 while it is focused,or choose **Rename column** from its arrow or right-click menu to rename it later.Its type icon stays in place while editing. SQL refers to tables and columns by@@ -183,6 +188,8 @@ is refused ("Total's formula uses Quantity; change that formula first").**Delete column** opens a confirmation;it removes this table’s column and values while preserving other tables.Drag a column header left or right to reorder it, or use **Move left / Move right**.+Holding or dragging a column menu item, including a type choice, does not move+the column; a drag must start on the header itself.To add a column next to another, right-click its header and choose **Insert left** or**Insert right**: a Text column appears on that side with its name selected forediting, and its type is inferred from what you type.@@ -253,13 +260,21 @@ An editable empty row always follows the records. Enter a value in any of itscells to create a record; the next empty row appears immediately. Merely focusingor tabbing through an empty row does not save an empty record.Click a cell to edit, or focus it with the arrow keys and start typing. Enter-saves and keeps that cell selected; Down then selects the same column in the-next row, ready to type. Arrow keys inside a text editor keep their native cursor+saves and immediately edits the same column in the next row, including the empty+new-record row. Typing there starts the next record without waiting for the+previous save. Shift+Enter moves up. Both place the typing cursor at the end of+the destination cell's text, ready to type. The active cell has one subtle outline,+with no additional border around its editor. Arrow keys inside a text editor keep their native cursorbehavior. Escape cancels. Tab saves and immediately edits the next writable cell;Shift+Tab moves backward, and both wrap between rows. Read-only columns are-skipped. Select values open the option picker; checkboxes change+skipped. If a pending save infers a column's type, the cell currently being typed+in keeps its editor, draft and focus until it is committed or canceled.+Select values open the option picker; checkboxes changedirectly. Type on a selected select cell to search its options; Enter chooses amatch, and Tab chooses the highlighted option or typed match before moving on.+Blank cells stay visually blank; no `Unnamed` placeholder is inserted. Delete+and Backspace both clear a selected cell immediately, including select and+checkbox cells. While editing text, they retain their normal text-editing behavior.Number cells display thousands separators (for example, `100,000`); opening aneditor shows the raw number for editing. Invalid numbers and integers outside thesafe integer range stay in the editor with a failure outline instead of saving adiff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.mdindex 1a961c5987..25040381b5 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md@@ -195,6 +195,11 @@- [GetTeamInvitesResponses](type-aliases/GetTeamInvitesResponses.md)- [GetTeamResponse](type-aliases/GetTeamResponse.md)- [GetTeamResponses](type-aliases/GetTeamResponses.md)+- [GetTrialEligibilityData](type-aliases/GetTrialEligibilityData.md)+- [GetTrialEligibilityError](type-aliases/GetTrialEligibilityError.md)+- [GetTrialEligibilityErrors](type-aliases/GetTrialEligibilityErrors.md)+- [GetTrialEligibilityResponse](type-aliases/GetTrialEligibilityResponse.md)+- [GetTrialEligibilityResponses](type-aliases/GetTrialEligibilityResponses.md)- [GetUserInfo](type-aliases/GetUserInfo.md)- [GetUserInfoData](type-aliases/GetUserInfoData.md)- [GetUserInfoError](type-aliases/GetUserInfoError.md)@@ -526,6 +531,7 @@- [ToggleTeamNonAdminInvitesErrors](type-aliases/ToggleTeamNonAdminInvitesErrors.md)- [ToggleTeamNonAdminInvitesResponse](type-aliases/ToggleTeamNonAdminInvitesResponse.md)- [ToggleTeamNonAdminInvitesResponses](type-aliases/ToggleTeamNonAdminInvitesResponses.md)+- [TrialEligibility](type-aliases/TrialEligibility.md)- [UpdateAiBillingAutoReloadData](type-aliases/UpdateAiBillingAutoReloadData.md)- [UpdateAiBillingAutoReloadError](type-aliases/UpdateAiBillingAutoReloadError.md)- [UpdateAiBillingAutoReloadErrors](type-aliases/UpdateAiBillingAutoReloadErrors.md)diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityData.mdnew file mode 100644index 0000000000..0d39f0d30e--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityData.md@@ -0,0 +1,12 @@+# Type Alias: GetTrialEligibilityData++> **GetTrialEligibilityData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/user/stripe/trial_eligibility"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body?` | `never` |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/user/stripe/trial_eligibility"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityError.mdnew file mode 100644index 0000000000..951ac976bc--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityError.md@@ -0,0 +1,3 @@+# Type Alias: GetTrialEligibilityError++> **GetTrialEligibilityError** = [`GetTrialEligibilityErrors`](GetTrialEligibilityErrors.md)\[keyof [`GetTrialEligibilityErrors`](GetTrialEligibilityErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityErrors.mdnew file mode 100644index 0000000000..cec651f9d0--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityErrors.md@@ -0,0 +1,11 @@+# Type Alias: GetTrialEligibilityErrors++> **GetTrialEligibilityErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponse.mdnew file mode 100644index 0000000000..3fd6da32f6--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponse.md@@ -0,0 +1,3 @@+# Type Alias: GetTrialEligibilityResponse++> **GetTrialEligibilityResponse** = [`GetTrialEligibilityResponses`](GetTrialEligibilityResponses.md)\[keyof [`GetTrialEligibilityResponses`](GetTrialEligibilityResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponses.mdnew file mode 100644index 0000000000..ffa3480859--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GetTrialEligibilityResponses.md@@ -0,0 +1,9 @@+# Type Alias: GetTrialEligibilityResponses++> **GetTrialEligibilityResponses** = \{ `200`: [`TrialEligibility`](TrialEligibility.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`TrialEligibility`](TrialEligibility.md) |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TrialEligibility.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TrialEligibility.mdnew file mode 100644index 0000000000..5c2ce7d279--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/TrialEligibility.md@@ -0,0 +1,12 @@+# Type Alias: TrialEligibility++> **TrialEligibility** = \{ `eligible`: `boolean`; `existingSubscription`: `boolean`; \}++Whether the authenticated customer can receive the introductory Pro trial.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-eligible"></a> `eligible` | `boolean` | Confirmed against the same subscription history used during checkout. |+| <a id="property-existingsubscription"></a> `existingSubscription` | `boolean` | An existing subscription requires management instead of a new checkout. |diff --git a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/DeviceRequest.md b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/DeviceRequest.mdindex 886322ff58..963d1cbe72 100644--- a/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/DeviceRequest.md+++ b/packages/sdk-docs/reference/generated/notification/types.gen/type-aliases/DeviceRequest.md@@ -1,6 +1,6 @@# Type Alias: DeviceRequest-> **DeviceRequest** = \{ `deviceType`: [`DeviceType`](DeviceType.md); `token`: `string`; \}+> **DeviceRequest** = \{ `deviceType`: [`DeviceType`](DeviceType.md); `nativeCallCapable?`: `boolean`; `token`: `string`; \}Request to register or unregister a device for push notifications.@@ -9,4 +9,5 @@ Request to register or unregister a device for push notifications.| Property | Type | Description || ------ | ------ | ------ || <a id="property-devicetype"></a> `deviceType` | [`DeviceType`](DeviceType.md) | The device platform type (iOS or Android). |+| <a id="property-nativecallcapable"></a> `nativeCallCapable?` | `boolean` | Whether this Android binary supports native Telecom incoming calls. || <a id="property-token"></a> `token` | `string` | The device push notification token. |