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(databases): distinguish awareness peers across tabs (#7403)
Wolf Mermelstein463f0e9f5cce
diff --git a/apps/web/src/features/block-database/components/database-table.tsx b/apps/web/src/features/block-database/components/database-table.tsxindex 6359c90361..13d174704c 100644--- a/apps/web/src/features/block-database/components/database-table.tsx+++ b/apps/web/src/features/block-database/components/database-table.tsx@@ -63,6 +63,7 @@ export type DatabaseCellFocus = {/** Another viewer of the same table; no row or column means no cell. */export type DatabaseCellPresence = {+ peerId?: string;userId: string;rowId?: string;columnId?: string;@@ -918,7 +919,7 @@ function presenceOutline(edges: PresenceEdges = { top: true, right: true, bottom: true, left: true }): JSX.CSSProperties | undefined {if (!user) return undefined;- const color = presenceColor(user.userId);+ const color = presenceColor(user.peerId ?? user.userId);const border = `2px ${user.editing ? 'dashed' : 'solid'} ${color}`;return {'background-color': `color-mix(in srgb, ${color} 8%, transparent)`,@@ -951,7 +952,11 @@ function PresenceTag(props: { user: DatabaseCellPresence; below?: boolean }) {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 }}- style={{ 'background-color': presenceColor(props.user.userId) }}+ style={{+ 'background-color': presenceColor(+ props.user.peerId ?? props.user.userId+ ),+ }}>{presenceName(props.user.userId)}</span>diff --git a/apps/web/src/features/block-database/queries/table-rows.ts b/apps/web/src/features/block-database/queries/table-rows.tsindex 20a75574e3..15ff2f71f4 100644--- a/apps/web/src/features/block-database/queries/table-rows.ts+++ b/apps/web/src/features/block-database/queries/table-rows.ts@@ -323,12 +323,33 @@ export function createDatabaseRowsSource(props: {const failed = rowsQuery.error();const schema =failed && isStaleSchema(failed) ? refreshSchema() : okAsync(undefined);- return schema.andThen(() => {- const table = currentTable();- return table- ? readAgain(table.table.version)- : errAsync<void, DatabaseReadFailure>(TABLE_UNAVAILABLE);- });+ const span = Telemetry.span('database.rows.read_refresh');+ span.setAttr('database.id', props.databaseId);+ span.setAttr('database.table_id', tableId);+ const reading = span.run(() =>+ schema.andThen(() => {+ const table = currentTable();+ return table+ ? readAgain(table.table.version)+ : errAsync<void, DatabaseReadFailure>(TABLE_UNAVAILABLE);+ })+ );+ return reading+ .andTee(() => {+ span.setAttr('database.outcome', 'success');+ span.end();+ })+ .orTee((failure) => {+ span.setAttr('database.outcome', 'error');+ span.setAttr('database.error_kind', failure.kind);+ span.error(JSON.stringify(failure));+ Telemetry.warn('database rows could not be refreshed', {+ databaseId: props.databaseId,+ tableId,+ failure: JSON.stringify(failure),+ });+ span.end();+ });}/** Read these rows again by id, through the engine, into the cache the view reads. */function readRows(rowIds: string[]): ResultAsync<void, DatabaseReadFailure> {diff --git a/apps/web/src/lib/queries/storage/databases-sync.test.ts b/apps/web/src/lib/queries/storage/databases-sync.test.tsindex 92e54926d0..fe4f826280 100644--- a/apps/web/src/lib/queries/storage/databases-sync.test.ts+++ b/apps/web/src/lib/queries/storage/databases-sync.test.ts@@ -81,6 +81,7 @@ it('sends the local state debounced, heartbeats it, and announces leaving on disexpect(mock.shareAwareness).toHaveBeenCalledWith({id: 'db',state: {+ peerId: expect.any(String),tableId: 'tasks',rowId: 'row-1',columnId: 'notes',@@ -94,6 +95,7 @@ it('sends the local state debounced, heartbeats it, and announces leaving on disexpect(mock.shareAwareness).toHaveBeenLastCalledWith({id: 'db',state: {+ peerId: expect.any(String),tableId: 'tasks',rowId: 'row-1',columnId: 'notes',@@ -107,6 +109,7 @@ it('sends the local state debounced, heartbeats it, and announces leaving on disexpect(mock.shareAwareness).toHaveBeenLastCalledWith({id: 'db',state: {+ peerId: expect.any(String),tableId: 'tasks',},});@@ -114,6 +117,7 @@ it('sends the local state debounced, heartbeats it, and announces leaving on disexpect(mock.shareAwareness).toHaveBeenLastCalledWith({id: 'db',state: {+ peerId: expect.any(String),tableId: 'tasks',left: true,},@@ -121,7 +125,7 @@ it('sends the local state debounced, heartbeats it, and announces leaving on disexpect(mock.shareAwareness).toHaveBeenCalledTimes(4);});-it('merges remote states per user, drops stale relays, itself, other databases, leavers, and silent viewers', () => {+it('merges legacy states per user, drops stale relays, itself, other databases, leavers, and silent viewers', () => {const { remote, dispose } = createRoot((dispose) => ({remote: useDatabaseAwareness(() => 'db',@@ -274,3 +278,45 @@ it('drops an awareness relay without its relay time', () => {);dispose();});++it('keeps same-user tabs separate, suppresses only this peer, and leaves one peer at a time', () => {+ const { remote, dispose } = createRoot((dispose) => ({+ remote: useDatabaseAwareness(+ () => 'db',+ () => ({ tableId: 'tasks' })+ ).remote,+ dispose,+ }));+ vi.advanceTimersByTime(150);+ const peerId = mock.shareAwareness.mock.calls.at(-1)![0].state.peerId;+ const first = crypto.randomUUID();+ const second = crypto.randomUUID();+ relay('me', { peerId, tableId: 'tasks', rowId: 'local' }, 100);+ relay('me', { peerId: first, tableId: 'tasks', rowId: 'one' }, 101);+ relay('me', { peerId: second, tableId: 'tasks', rowId: 'two' }, 102);+ expect(remote().map((state) => [state.userId, state.rowId])).toEqual([+ ['me', 'one'],+ ['me', 'two'],+ ]);+ relay('me', { peerId: first, tableId: 'tasks', left: true }, 103);+ expect(remote().map((state) => state.rowId)).toEqual(['two']);+ relay('me', { peerId: first, tableId: 'tasks', rowId: 'stale' }, 102);+ expect(remote().map((state) => state.rowId)).toEqual(['two']);+ // Peer ids do not replace the authenticated identity or collide across users.+ relay('alex', { peerId: second, tableId: 'tasks', rowId: 'alex' }, 104);+ expect(remote().map((state) => state.userId)).toEqual(['me', 'alex']);+ dispose();+});++it('forgets peers when switching databases', () => {+ const [database, setDatabase] = createSignal('db');+ const { remote, dispose } = createRoot((dispose) => ({+ remote: useDatabaseAwareness(database, () => ({ tableId: 'tasks' })).remote,+ dispose,+ }));+ relay('alex', { peerId: crypto.randomUUID(), tableId: 'tasks' }, 100);+ expect(remote()).toHaveLength(1);+ setDatabase('other');+ expect(remote()).toEqual([]);+ dispose();+});diff --git a/apps/web/src/lib/queries/storage/databases-sync.ts b/apps/web/src/lib/queries/storage/databases-sync.tsindex d4b7dc5f83..c98c93c233 100644--- a/apps/web/src/lib/queries/storage/databases-sync.ts+++ b/apps/web/src/lib/queries/storage/databases-sync.ts@@ -24,6 +24,7 @@ const AWARENESS_EXPIRY_MS = 45_000;const AWARENESS_SWEEP_MS = 5_000;const awarenessSchema: z.ZodType<Awareness> = z.object({+ peerId: z.string().uuid().optional(),tableId: z.string(),rowId: z.string().optional(),columnId: z.string().optional(),@@ -92,7 +93,7 @@ export function useDatabaseTableChangedSync(}/** Where this client is inside a database. */-export type LocalDatabaseAwareness = Omit<Awareness, 'left'>;+export type LocalDatabaseAwareness = Omit<Awareness, 'left' | 'peerId'>;/** Where another viewer is inside the database. */type RemoteDatabaseAwareness = Omit<Awareness, 'left' | 'editing'> & {@@ -101,8 +102,9 @@ type RemoteDatabaseAwareness = Omit<Awareness, 'left' | 'editing'> & {};type HeldAwareness = {+ userId: string;state: Awareness;- /** Server relay time, orders messages from the same viewer. */+ /** Server relay time, orders messages from the same peer. */relayedAt: number;/** Local clock, decides expiry so clock skew cannot drop live viewers. */receivedAt: number;@@ -117,12 +119,13 @@ export function useDatabaseAwareness(local: () => LocalDatabaseAwareness | undefined): { remote: Accessor<RemoteDatabaseAwareness[]> } {const userId = useUserId();+ const peerId = crypto.randomUUID();const held = new ReactiveMap<string, HeldAwareness>();let announced: { databaseId: string; state: Awareness } | undefined;const send = (id: string, state: Awareness) => {void storageServiceClient.databases- .shareAwareness({ id, state })+ .shareAwareness({ id, state: { ...state, peerId } }).mapErr((errors) =>Telemetry.warn('database awareness was not shared', {databaseId: id,@@ -175,6 +178,7 @@ export function useDatabaseAwareness(() => shareSoon()));+ createEffect(on(databaseId, () => held.clear()));const heartbeat = setInterval(() => {if (announced) send(announced.databaseId, announced.state);}, AWARENESS_HEARTBEAT_MS);@@ -183,14 +187,16 @@ export function useDatabaseAwareness(if (message.type !== AWARENESS_MESSAGE_TYPE) return;const relay = parseMessageData(message, awarenessRelaySchema);if (!relay || relay.databaseId !== databaseId()) return;- if (relay.userId === userId()) return;- const current = held.get(relay.userId);- if (current && current.relayedAt > relay.relayedAt) return;- if (relay.state.left) {- held.delete(relay.userId);+ if (+ relay.userId === userId() &&+ (!relay.state.peerId || relay.state.peerId === peerId)+ )return;- }- held.set(relay.userId, {+ const key = JSON.stringify([relay.userId, relay.state.peerId ?? null]);+ const current = held.get(key);+ if (current && current.relayedAt > relay.relayedAt) return;+ held.set(key, {+ userId: relay.userId,state: relay.state,relayedAt: relay.relayedAt,receivedAt: Date.now(),@@ -211,14 +217,17 @@ export function useDatabaseAwareness(});const remote = () =>- [...held.entries()].map(([id, { state }]) => ({- userId: id,- tableId: state.tableId,- rowId: state.rowId,- columnId: state.columnId,- endRowId: state.endRowId,- endColumnId: state.endColumnId,- editing: Boolean(state.editing),- }));+ [...held.values()]+ .filter(({ state }) => !state.left)+ .map(({ userId, state }) => ({+ userId,+ peerId: state.peerId,+ tableId: state.tableId,+ rowId: state.rowId,+ columnId: state.columnId,+ endRowId: state.endRowId,+ endColumnId: state.endColumnId,+ editing: Boolean(state.editing),+ }));return { remote };}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/awareness.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/awareness.tsindex a121ae7b7e..eed307af83 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/awareness.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/awareness.ts@@ -22,6 +22,9 @@ export interface Awareness {endRowId?: string;/** Whether the viewer left the database; other viewers drop their state. */left?: boolean;+ /** This mounted client's random peer id, distinct from its authenticated user.+Older clients omit it and remain visible as one peer per user. */+ peerId?: string;/** The row of the focused cell, if any. */rowId?: string;/** The table the viewer is looking at. */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex e0e6698dba..722c84efff 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -5419,6 +5419,12 @@ export const shareDatabaseAwarenessBody = zod.describe('Whether the viewer left the database; other viewers drop their state.'),+ peerId: zod+ .uuid()+ .optional()+ .describe(+ "This mounted client's random peer id, distinct from its authenticated user.\nOlder clients omit it and remain visible as one peer per user."+ ),rowId: zod.uuid().optional()diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex acbad01896..b4487fdd30 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -17664,6 +17664,11 @@"type": "boolean","description": "Whether the viewer left the database; other viewers drop their state."},+ "peerId": {+ "type": "string",+ "format": "uuid",+ "description": "This mounted client's random peer id, distinct from its authenticated user.\nOlder clients omit it and remain visible as one peer per user."+ },"rowId": {"type": "string","format": "uuid",diff --git a/crates/databases/src/domain/models.rs b/crates/databases/src/domain/models.rsindex 88ababeb31..6a22a99550 100644--- a/crates/databases/src/domain/models.rs+++ b/crates/databases/src/domain/models.rs@@ -973,6 +973,11 @@ pub fn grant_writes(grant: AccessLevel) -> bool {#[derive(utoipa::ToSchema, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Awareness {+ /// This mounted client's random peer id, distinct from its authenticated user.+ /// Older clients omit it and remain visible as one peer per user.+ #[schema(value_type = Option<Uuid>, nullable = false)]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub peer_id: Option<Uuid>,/// The table the viewer is looking at.#[schema(value_type = Uuid)]pub table_id: TableId,diff --git a/crates/databases/src/domain/service/test/awareness.rs b/crates/databases/src/domain/service/test/awareness.rsindex d29ac10d49..bdd8fe5164 100644--- a/crates/databases/src/domain/service/test/awareness.rs+++ b/crates/databases/src/domain/service/test/awareness.rs@@ -6,6 +6,7 @@ use super::*;async fn awareness_is_relayed_for_the_viewer() {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),@@ -39,6 +40,7 @@ async fn a_refused_relay_is_an_error() {receipt::<ViewAccessLevel>(seeded.database_id, VIEWER, AccessLevel::View),viewer(VIEWER),Awareness {+ peer_id: Some(uuid::Uuid::from_u128(7)),table_id: seeded.table_id,row_id: None,column_id: None,diff --git a/crates/databases/src/outbound/gateway_event_publisher/test.rs b/crates/databases/src/outbound/gateway_event_publisher/test.rsindex 70c4392488..c8b7b6e004 100644--- a/crates/databases/src/outbound/gateway_event_publisher/test.rs+++ b/crates/databases/src/outbound/gateway_event_publisher/test.rs@@ -27,6 +27,7 @@ fn an_awareness_relay_serializes_its_relay_time_as_epoch_milliseconds() {database_id: DatabaseId::from_uuid(Uuid::from_u128(1)),user_id: "macro|[email protected]".to_string(),state: Awareness {+ peer_id: Some(uuid::Uuid::from_u128(7)),table_id: TableId::from_uuid(Uuid::from_u128(2)),row_id: Some(RowId::from_uuid(Uuid::from_u128(3))),column_id: Some(ColumnId::from_uuid(Uuid::from_u128(4))),@@ -43,6 +44,7 @@ fn an_awareness_relay_serializes_its_relay_time_as_epoch_milliseconds() {"databaseId": "00000000-0000-0000-0000-000000000001","userId": "macro|[email protected]","state": {+ "peerId": "00000000-0000-0000-0000-000000000007","tableId": "00000000-0000-0000-0000-000000000002","rowId": "00000000-0000-0000-0000-000000000003","columnId": "00000000-0000-0000-0000-000000000004",diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.mdindex 18eff16376..3bf4b20712 100644--- a/docs/AGENT_GUIDE/databases.md+++ b/docs/AGENT_GUIDE/databases.md@@ -450,3 +450,10 @@ a SQL statement however many rows it touches, or a schema change such as a newtable or column. Consecutive edits by one person fold into `made N edits`. Changes anAI agent made read as the agent acting for the user who asked. The same entriesappear on `/app/component/activity`; clicking one opens the database.++Database awareness identifies each mounted client with a random peer ID while the+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.+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/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex cffab9d450..54d9b53a7a 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -1011,6 +1011,11 @@ export type Awareness = {* Whether the viewer left the database; other viewers drop their state.*/left?: boolean;+ /**+ * This mounted client's random peer id, distinct from its authenticated user.+ * Older clients omit it and remain visible as one peer per user.+ */+ peerId?: string;/*** The row of the focused cell, if any.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex acbad01896..b4487fdd30 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -17664,6 +17664,11 @@"type": "boolean","description": "Whether the viewer left the database; other viewers drop their state."},+ "peerId": {+ "type": "string",+ "format": "uuid",+ "description": "This mounted client's random peer id, distinct from its authenticated user.\nOlder clients omit it and remain visible as one peer per user."+ },"rowId": {"type": "string","format": "uuid",