Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(databases): draw collaborator selections without shifting the grid (#9388)

Wolf Mermelstein5c27e9e0ed96
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index d231838310..ad19985040 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -17,6 +17,7 @@ jobs:
should_run: ${{ steps.filter.outputs.should_run }}
codegen_changed: ${{ steps.filter.outputs.codegen_changed }}
i18n_changed: ${{ steps.filter.outputs.i18n_changed }}
+ database_grid_changed: ${{ steps.filter.outputs.database_grid_changed }}
steps:
- name: Checkout Repo
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
@@ -69,6 +70,8 @@ jobs:
- 'apps/web/src/lib/core/constant/settingsTabsConfig.tsx'
- 'apps/web/src/components/ui/components/Dropdown.tsx'
- 'apps/web/src/features/settings/**'
+ database_grid_changed:
+ - 'apps/web/src/features/database/**'
android-native-check:
name: Android Native Check
runs-on: namespace-profile-linux-tiny-no-cache
@@ -422,6 +425,12 @@ jobs:
bunx playwright install-deps chromium
just test-i18n-browser
working-directory: apps/web
+ - name: Database Grid Browser Tests
+ if: needs.path-check.outputs.database_grid_changed == 'true'
+ run: |-
+ bunx playwright install-deps chromium
+ just test-database-browser
+ working-directory: apps/web
- name: Teardown Nix
if: always()
uses: './.github/actions/teardown-nix'
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 5f5e9fa1a4..f5471f919e 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -221,6 +221,14 @@ new MutationObserver(() => {
Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '1,2,3'` (the same ids coming back) is a `<Suspense>` detach and re-attach. Fresh ids are a true remount. Nothing at all means the subtree never moved and the cause is elsewhere. Re-running the same interaction a second time is the cheapest way to prove a cold-cache cause: a once-per-session query settles after the first attempt, so the second attempt stays clean.
+Remote database selections have a backend-free desktop/phone regression that
+measures every row and cell while collaborators move, share a cell, or select a
+range, and checks their name labels above the header and under it once
+scrolled: `just test-database-browser`. Keep the outline an overlay, never a
+border on the cell. Virtual rows are transformed, so each is its own stacking
+context: a row carrying labels rises above the header only while its top edge
+is in view.
+
Column renames have a backend-free desktop/phone regression using the real
schema query and mutation adapter with delayed service responses:
`bunx playwright test --config src/features/block-database/browser-test/playwright.config.ts rename.browser.e2e.ts`.
diff --git a/apps/web/justfile b/apps/web/justfile
index 669ba24db9..7b0bdf17c0 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -220,6 +220,11 @@ test-signup-browser *ARGS:
test-i18n-browser *ARGS:
env -u LD_LIBRARY_PATH bunx playwright test --config src/lib/i18n/browser-test/playwright.config.ts {{ARGS}}
+# Database grid layout under remote presence, in Chromium. Same
+# LD_LIBRARY_PATH caveat as the sign-up browser tests above.
+test-database-browser *ARGS:
+ env -u LD_LIBRARY_PATH bunx playwright test --config src/features/database/browser-test/playwright.config.ts {{ARGS}}
+
# Optimistic mutations through the real worker/WASM cache in Chromium. Same
# LD_LIBRARY_PATH caveat as the sign-up browser tests above.
test-functional *ARGS:
diff --git a/apps/web/src/features/database/browser-test/grid.html b/apps/web/src/features/database/browser-test/grid.html
new file mode 100644
index 0000000000..aa3e6a567e
--- /dev/null
+++ b/apps/web/src/features/database/browser-test/grid.html
@@ -0,0 +1 @@
+<!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><title>Database grid presence</title></head><body><div id="root"></div><script type="module" src="./grid.tsx"></script></body></html>
diff --git a/apps/web/src/features/database/browser-test/grid.tsx b/apps/web/src/features/database/browser-test/grid.tsx
new file mode 100644
index 0000000000..3703be99db
--- /dev/null
+++ b/apps/web/src/features/database/browser-test/grid.tsx
@@ -0,0 +1,85 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { createSignal } from 'solid-js';
+import { render } from 'solid-js/web';
+import { macroDarkTheme } from '../../theme/themes/macro-dark';
+import { macroLightTheme } from '../../theme/themes/macro-light';
+import { themeCssVars } from '../../theme/utils/themeCssVars';
+import type { DatabaseCellPresence } from '../components/database-table';
+import { GridCell } from '../components/grid-cell';
+import type { DatabaseViewColumn } from '../core/database-view';
+import type { DatabaseRow } from '../core/table';
+import { DatabaseTableView } from '../views/database-table-view';
+
+/**
+ * The production grid with the app's styles, so remote presence can be
+ * measured and screenshotted without a signed-in app. Tests drive the
+ * collaborators through `window.setRemoteUsers`.
+ */
+const title: DatabaseViewColumn = {
+ id: 'title',
+ name: 'Title',
+ dataType: 'STRING',
+ options: [],
+ isMultiSelect: false,
+ writable: true,
+};
+const COLUMNS: DatabaseViewColumn[] = [
+ title,
+ { ...title, id: 'owner', name: 'Owner' },
+ { ...title, id: 'notes', name: 'Notes' },
+];
+const ROWS: DatabaseRow[] = Array.from({ length: 30 }, (_, index) => ({
+ rowId: `row-${index}`,
+ cells: {
+ title: `Task ${index + 1}`,
+ owner: index % 2 ? 'Sam' : 'Alex',
+ // One row wraps onto several lines.
+ notes:
+ index === 3
+ ? 'A long note that wraps onto several lines in a narrow column, so its row is taller than the others.'
+ : `Note ${index + 1}`,
+ },
+}));
+
+const [remoteUsers, setRemoteUsers] = createSignal<DatabaseCellPresence[]>([]);
+Reflect.set(window, 'setRemoteUsers', setRemoteUsers);
+
+function Fixture() {
+ return (
+ <div class="flex h-dvh flex-col bg-panel text-ink">
+ <DatabaseTableView
+ name="Tasks"
+ rows={ROWS}
+ columns={COLUMNS}
+ titleColumnId="title"
+ sort={[]}
+ widths={{ title: 180, owner: 140, notes: 220 }}
+ canEdit
+ pending={false}
+ getRowTitle={(row) => String(row.cells.title)}
+ onOpen={() => {}}
+ onSort={() => {}}
+ remoteUsers={remoteUsers()}
+ renderCell={(row, column, options) => (
+ <GridCell
+ column={column()}
+ value={row().cells[column().id] ?? null}
+ canEdit
+ onWrite={async () => true}
+ onAddOption={async () => true}
+ {...options}
+ />
+ )}
+ />
+ </div>
+ );
+}
+
+const dark = new URLSearchParams(location.search).get('theme') === 'dark';
+for (const [key, token] of Object.entries(
+ themeCssVars(dark ? macroDarkTheme : macroLightTheme)
+))
+ document.documentElement.style.setProperty(key, token);
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/database/browser-test/playwright.config.ts b/apps/web/src/features/database/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..3d4971fde3
--- /dev/null
+++ b/apps/web/src/features/database/browser-test/playwright.config.ts
@@ -0,0 +1,27 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from '@playwright/test';
+
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = process.env.DATABASE_GRID_TEST_PORT ?? '3049';
+export default defineConfig({
+ testDir: fileURLToPath(new URL('.', import.meta.url)),
+ testMatch: '*.browser.e2e.ts',
+ workers: 1,
+ timeout: 180_000,
+ forbidOnly: !!process.env.CI,
+ reporter: process.env.CI ? [['list'], ['github']] : 'line',
+ use: {
+ baseURL: `http://localhost:${port}`,
+ headless: true,
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ webServer: {
+ command: `MACRO_DEV_HTTPS=false bunx vite --config src/features/database/browser-test/vite.config.ts --port ${port} --strictPort`,
+ cwd: webDirectory,
+ url: `http://localhost:${port}/app/`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ },
+});
diff --git a/apps/web/src/features/database/browser-test/presence.browser.e2e.ts b/apps/web/src/features/database/browser-test/presence.browser.e2e.ts
new file mode 100644
index 0000000000..6df0eb8f11
--- /dev/null
+++ b/apps/web/src/features/database/browser-test/presence.browser.e2e.ts
@@ -0,0 +1,184 @@
+import { expect, type Page, test } from '@playwright/test';
+
+type Presence = {
+ userId: string;
+ rowId?: string;
+ columnId?: string;
+ endRowId?: string;
+ endColumnId?: string;
+ editing: boolean;
+};
+
+const ALEX = 'macro|[email protected]';
+const SAM = 'macro|[email protected]';
+
+async function open(page: Page) {
+ await page.goto('/src/features/database/browser-test/grid.html');
+ await expect(page.getByRole('grid', { name: 'Tasks' })).toBeVisible();
+ await page.evaluate(() => document.fonts.ready);
+}
+
+async function present(page: Page, users: Presence[]) {
+ await page.evaluate((next) => {
+ Reflect.get(window, 'setRemoteUsers')(next);
+ }, users);
+ // Let the style and any observers settle before measuring.
+ await page.evaluate(
+ () =>
+ new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve))
+ )
+ );
+}
+
+/** Every row's and cell's box, rounded to hundredths of a pixel. */
+function layout(page: Page) {
+ return page.evaluate(() =>
+ [
+ ...document.querySelectorAll<HTMLElement>(
+ '[role="row"], [data-grid-cell]'
+ ),
+ ].map((element) => {
+ const { x, y, width, height } = element.getBoundingClientRect();
+ return [x, y, width, height].map(
+ (value) => Math.round(value * 100) / 100
+ );
+ })
+ );
+}
+
+function cell(page: Page, rowId: string, column: number) {
+ return page.locator(
+ `[data-grid-row-id="${rowId}"] [data-grid-cell][data-grid-column="${column}"]`
+ );
+}
+
+/** Whether the label's center is painted by the label, not by what covers it. */
+function labelOnTop(page: Page, name: string) {
+ return page.getByRole('note', { name }).evaluate((label) => {
+ // Hit testing skips elements that ignore the pointer, as labels do.
+ label.style.pointerEvents = 'auto';
+ const { x, y, width, height } = label.getBoundingClientRect();
+ const hit = document.elementFromPoint(x + width / 2, y + height / 2);
+ label.style.pointerEvents = '';
+ return !!hit && label.contains(hit);
+ });
+}
+
+const MOVES: Presence[][] = [
+ [{ userId: ALEX, rowId: 'row-0', columnId: 'title', editing: false }],
+ [{ userId: ALEX, rowId: 'row-1', columnId: 'owner', editing: false }],
+ // The wrapped row, while editing.
+ [{ userId: ALEX, rowId: 'row-3', columnId: 'notes', editing: true }],
+ [
+ { userId: ALEX, rowId: 'row-2', columnId: 'owner', editing: false },
+ { userId: SAM, rowId: 'row-2', columnId: 'owner', editing: true },
+ ],
+ [
+ {
+ userId: SAM,
+ rowId: 'row-4',
+ columnId: 'title',
+ endRowId: 'row-6',
+ endColumnId: 'notes',
+ editing: false,
+ },
+ ],
+ [],
+];
+
+for (const viewport of [
+ { name: 'desktop', width: 1280, height: 800 },
+ { name: 'phone', width: 390, height: 844 },
+]) {
+ test(`remote presence never moves a row or cell on ${viewport.name}`, async ({
+ page,
+ }) => {
+ await page.setViewportSize(viewport);
+ await open(page);
+ const before = await layout(page);
+ for (const users of MOVES) {
+ await present(page, users);
+ expect(await layout(page), JSON.stringify(users)).toEqual(before);
+ }
+
+ // The last row, scrolled to the bottom.
+ await page
+ .locator('[data-grid]')
+ .evaluate((grid) =>
+ grid.parentElement!.scrollTo({ top: grid.scrollHeight })
+ );
+ await present(page, []);
+ const bottom = await layout(page);
+ await present(page, [
+ { userId: ALEX, rowId: 'row-29', columnId: 'notes', editing: false },
+ ]);
+ expect(await layout(page)).toEqual(bottom);
+ });
+}
+
+test('the name sits above the top-right of the cell, readable on the first row', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await open(page);
+ await present(page, [
+ { userId: ALEX, rowId: 'row-0', columnId: 'owner', editing: false },
+ { userId: SAM, rowId: 'row-0', columnId: 'owner', editing: true },
+ ]);
+ const target = (await cell(page, 'row-0', 2).boundingBox())!;
+ const alex = (await page
+ .getByRole('note', { name: 'Alex is here' })
+ .boundingBox())!;
+ const sam = (await page
+ .getByRole('note', { name: 'Sam is editing' })
+ .boundingBox())!;
+ for (const label of [alex, sam]) {
+ expect(label.y + label.height).toBeCloseTo(target.y, 0);
+ expect(label.x).toBeGreaterThanOrEqual(target.x - 1);
+ }
+ // The first collaborator takes the corner, inside the cell's 1px divider;
+ // the next sits to its left.
+ expect(
+ Math.abs(alex.x + alex.width - (target.x + target.width))
+ ).toBeLessThanOrEqual(1);
+ expect(sam.x + sam.width).toBeLessThanOrEqual(alex.x);
+ // Above the sticky header, not clipped by it or the scroll container.
+ expect(await labelOnTop(page, 'Alex is here')).toBe(true);
+ expect(await labelOnTop(page, 'Sam is editing')).toBe(true);
+});
+
+test('a label hides under the header once its cell scrolls beneath it', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await open(page);
+ await present(page, [
+ { userId: ALEX, rowId: 'row-10', columnId: 'title', editing: false },
+ ]);
+ const scrollTo = (rowId: string, offset: number) =>
+ page.locator('[data-grid]').evaluate(
+ (grid, [id, by]) => {
+ const scroller = grid.parentElement!;
+ const header = grid.querySelector<HTMLElement>('[aria-rowindex="1"]')!;
+ const row = grid.querySelector<HTMLElement>(
+ `[data-grid-row-id="${id}"]`
+ )!;
+ // Virtual rows are placed by transform, so offsetTop is always 0.
+ const rowTop =
+ row.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top +
+ scroller.scrollTop;
+ scroller.scrollTop = rowTop - header.offsetHeight + by;
+ },
+ [rowId, offset] as const
+ );
+ // The row is the first one under the header: its label covers the header.
+ await scrollTo('row-10', 0);
+ await expect.poll(() => labelOnTop(page, 'Alex is here')).toBe(true);
+ // The cell has gone beneath the header: so has its label.
+ await scrollTo('row-10', 20);
+ await expect.poll(() => labelOnTop(page, 'Alex is here')).toBe(false);
+ await scrollTo('row-10', -200);
+ await expect.poll(() => labelOnTop(page, 'Alex is here')).toBe(true);
+});
diff --git a/apps/web/src/features/database/browser-test/vite.config.ts b/apps/web/src/features/database/browser-test/vite.config.ts
new file mode 100644
index 0000000000..bbf1d0d131
--- /dev/null
+++ b/apps/web/src/features/database/browser-test/vite.config.ts
@@ -0,0 +1,17 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, mergeConfig } from 'vite';
+import { createAppViteConfig } from '../../../../vite.base.ts';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const appConfig = createAppViteConfig();
+
+// The app's config, with the dependency scan starting from this fixture so a
+// cold dev server bundles every dependency before the first load.
+export default defineConfig(async (env) =>
+ mergeConfig(await appConfig(env), {
+ cacheDir: `${directory}.vite`,
+ optimizeDeps: {
+ entries: ['src/features/database/browser-test/grid.html'],
+ },
+ })
+);
diff --git a/apps/web/src/features/database/components/database-table.test.tsx b/apps/web/src/features/database/components/database-table.test.tsx
index a0c9658ede..25e5787fb2 100644
--- a/apps/web/src/features/database/components/database-table.test.tsx
+++ b/apps/web/src/features/database/components/database-table.test.tsx
@@ -883,6 +883,24 @@ describe('spreadsheet interactions', () => {
});
describe('presence and reveal', () => {
+ // JSDOM has no layout: every label's cell edge reads as in view.
+ beforeEach(() => {
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(
+ private readonly callback: (
+ entries: { isIntersecting: boolean }[]
+ ) => void
+ ) {}
+ observe() {
+ this.callback([{ isIntersecting: true }]);
+ }
+ disconnect() {}
+ }
+ );
+ });
+ afterEach(() => vi.unstubAllGlobals());
it('marks the cell a remote viewer is on and shares the focused cell', () => {
const onCellFocus = vi.fn();
const [remoteUsers, setRemoteUsers] = createSignal([
@@ -899,6 +917,13 @@ describe('presence and reveal', () => {
editing: true,
},
{ userId: 'macro|[email protected]', editing: false },
+ {
+ userId: 'macro|[email protected]',
+ rowId: 'two',
+ columnId: 'name',
+ editing: false,
+ canEdit: false,
+ },
]);
const [highlightRowId, setHighlightRowId] = createSignal<string>();
render(() => (
@@ -937,18 +962,29 @@ describe('presence and reveal', () => {
expect(alexCell.dataset.gridRow).toBe('1');
expect(alexCell.dataset.gridColumn).toBe('2');
expect(alexCell.dataset.remoteUsers).toBe('macro|[email protected]');
- expect(alexCell.style.borderTop).toContain('2px solid');
- expect(alexCell.style.backgroundColor).toContain('color-mix');
+ // The outline is an overlay, so the cell itself gains no border.
+ expect(alexCell.style.borderTop).toBe('');
+ const alexOutline = alexCell.querySelector<HTMLElement>(
+ '[data-remote-outline]'
+ )!;
+ expect(alexOutline.style.borderTop).toContain('2px solid');
+ expect(alexOutline.style.backgroundColor).toContain('color-mix');
// Sam has no cached profile: the email name is shown, dashed while editing.
const samTag = screen.getByRole('note', { name: 'Sam is editing' });
- const samCell = samTag.closest<HTMLElement>('[data-grid-cell]')!;
- expect(samCell.style.borderTop).toContain('dashed');
- expect(samCell.style.borderTop).not.toBe(alexCell.style.borderTop);
+ const samOutline = samTag
+ .closest<HTMLElement>('[data-grid-cell]')!
+ .querySelector<HTMLElement>('[data-remote-outline]')!;
+ expect(samOutline.style.borderTop).toContain('dashed');
+ expect(samOutline.style.borderTop).not.toBe(alexOutline.style.borderTop);
+ // Lee can only view: marked as viewing.
+ expect(
+ screen.getByRole('note', { name: 'Lee is viewing' }).textContent
+ ).toBe('Lee');
// Pat is on the table with no cell: nothing to draw.
- expect(document.querySelectorAll('[data-remote-users]')).toHaveLength(2);
+ expect(document.querySelectorAll('[data-remote-users]')).toHaveLength(3);
setRemoteUsers([]);
expect(screen.queryByRole('note')).toBeNull();
- expect(alexCell.style.borderTop).toBe('');
+ expect(document.querySelector('[data-remote-outline]')).toBeNull();
const secondNotes = screen
.getAllByRole('row')[2]
diff --git a/apps/web/src/features/database/components/database-table.tsx b/apps/web/src/features/database/components/database-table.tsx
index a2501a005b..c37eaf1ac0 100644
--- a/apps/web/src/features/database/components/database-table.tsx
+++ b/apps/web/src/features/database/components/database-table.tsx
@@ -2,6 +2,7 @@ import { debounce } from '@core/util/debounce';
import { fireAndForget } from '@core/util/fireAndForget';
import ArrowSquareOutIcon from '@icon/system/regular/arrow-square-out.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
+import EyeIcon from '@icon/system/regular/eye.svg';
import PencilIcon from '@icon/system/regular/pencil-simple.svg';
import TrashIcon from '@icon/system/regular/trash.svg';
import { ContextMenu } from '@kobalte/core/context-menu';
@@ -25,6 +26,7 @@ import {
type JSX,
on,
onCleanup,
+ onMount,
Show,
untrack,
} from 'solid-js';
@@ -82,6 +84,8 @@ export type DatabaseCellPresence = {
endRowId?: string;
endColumnId?: string;
editing: boolean;
+ /** False for a viewer whose access is view-only; absent from older servers. */
+ canEdit?: boolean;
};
/** Lets the host open a cell's editor or a header's rename; a target not yet mounted opens once it registers. */
@@ -1015,6 +1019,11 @@ export function DatabaseTable(props: DatabaseTableProps) {
);
const highlighted = () =>
props.highlightRowId === row().rowId;
+ const hostsLabels = () =>
+ remoteRanges().some(
+ ({ bounds }) => bounds.top === index()
+ );
+ const [topInView, setTopInView] = createSignal(true);
const [live, setLive] = createSignal(
!props.renderCellPreview || mountsLive(rowId, index())
);
@@ -1052,7 +1061,12 @@ export function DatabaseTable(props: DatabaseTableProps) {
data-highlighted={highlighted() ? '' : undefined}
aria-rowindex={index() + 2}
class="group absolute inset-x-0 top-0 grid min-h-10 border-b border-edge-muted/60 hover:bg-hover/50"
- classList={{ 'bg-accent/15': highlighted() }}
+ classList={{
+ 'bg-accent/15': highlighted(),
+ // Its presence labels paint over the sticky header
+ // while the row's top edge is in view.
+ 'z-2': hostsLabels() && topInView(),
+ }}
style={{
...position(),
// A preview keeps the live row's height, so rows
@@ -1068,6 +1082,13 @@ export function DatabaseTable(props: DatabaseTableProps) {
}}
onClick={() => previewRows.get(rowId)?.upgrade()}
>
+ <Show when={hostsLabels()}>
+ <TopEdgeInView
+ root={scrollContainer}
+ header={header()}
+ onChange={setTopInView}
+ />
+ </Show>
<div
role="gridcell"
aria-colindex={1}
@@ -1114,6 +1135,15 @@ export function DatabaseTable(props: DatabaseTableProps) {
const columnId = column().id;
const presence = () =>
presenceAt(row().rowId, column().id);
+ // Named at the selection's top-right cell.
+ const labelled = () =>
+ presence()
+ .filter(
+ ({ bounds }) =>
+ bounds.top === index() &&
+ bounds.right === columnIndex()
+ )
+ .map(({ user }) => user);
return (
<div
role="gridcell"
@@ -1141,25 +1171,6 @@ export function DatabaseTable(props: DatabaseTableProps) {
.join(' ')
: undefined
}
- style={presenceOutline(
- presence()[0]?.user,
- presence()[0]
- ? {
- top:
- index() ===
- presence()[0].bounds.top,
- bottom:
- index() ===
- presence()[0].bounds.bottom,
- left:
- columnIndex() ===
- presence()[0].bounds.left,
- right:
- columnIndex() ===
- presence()[0].bounds.right,
- }
- : undefined
- )}
>
<Show
when={live()}
@@ -1185,18 +1196,30 @@ export function DatabaseTable(props: DatabaseTableProps) {
),
})}
</Show>
- <Show when={presence().length}>
- <span class="pointer-events-none absolute top-0 left-0 z-1 flex gap-px">
- <For
- each={presence().filter(
- ({ bounds }) =>
- bounds.top === index() &&
- bounds.left === columnIndex()
- )}
- >
- {({ user }) => (
- <PresenceTag user={user} below />
- )}
+ <Show when={presence()[0]}>
+ {(first) => (
+ <span
+ aria-hidden="true"
+ data-remote-outline
+ class="pointer-events-none absolute inset-0"
+ style={presenceOutline(first().user, {
+ top: index() === first().bounds.top,
+ bottom:
+ index() === first().bounds.bottom,
+ left:
+ columnIndex() ===
+ first().bounds.left,
+ right:
+ columnIndex() ===
+ first().bounds.right,
+ })}
+ />
+ )}
+ </Show>
+ <Show when={labelled().length}>
+ <span class="pointer-events-none absolute right-0 bottom-full flex flex-row-reverse gap-px">
+ <For each={labelled()}>
+ {(user) => <PresenceTag user={user} />}
</For>
</span>
</Show>
@@ -1379,11 +1402,11 @@ type PresenceEdges = {
left: boolean;
};
+/** The overlay's borders: absolutely positioned, so they never size the cell. */
function presenceOutline(
- user: DatabaseCellPresence | undefined,
- edges: PresenceEdges = { top: true, right: true, bottom: true, left: true }
-): JSX.CSSProperties | undefined {
- if (!user) return undefined;
+ user: DatabaseCellPresence,
+ edges: PresenceEdges
+): JSX.CSSProperties {
const color = presenceColor(user.peerId ?? user.userId);
const border = `2px ${user.editing ? 'dashed' : 'solid'} ${color}`;
return {
@@ -1407,23 +1430,59 @@ function presenceName(userId: string) {
: getInitials(firstName, lastName, email);
}
-function PresenceTag(props: { user: DatabaseCellPresence; below?: boolean }) {
+/**
+ * Reports whether the top edge of its positioned parent is visible between the
+ * scroll container's sticky header and summary.
+ */
+function TopEdgeInView(props: {
+ root: HTMLElement;
+ header: HTMLElement | undefined;
+ onChange: (inView: boolean) => void;
+}) {
+ let edge!: HTMLSpanElement;
+ onMount(() => {
+ const footer = props.root.querySelector<HTMLElement>('[data-grid-summary]');
+ const observer = new IntersectionObserver(
+ ([entry]) => props.onChange(entry.isIntersecting),
+ {
+ root: props.root,
+ rootMargin: `-${props.header?.offsetHeight ?? 0}px 0px -${footer?.offsetHeight ?? 0}px 0px`,
+ }
+ );
+ observer.observe(edge);
+ onCleanup(() => observer.disconnect());
+ });
+ return (
+ <span
+ ref={edge}
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-x-0 top-0 h-px"
+ />
+ );
+}
+
+function PresenceTag(props: { user: DatabaseCellPresence }) {
+ const viewing = () => props.user.canEdit === false;
const label = () =>
- `${presenceName(props.user.userId)} is ${props.user.editing ? 'editing' : 'here'}`;
+ `${presenceName(props.user.userId)} is ${
+ props.user.editing ? 'editing' : viewing() ? 'viewing' : 'here'
+ }`;
return (
<span
role="note"
aria-label={label()}
title={label()}
- class="max-w-40 truncate px-1.5 py-0.5 text-[11px] font-medium leading-4 text-surface shadow-sm"
- classList={{ 'rounded-t-sm': !props.below, 'rounded-b-sm': props.below }}
+ class="flex max-w-40 items-center gap-0.5 rounded-t-sm px-1.5 py-0.5 text-[11px] font-medium leading-4 text-surface shadow-sm"
style={{
'background-color': presenceColor(
props.user.peerId ?? props.user.userId
),
}}
>
- {presenceName(props.user.userId)}
+ <Show when={viewing()}>
+ <EyeIcon aria-hidden="true" class="size-3 shrink-0" />
+ </Show>
+ <span class="truncate">{presenceName(props.user.userId)}</span>
</span>
);
}
diff --git a/apps/web/src/lib/queries/storage/databases-sync.test.ts b/apps/web/src/lib/queries/storage/databases-sync.test.ts
index ec222edaae..51e9751196 100644
--- a/apps/web/src/lib/queries/storage/databases-sync.test.ts
+++ b/apps/web/src/lib/queries/storage/databases-sync.test.ts
@@ -158,9 +158,11 @@ it('merges legacy states per user, drops stale relays, itself, other databases,
102,
'other-db'
);
+ // A server that predates view-only presence stamps no access: an editor.
expect(remote()).toEqual([
{
userId: 'alex',
+ canEdit: true,
tableId: 'tasks',
rowId: 'row-1',
columnId: 'name',
@@ -325,6 +327,37 @@ it('keeps same-user tabs separate, suppresses only this peer, and leaves one pee
dispose();
});
+it('marks a view-only viewer from the access the server stamped', () => {
+ const { remote, dispose } = createRoot((dispose) => ({
+ remote: useDatabaseAwareness(
+ () => 'db',
+ () => ({ tableId: 'tasks' })
+ ).remote,
+ dispose,
+ }));
+ mock.event?.({
+ type: 'database_awareness',
+ data: JSON.stringify({
+ databaseId: 'db',
+ userId: 'pat',
+ canEdit: false,
+ state: { tableId: 'tasks', rowId: 'row-1', columnId: 'name' },
+ relayedAt: 100,
+ }),
+ });
+ expect(remote()).toEqual([
+ {
+ userId: 'pat',
+ canEdit: false,
+ tableId: 'tasks',
+ rowId: 'row-1',
+ columnId: 'name',
+ editing: false,
+ },
+ ]);
+ dispose();
+});
+
it('forgets peers when switching databases', () => {
const [database, setDatabase] = createSignal('db');
const { remote, dispose } = createRoot((dispose) => ({
diff --git a/apps/web/src/lib/queries/storage/databases-sync.ts b/apps/web/src/lib/queries/storage/databases-sync.ts
index 8c429c5fa9..d4ca625503 100644
--- a/apps/web/src/lib/queries/storage/databases-sync.ts
+++ b/apps/web/src/lib/queries/storage/databases-sync.ts
@@ -47,6 +47,8 @@ const databaseChangedSchema = z.object({ databaseId: z.string() });
const awarenessRelaySchema: z.ZodType<AwarenessRelay> = z.object({
databaseId: z.string(),
userId: z.string(),
+ // Servers that predate it omit it; their viewers read as editors.
+ canEdit: z.boolean().default(true),
state: awarenessSchema,
relayedAt: z.number(),
});
@@ -116,10 +118,12 @@ export type LocalDatabaseAwareness = Omit<Awareness, 'left' | 'peerId'>;
type RemoteDatabaseAwareness = Omit<Awareness, 'left' | 'editing'> & {
userId: string;
editing: boolean;
+ canEdit: boolean;
};
type HeldAwareness = {
userId: string;
+ canEdit: boolean;
state: Awareness;
/** Server relay time, orders messages from the same peer. */
relayedAt: number;
@@ -214,6 +218,7 @@ export function useDatabaseAwareness(
if (current && current.relayedAt > relay.relayedAt) return;
held.set(key, {
userId: relay.userId,
+ canEdit: relay.canEdit,
state: relay.state,
relayedAt: relay.relayedAt,
receivedAt: Date.now(),
@@ -236,8 +241,9 @@ export function useDatabaseAwareness(
const remote = () =>
[...held.values()]
.filter(({ state }) => !state.left)
- .map(({ userId, state }) => ({
+ .map(({ userId, canEdit, state }) => ({
userId,
+ canEdit,
peerId: state.peerId,
tableId: state.tableId,
rowId: state.rowId,
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/awarenessRelay.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/awarenessRelay.ts
index c12437edfc..1c0a95e03f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/awarenessRelay.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/awarenessRelay.ts
@@ -11,6 +11,9 @@ import type { Awareness } from './awareness';
when the server relayed it so receivers can drop older relays.
*/
export interface AwarenessRelay {
+ /** Whether the viewer's grant lets them edit; a viewer who cannot is
+shown as viewing. */
+ canEdit: boolean;
/** The database the viewer is in. */
databaseId: string;
/** When the server relayed it, in milliseconds since the Unix epoch. */
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 528039a7ae..68e746afb8 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -21554,8 +21554,12 @@
"AwarenessRelay": {
"type": "object",
"description": "The [`AWARENESS_MESSAGE_TYPE`] payload: one viewer's awareness, stamped\nwhen the server relayed it so receivers can drop older relays.",
- "required": ["databaseId", "userId", "state", "relayedAt"],
+ "required": ["databaseId", "userId", "canEdit", "state", "relayedAt"],
"properties": {
+ "canEdit": {
+ "type": "boolean",
+ "description": "Whether the viewer's grant lets them edit; a viewer who cannot is\nshown as viewing."
+ },
"databaseId": {
"type": "string",
"format": "uuid",
diff --git a/crates/database_webhooks/src/wiring/test.rs b/crates/database_webhooks/src/wiring/test.rs
index 541046cf7b..a47aa4df8c 100644
--- a/crates/database_webhooks/src/wiring/test.rs
+++ b/crates/database_webhooks/src/wiring/test.rs
@@ -39,6 +39,7 @@ impl databases::domain::ports::TableEventPublisher for Unheard {
&self,
_: DatabaseId,
_: &MacroUserIdStr<'_>,
+ _: bool,
_: &databases::domain::models::Awareness,
) -> Result<(), Self::Error> {
Ok(())
diff --git a/crates/databases/src/domain/ports.rs b/crates/databases/src/domain/ports.rs
index 020e3b0ac0..2c81fff0a4 100644
--- a/crates/databases/src/domain/ports.rs
+++ b/crates/databases/src/domain/ports.rs
@@ -335,11 +335,13 @@ pub trait TableEventPublisher: Send + Sync + 'static {
version: TableVersion,
) -> impl Future<Output = Result<(), Self::Error>> + Send;
- /// Relay where a viewer is to the database's other viewers.
+ /// Relay where a viewer is to the database's other viewers, and whether
+ /// their grant lets them edit.
fn awareness(
&self,
database_id: DatabaseId,
user_id: &MacroUserIdStr<'_>,
+ can_edit: bool,
state: &Awareness,
) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
@@ -485,8 +487,9 @@ pub trait DatabasesService: Send + Sync + 'static {
since: TableVersion,
) -> impl Future<Output = Result<TableChanges, DatabaseError>> + Send;
- /// Tell the database's other viewers where this viewer is; a relay
- /// failure is the caller's error.
+ /// Tell the database's other viewers where this viewer is and whether
+ /// they can edit; a viewer who cannot is never relayed as editing. A
+ /// relay failure is the caller's error.
fn share_awareness(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/crates/databases/src/domain/service.rs b/crates/databases/src/domain/service.rs
index 677f74ef57..1539ed2bc9 100644
--- a/crates/databases/src/domain/service.rs
+++ b/crates/databases/src/domain/service.rs
@@ -42,7 +42,7 @@ use crate::domain::models::{
Database, DatabaseDetail, DatabaseError, DatabaseId, FirstTable, InferColumnType,
InferColumnTypeOutcome, ListedDatabase, OpBatch, OptionId, PropertyDefinitionId,
QueryDefinition, QueryId, RowId, RowRef, SavedQuery, SavedQueryError, SchemaError,
- SharingError, Table, TableDetail, TableId, TableVersion, ViewId, Viewer,
+ SharingError, Table, TableDetail, TableId, TableVersion, ViewId, Viewer, grant_writes,
};
use crate::domain::ports::{
AccessDirectory, CellStore, ColumnDefinitionStore, DatabasesRepo, DatabasesService,
@@ -852,8 +852,13 @@ where
state: Awareness,
) -> Result<(), DatabaseError> {
let database_id = receipt_database_id(&receipt)?;
+ let can_edit = grant_writes(receipt_grant(&receipt, AccessLevel::View));
+ let state = Awareness {
+ editing: state.editing && can_edit,
+ ..state
+ };
self.events
- .awareness(database_id, &viewer.user_id, &state)
+ .awareness(database_id, &viewer.user_id, can_edit, &state)
.await
.map_err(repository_error)
}
diff --git a/crates/databases/src/domain/service/test/awareness.rs b/crates/databases/src/domain/service/test/awareness.rs
index bdd8fe5164..1226f42c24 100644
--- a/crates/databases/src/domain/service/test/awareness.rs
+++ b/crates/databases/src/domain/service/test/awareness.rs
@@ -1,9 +1,10 @@
-//! Awareness relays reach the gateway, and a refused relay is an error.
+//! Awareness relays reach the gateway stamped with whether the viewer can
+//! edit, and a refused relay is an error.
use super::*;
#[tokio::test]
-async fn awareness_is_relayed_for_the_viewer() {
+async fn an_editors_awareness_is_relayed_as_editable() {
let seeded = seeded().await;
let state = Awareness {
peer_id: Some(uuid::Uuid::from_u128(7)),
@@ -15,6 +16,34 @@ async fn awareness_is_relayed_for_the_viewer() {
editing: true,
left: false,
};
+ seeded
+ .service
+ .share_awareness(
+ receipt::<ViewAccessLevel>(seeded.database_id, VIEWER, AccessLevel::Edit),
+ viewer(VIEWER),
+ state.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ seeded.world.lock().unwrap().awareness,
+ vec![(seeded.database_id, VIEWER.to_string(), true, state)]
+ );
+}
+
+#[tokio::test]
+async fn a_view_only_awareness_is_relayed_as_viewing_and_never_editing() {
+ let seeded = seeded().await;
+ let state = Awareness {
+ peer_id: Some(uuid::Uuid::from_u128(7)),
+ table_id: seeded.table_id,
+ row_id: Some(seeded.row_id),
+ column_id: Some(seeded.name_column.id),
+ end_row_id: None,
+ end_column_id: None,
+ editing: true,
+ left: false,
+ };
seeded
.service
.share_awareness(
@@ -26,7 +55,15 @@ async fn awareness_is_relayed_for_the_viewer() {
.unwrap();
assert_eq!(
seeded.world.lock().unwrap().awareness,
- vec![(seeded.database_id, VIEWER.to_string(), state)]
+ vec![(
+ seeded.database_id,
+ VIEWER.to_string(),
+ false,
+ Awareness {
+ editing: false,
+ ..state
+ }
+ )]
);
}
diff --git a/crates/databases/src/domain/service/test/fakes.rs b/crates/databases/src/domain/service/test/fakes.rs
index 753528e569..cca6b7b712 100644
--- a/crates/databases/src/domain/service/test/fakes.rs
+++ b/crates/databases/src/domain/service/test/fakes.rs
@@ -27,7 +27,8 @@ pub(super) struct World {
pub(super) published: Vec<(TableId, TableVersion)>,
pub(super) metadata_changes: Vec<DatabaseId>,
/// Every awareness relay the service asked for.
- pub(super) awareness: Vec<(DatabaseId, String, Awareness)>,
+ /// Each as (database, user, whether they can edit, state).
+ pub(super) awareness: Vec<(DatabaseId, String, bool, Awareness)>,
/// Simulate the gateway refusing an awareness relay.
pub(super) awareness_relay_fails: bool,
pub(super) share_updates: Vec<Vec<models_permissions::share_permission::channel_share_permission::UpdateChannelSharePermission>>,
@@ -668,15 +669,19 @@ impl TableEventPublisher for FakeEvents {
&self,
database_id: DatabaseId,
user_id: &MacroUserIdStr<'_>,
+ can_edit: bool,
state: &Awareness,
) -> Result<(), FakeError> {
let mut world = self.0.lock().unwrap();
if world.awareness_relay_fails {
return Err(FakeError);
}
- world
- .awareness
- .push((database_id, user_id.as_ref().to_string(), state.clone()));
+ world.awareness.push((
+ database_id,
+ user_id.as_ref().to_string(),
+ can_edit,
+ state.clone(),
+ ));
Ok(())
}
}
diff --git a/crates/databases/src/outbound/gateway_event_publisher.rs b/crates/databases/src/outbound/gateway_event_publisher.rs
index 90baef52da..68922b99e4 100644
--- a/crates/databases/src/outbound/gateway_event_publisher.rs
+++ b/crates/databases/src/outbound/gateway_event_publisher.rs
@@ -50,6 +50,9 @@ pub struct AwarenessRelay {
pub database_id: DatabaseId,
/// The viewer.
pub user_id: String,
+ /// Whether the viewer's grant lets them edit; a viewer who cannot is
+ /// shown as viewing.
+ pub can_edit: bool,
/// Where the viewer is.
pub state: Awareness,
/// When the server relayed it, in milliseconds since the Unix epoch.
@@ -127,6 +130,7 @@ impl TableEventPublisher for GatewayTableEventPublisher {
&self,
database_id: DatabaseId,
user_id: &MacroUserIdStr<'_>,
+ can_edit: bool,
state: &Awareness,
) -> Result<(), Self::Error> {
self.client
@@ -136,6 +140,7 @@ impl TableEventPublisher for GatewayTableEventPublisher {
serde_json::to_value(AwarenessRelay {
database_id,
user_id: user_id.as_ref().to_string(),
+ can_edit,
state: state.clone(),
relayed_at: Utc::now(),
})
@@ -172,6 +177,7 @@ impl TableEventPublisher for NoOpTableEventPublisher {
&self,
_database_id: DatabaseId,
_user_id: &MacroUserIdStr<'_>,
+ _can_edit: bool,
_state: &Awareness,
) -> Result<(), Self::Error> {
Ok(())
@@ -230,12 +236,17 @@ impl TableEventPublisher for MaybeGatewayTableEventPublisher {
&self,
database_id: DatabaseId,
user_id: &MacroUserIdStr<'_>,
+ can_edit: bool,
state: &Awareness,
) -> Result<(), Self::Error> {
match self {
- Self::Gateway(publisher) => publisher.awareness(database_id, user_id, state).await,
+ Self::Gateway(publisher) => {
+ publisher
+ .awareness(database_id, user_id, can_edit, state)
+ .await
+ }
Self::NoOp(publisher) => publisher
- .awareness(database_id, user_id, state)
+ .awareness(database_id, user_id, can_edit, state)
.await
.map_err(|never| match never {}),
}
diff --git a/crates/databases/src/outbound/gateway_event_publisher/test.rs b/crates/databases/src/outbound/gateway_event_publisher/test.rs
index c8b7b6e004..fbd4301fd1 100644
--- a/crates/databases/src/outbound/gateway_event_publisher/test.rs
+++ b/crates/databases/src/outbound/gateway_event_publisher/test.rs
@@ -26,6 +26,7 @@ fn an_awareness_relay_serializes_its_relay_time_as_epoch_milliseconds() {
let payload = AwarenessRelay {
database_id: DatabaseId::from_uuid(Uuid::from_u128(1)),
user_id: "macro|[email protected]".to_string(),
+ can_edit: true,
state: Awareness {
peer_id: Some(uuid::Uuid::from_u128(7)),
table_id: TableId::from_uuid(Uuid::from_u128(2)),
@@ -43,6 +44,7 @@ fn an_awareness_relay_serializes_its_relay_time_as_epoch_milliseconds() {
serde_json::json!({
"databaseId": "00000000-0000-0000-0000-000000000001",
"userId": "macro|[email protected]",
+ "canEdit": true,
"state": {
"peerId": "00000000-0000-0000-0000-000000000007",
"tableId": "00000000-0000-0000-0000-000000000002",
diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.md
index 01ab7d986a..064aeddc07 100644
--- a/docs/agent-guide/databases.md
+++ b/docs/agent-guide/databases.md
@@ -782,6 +782,13 @@ Database awareness identifies each mounted client with a random peer ID while th
server supplies its authenticated user. Open the same database in two tabs signed
in as the same user: each should show the other tab's selection and name. Moving
or leaving one peer must not overwrite or remove another peer's selection.
+Another viewer's selection is an outline in their color laid over the cells, and
+their name sits above the selection's top-right corner, over the sticky header
+while that edge is in view. Neither ever changes a row's or cell's size. Anyone
+who can view the database shares and sees presence: a view-only viewer's label
+shows an eye (`Lee is viewing`), and the server never relays them as editing.
+Sign in as an editor and a viewer to check both directions; the viewer still
+cannot change cells.
Refresh failures emit a `database.rows.read_refresh` span with the database ID,
table ID, and failure kind, plus a `database rows could not be refreshed` log.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AwarenessRelay.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AwarenessRelay.md
index ac393a4459..54089b464a 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AwarenessRelay.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AwarenessRelay.md
@@ -1,6 +1,6 @@
# Type Alias: AwarenessRelay
-> **AwarenessRelay** = \{ `databaseId`: `string`; `relayedAt`: `number`; `state`: [`Awareness`](Awareness.md); `userId`: `string`; \}
+> **AwarenessRelay** = \{ `canEdit`: `boolean`; `databaseId`: `string`; `relayedAt`: `number`; `state`: [`Awareness`](Awareness.md); `userId`: `string`; \}
The [`AWARENESS_MESSAGE_TYPE`] payload: one viewer's awareness, stamped
when the server relayed it so receivers can drop older relays.
@@ -9,6 +9,7 @@ when the server relayed it so receivers can drop older relays.
| Property | Type | Description |
| ------ | ------ | ------ |
+| <a id="property-canedit"></a> `canEdit` | `boolean` | Whether the viewer's grant lets them edit; a viewer who cannot is shown as viewing. |
| <a id="property-databaseid"></a> `databaseId` | `string` | The database the viewer is in. |
| <a id="property-relayedat"></a> `relayedAt` | `number` | When the server relayed it, in milliseconds since the Unix epoch. |
| <a id="property-state"></a> `state` | [`Awareness`](Awareness.md) | Where the viewer is. |
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 25146e5147..b1cf29ab41 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1221,6 +1221,11 @@ export type Awareness = {
* when the server relayed it so receivers can drop older relays.
*/
export type AwarenessRelay = {
+ /**
+ * Whether the viewer's grant lets them edit; a viewer who cannot is
+ * shown as viewing.
+ */
+ canEdit: boolean;
/**
* The database the viewer is in.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 528039a7ae..68e746afb8 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -21554,8 +21554,12 @@
"AwarenessRelay": {
"type": "object",
"description": "The [`AWARENESS_MESSAGE_TYPE`] payload: one viewer's awareness, stamped\nwhen the server relayed it so receivers can drop older relays.",
- "required": ["databaseId", "userId", "state", "relayedAt"],
+ "required": ["databaseId", "userId", "canEdit", "state", "relayedAt"],
"properties": {
+ "canEdit": {
+ "type": "boolean",
+ "description": "Whether the viewer's grant lets them edit; a viewer who cannot is\nshown as viewing."
+ },
"databaseId": {
"type": "string",
"format": "uuid",
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index f22c814db6..75cf379091 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -75,6 +75,10 @@ fn path_check() -> Job {
"${{ steps.filter.outputs.codegen_changed }}",
)
.add_output("i18n_changed", "${{ steps.filter.outputs.i18n_changed }}")
+ .add_output(
+ "database_grid_changed",
+ "${{ steps.filter.outputs.database_grid_changed }}",
+ )
.add_step(checkout("Checkout Repo", false))
.add_step(paths_filter())
}
@@ -197,6 +201,7 @@ fn test() -> Job {
.add_step(run_tests())
.add_step(run_signup_browser_tests())
.add_step(run_i18n_browser_tests())
+ .add_step(run_database_browser_tests())
.add_step(steps::teardown_nix())
}
@@ -283,7 +288,8 @@ fn paths_filter() -> Step<Use> {
// stays off for a shell-only tweak. Workflow YAML drift is `check
// generated workflows`. `i18n_changed` covers what the interface language
// browser tests render: translations, the menu primitives, and settings
- // navigation.
+ // navigation. `database_grid_changed` covers the database grid's browser
+ // tests.
Step::new("Filter changed paths")
.uses(
"dorny",
@@ -294,7 +300,7 @@ fn paths_filter() -> Step<Use> {
.add_with((
"filters",
format!(
- "should_run:\n{artifact_paths} - 'services/lexical-service/**'\n - 'packages/sdk/**'\n - 'packages/sdk-docs/**'\n - 'services/ai-editing-worker/**'\n - 'packages/code-mode-sdk/**'\n - 'crates/code_execution/src/outbound/deno/*.mjs'\n - 'crates/agent_code_mode/src/domain/documentation.json'\n - 'crates/agent_code_mode/SKILL.md'\n - 'crates/ai_tools/src/display_results/schema.generated.json'\n - '.github/actions/setup-reqs-web/**'\ncodegen_changed:\n - 'crates/**/*.rs'\n - 'services/**/*.rs'\n - 'Cargo.toml'\n - 'Cargo.lock'\n - 'apps/web/scripts/generate-api-schema.ts'\n - 'apps/web/scripts/services.ts'\n - 'packages/sdk/**'\n - 'apps/docs/**'\n - '.github/actions/setup-reqs-web/**'\ni18n_changed:\n - 'apps/web/src/lib/i18n/**'\n - 'apps/web/src/lib/core/component/ContextMenu.tsx'\n - 'apps/web/src/lib/core/constant/settingsTabsConfig.tsx'\n - 'apps/web/src/components/ui/components/Dropdown.tsx'\n - 'apps/web/src/features/settings/**'\n"
+ "should_run:\n{artifact_paths} - 'services/lexical-service/**'\n - 'packages/sdk/**'\n - 'packages/sdk-docs/**'\n - 'services/ai-editing-worker/**'\n - 'packages/code-mode-sdk/**'\n - 'crates/code_execution/src/outbound/deno/*.mjs'\n - 'crates/agent_code_mode/src/domain/documentation.json'\n - 'crates/agent_code_mode/SKILL.md'\n - 'crates/ai_tools/src/display_results/schema.generated.json'\n - '.github/actions/setup-reqs-web/**'\ncodegen_changed:\n - 'crates/**/*.rs'\n - 'services/**/*.rs'\n - 'Cargo.toml'\n - 'Cargo.lock'\n - 'apps/web/scripts/generate-api-schema.ts'\n - 'apps/web/scripts/services.ts'\n - 'packages/sdk/**'\n - 'apps/docs/**'\n - '.github/actions/setup-reqs-web/**'\ni18n_changed:\n - 'apps/web/src/lib/i18n/**'\n - 'apps/web/src/lib/core/component/ContextMenu.tsx'\n - 'apps/web/src/lib/core/constant/settingsTabsConfig.tsx'\n - 'apps/web/src/components/ui/components/Dropdown.tsx'\n - 'apps/web/src/features/settings/**'\ndatabase_grid_changed:\n - 'apps/web/src/features/database/**'\n"
),
))
}
@@ -478,6 +484,17 @@ fn run_i18n_browser_tests() -> Step<Run> {
.working_directory(xtask_paths::repo_dir!("apps/web"))
}
+/// Rows and cells measured under remote presence in Chromium. Only when the
+/// database grid changes.
+fn run_database_browser_tests() -> Step<Run> {
+ Step::new("Database Grid Browser Tests")
+ .run("bunx playwright install-deps chromium\njust test-database-browser")
+ .if_condition(Expression::new(
+ "needs.path-check.outputs.database_grid_changed == 'true'",
+ ))
+ .working_directory(xtask_paths::repo_dir!("apps/web"))
+}
+
fn cycles_import_check() -> Step<Run> {
Step::new("Cycles Import Check")
.run("biome lint --changed --no-errors-on-unmatched --only=suspicious/noImportCycles")