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(sync-service): attribute AI edits to the agent or '<user> (AI)' in history and blame (#9017)
Wolf Mermelsteinc24e6b67abb5
diff --git a/apps/web/src/features/block-md/history/HistoryContext.tsx b/apps/web/src/features/block-md/history/HistoryContext.tsxindex 033c342522..fb125c6384 100644--- a/apps/web/src/features/block-md/history/HistoryContext.tsx+++ b/apps/web/src/features/block-md/history/HistoryContext.tsx@@ -1,7 +1,5 @@-import { MACRO_AGENT_BOT_ID } from '@core/constant/macroAgent';import { getDisplayName, tryMacroId } from '@core/user';import { ThrownResultError } from '@core/util/result';-import { isAiPeer } from '@macro-inc/collaboration/collab/ai-peer';import {buildDiffState,buildWhoMap,@@ -22,6 +20,7 @@ import {mapArray,useContext,} from 'solid-js';+import { type PeerRecord, peerAuthorId, useAuthorName } from './author';import { sessionize } from './sessionize';import { buildTimestampIndex } from './timestampIndex';import { userColor, userLabel } from './utils';@@ -124,13 +123,10 @@ export function HistoryProvider(props: {isOpen() || shouldLoad() ? props.documentId() : '');- // AI peers are recognizable from the peer id alone (reserved block) and all- // collapse into the single Macro identity. Checked before the peer map,- // which may attribute them to whoever's token the AI worker connected with.- const resolvePeerUser = (peers: Map<string, string>, peer: string): string =>- isAiPeer(BigInt(peer))- ? MACRO_AGENT_BOT_ID- : (peers.get(peer) ?? 'unknown');+ const resolvePeerUser = (+ peers: Map<string, PeerRecord>,+ peer: string+ ): string => peerAuthorId(peer, peers.get(peer));// Non-suspending reads of the loaded doc and peer map. Reading the resource// (`historyDoc()`) or the query.data while they're still pending bubbles@@ -140,7 +136,7 @@ export function HistoryProvider(props: {historyDoc.state === 'ready' || historyDoc.state === 'refreshing'? historyDoc.latest: undefined;- const loadedPeers = (): Map<string, string> | undefined =>+ const loadedPeers = (): Map<string, PeerRecord> | undefined =>peerMap.isSuccess ? peerMap.data : undefined;// Either fetch failing leaves the timeline permanently empty, so surface it@@ -151,17 +147,21 @@ export function HistoryProvider(props: {return null;});- // One stable display-name accessor per unique userId, batched into one fetch.+ // One stable display-name accessor per unique author, batched into one fetch.const uniqueUserIds = createMemo(() => {const peers = loadedPeers();- return peers ? [...new Set(peers.values())] : [];+ if (!peers) return [];+ return [+ ...new Set(+ [...peers].map(([peer, record]) => peerAuthorId(peer, record))+ ),+ ];});const userEntries = mapArray(uniqueUserIds, (userId) => {- const macroId = tryMacroId(userId);- const displayName = () =>- macroId- ? getDisplayName(macroId, { emailFallback: 'local-part' })- : userLabel(userId);+ const displayName = useAuthorName(+ () => userId,+ (id) => getDisplayName(tryMacroId(id), { emailFallback: 'local-part' })+ );return { userId, displayName, color: userColor(userId) };});const userById = (userId: string): HistoryUser =>diff --git a/apps/web/src/features/block-md/history/HistorySessionList.tsx b/apps/web/src/features/block-md/history/HistorySessionList.tsxindex edbc15cd77..ca500b7555 100644--- a/apps/web/src/features/block-md/history/HistorySessionList.tsx+++ b/apps/web/src/features/block-md/history/HistorySessionList.tsx@@ -3,7 +3,8 @@ import type { HistorySession } from '@service-sync/client';import { cn } from '@ui';import { type Accessor, createMemo, For, Show } from 'solid-js';import { buildActivityRows } from './activityRows';-import { userColor, userLabel } from './utils';+import { useAuthorName } from './author';+import { userColor } from './utils';type HistorySessionListProps = {sessions: readonly HistorySession[];@@ -13,8 +14,11 @@ type HistorySessionListProps = {};function UserName(props: { userId: string }) {- const name = () => getDisplayNameParts(tryMacroId(props.userId)).firstName;- return <>{name() || userLabel(props.userId)}</>;+ const name = useAuthorName(+ () => props.userId,+ (id) => getDisplayNameParts(tryMacroId(id)).firstName+ );+ return <>{name()}</>;}const MAX_NAMED = 3;diff --git a/apps/web/src/features/block-md/history/author.test.ts b/apps/web/src/features/block-md/history/author.test.tsnew file mode 100644index 0000000000..5b449ef4dd--- /dev/null+++ b/apps/web/src/features/block-md/history/author.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';+import { peerAuthorId } from './author';+import { userLabel } from './utils';++describe('peerAuthorId', () => {+ it('attributes a peer an agent registered to the agent', () => {+ expect(+ peerAuthorId('11646767255883251712', {+ userId: 'macro|[email protected]',+ actor: 'bot|0198c1a2-7b3c-7d4e-8f90-123456789abc',+ })+ ).toBe('bot|0198c1a2-7b3c-7d4e-8f90-123456789abc');+ });++ it('attributes an AI peer without an agent to the user, marked as AI', () => {+ expect(+ peerAuthorId('11646767255883251712', {+ userId: 'macro|[email protected]',+ actor: null,+ })+ ).toBe('ai|macro|[email protected]');+ expect(userLabel('ai|macro|[email protected]')).toBe('[email protected] (AI)');+ });++ it('still recognizes AI peers from the legacy reserved block', () => {+ expect(+ peerAuthorId('999999999999999000', {+ userId: 'macro|[email protected]',+ actor: null,+ })+ ).toBe('ai|macro|[email protected]');+ });++ it('attributes a human peer to its user', () => {+ expect(+ peerAuthorId('4242424242', {+ userId: 'macro|[email protected]',+ actor: null,+ })+ ).toBe('macro|[email protected]');+ expect(peerAuthorId('4242424242', undefined)).toBe('unknown');+ });++ it('falls back to Macro for an AI peer with no record', () => {+ expect(peerAuthorId('11646767255883251712', undefined)).toBe(+ '00000000-0000-0000-0000-00000000a1a1'+ );+ });+});diff --git a/apps/web/src/features/block-md/history/author.ts b/apps/web/src/features/block-md/history/author.tsnew file mode 100644index 0000000000..75640eb553--- /dev/null+++ b/apps/web/src/features/block-md/history/author.ts@@ -0,0 +1,55 @@+import {+ isBotPrincipalId,+ MACRO_AGENT_BOT_ID,+} from '@core/constant/macroAgent';+import { isAiPeer } from '@macro-inc/collaboration/collab/ai-peer';+import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';+import type { Accessor } from 'solid-js';+import { AI_AUTHOR_PREFIX, aiAuthorOnBehalfOf, userLabel } from './utils';++/** What the sync service recorded for a peer: whose token registered it, and+ * the signed agent actor (`bot|<uuid>`) it edited as, if any. */+export type PeerRecord = { userId: string; actor: string | null };++/**+ * Who a peer's edits are attributed to. A peer an agent registered resolves to+ * the agent (`bot|<uuid>`); any other AI peer to `ai|<userId>`, the user it+ * edited for; a human peer to its user. An AI peer with no record (registered+ * anonymously) falls back to Macro.+ */+export function peerAuthorId(+ peer: string,+ record: PeerRecord | undefined+): string {+ if (record?.actor) return record.actor;+ if (isAiPeer(BigInt(peer))) {+ return record ? `${AI_AUTHOR_PREFIX}${record.userId}` : MACRO_AGENT_BOT_ID;+ }+ return record?.userId ?? 'unknown';+}++/** The principal an author's avatar shows: the user behind an `ai|` author. */+export function authorPrincipalId(authorId: string): string {+ return aiAuthorOnBehalfOf(authorId) ?? authorId;+}++/**+ * Display name for an author id from `peerAuthorId`: the agent's name, `<user>+ * (AI)` for AI edits made for a user, or `userName` for a human. `userName` may+ * return '' while names load; the id's plain label stands in.+ */+export function useAuthorName(+ authorId: Accessor<string>,+ userName: (userId: string) => string+): Accessor<string> {+ const principal = () => authorPrincipalId(authorId());+ const bot = usePropertyUserDisplay(principal);+ const humanName = (userId: string) => userName(userId) || userLabel(userId);+ return () => {+ const id = authorId();+ const onBehalfOf = aiAuthorOnBehalfOf(id);+ if (onBehalfOf !== undefined) return `${humanName(onBehalfOf)} (AI)`;+ if (isBotPrincipalId(id)) return bot.name();+ return humanName(id);+ };+}diff --git a/apps/web/src/features/block-md/history/utils.ts b/apps/web/src/features/block-md/history/utils.tsindex 1603225abd..ffbe3948a9 100644--- a/apps/web/src/features/block-md/history/utils.ts+++ b/apps/web/src/features/block-md/history/utils.ts@@ -13,9 +13,21 @@ export function userColor(userId: string): string {*/export const SYSTEM_AUTHOR_ID = 'system';+/** Prefix of an author id for AI edits made for a user: `ai|<userId>`. */+export const AI_AUTHOR_PREFIX = 'ai|';++/** The user an `ai|<userId>` author edited for, or undefined for any other id. */+export function aiAuthorOnBehalfOf(authorId: string): string | undefined {+ return authorId.startsWith(AI_AUTHOR_PREFIX)+ ? authorId.slice(AI_AUTHOR_PREFIX.length)+ : undefined;+}+export function userLabel(userId: string): string {if (userId === 'unknown') return 'Unknown';if (userId === SYSTEM_AUTHOR_ID) return MACRO_AGENT_NAME;+ const onBehalfOf = aiAuthorOnBehalfOf(userId);+ if (onBehalfOf !== undefined) return `${userLabel(onBehalfOf)} (AI)`;if (isMacroAgentId(userId)) return `${MACRO_AGENT_NAME} (AI)`;const id = tryMacroId(userId);return id ? macroIdToEmail(id) : userId;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/blame-tooltip/BlameTooltip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/blame-tooltip/BlameTooltip.tsxindex 78b508f69c..cf8432717c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/blame-tooltip/BlameTooltip.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/blame-tooltip/BlameTooltip.tsx@@ -1,3 +1,8 @@+import {+ authorPrincipalId,+ peerAuthorId,+ useAuthorName,+} from '@block-md/history/author';import { UserIcon } from '@core/component/UserIcon';import { getDisplayNameParts, macroIdToEmail, tryMacroId } from '@core/user';import { formatRelativeTimestamp } from '@entity';@@ -17,15 +22,26 @@ import type { BlameTooltipState } from './blameTooltipPlugin';const FETCH_DELAY_MS = 400;const SHOW_DELAY_MS = 500;-function UserLine(props: { userId: string; editedAt: Date }) {- const macroId = tryMacroId(props.userId);- const name = () =>- getDisplayNameParts(macroId).firstName ||- (macroId ? macroIdToEmail(macroId) : props.userId);+function UserLine(props: { authorId: string; editedAt: Date }) {+ const name = useAuthorName(+ () => props.authorId,+ (userId) => {+ const macroId = tryMacroId(userId);+ return (+ getDisplayNameParts(macroId).firstName ||+ (macroId ? macroIdToEmail(macroId) : userId)+ );+ }+ );return (<span class="inline-flex items-center gap-1">- <UserIcon id={props.userId} size="sm" suppressClick showTooltip={false} />+ <UserIcon+ id={authorPrincipalId(props.authorId)}+ size="sm"+ suppressClick+ showTooltip={false}+ />{name()}, {formatRelativeTimestamp(props.editedAt)}</span>);@@ -78,8 +94,20 @@ export function BlameTooltip(props: {onCleanup(hide);+ const blame = () => {+ const data = visible() ? query.data : undefined;+ if (!data?.userId) return undefined;+ return {+ authorId: peerAuthorId(data.peerId, {+ userId: data.userId,+ actor: data.actor,+ }),+ editedAt: data.editedAt,+ };+ };+return (- <Show when={visible() && query.data?.userId ? query.data : undefined}>+ <Show when={blame()}>{(b) => (<divclass="fixed z-tool-tip rounded-md bg-surface px-2 py-1 text-xs text-ink-muted/70 pointer-events-none"@@ -88,7 +116,7 @@ export function BlameTooltip(props: {top: `${props.state.y + 12}px`,}}>- <UserLine userId={b().userId!} editedAt={b().editedAt} />+ <UserLine authorId={b().authorId} editedAt={b().editedAt} /></div>)}</Show>diff --git a/apps/web/src/lib/queries/sync/document-peers.ts b/apps/web/src/lib/queries/sync/document-peers.tsindex 7953bee2af..60c8b9f9c8 100644--- a/apps/web/src/lib/queries/sync/document-peers.ts+++ b/apps/web/src/lib/queries/sync/document-peers.ts@@ -1,3 +1,4 @@+import type { PeerRecord } from '@block-md/history/author';import { ThrownResultError } from '@core/util/result';import { syncServiceClient } from '@service-sync/client';import { queryOptions, useQuery } from '@tanstack/solid-query';@@ -6,10 +7,15 @@ import { syncKeys } from './keys';async function fetchDocumentPeers(documentId: string-): Promise<Map<string, string>> {+): Promise<Map<string, PeerRecord>> {const result = await syncServiceClient.getDocumentMetadata({ documentId });if (result.isErr()) throw new ThrownResultError(result.error);- return new Map(result.value.peers.map((p) => [String(p.peer_id), p.user_id]));+ return new Map(+ result.value.peers.map((p) => [+ String(p.peer_id),+ { userId: p.user_id, actor: p.actor ?? null },+ ])+ );}function documentPeersQueryOptions(documentId: string) {diff --git a/apps/web/src/lib/service-clients/service-sync/client.ts b/apps/web/src/lib/service-clients/service-sync/client.tsindex 8b98c51dcd..2a4f22febd 100644--- a/apps/web/src/lib/service-clients/service-sync/client.ts+++ b/apps/web/src/lib/service-clients/service-sync/client.ts@@ -190,7 +190,8 @@ export const syncServiceClient = {/*** Look up who last edited a given Lexical node and when. `user_id` is a* MacroId resolved server-side; `null` if the peer has no recorded user- * (anonymous edits or legacy data not yet mirrored locally).+ * (anonymous edits or legacy data not yet mirrored locally). `actor` is the+ * signed agent actor (`bot|<uuid>`) the peer edited as, null for humans.*/async getNodeBlame(args: { documentId: string; nodeId: string }) {const token = await getPermissionToken('document', args.documentId);@@ -209,10 +210,11 @@ export const syncServiceClient = {if (response.isErr()) {return err(response.error);}- const { peer_id, user_id, timestamp_ms } = response.value;+ const { peer_id, user_id, actor, timestamp_ms } = response.value;return ok({peerId: peer_id,userId: user_id ?? null,+ actor: actor ?? null,editedAt: new Date(timestamp_ms),});},diff --git a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRow.ts b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRow.tsindex 66472704ae..66674be64e 100644--- a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRow.ts+++ b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRow.ts@@ -5,9 +5,12 @@* Document sync service JSON control plane* OpenAPI spec version: 0.1.0*/+import type { BlameRowActor } from './blameRowActor';import type { BlameRowUserId } from './blameRowUserId';export interface BlameRow {+ /** Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans. */+ actor?: BlameRowActor;peer_id: string;timestamp_ms: number;user_id?: BlameRowUserId;diff --git a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRowActor.ts b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRowActor.tsnew file mode 100644index 0000000000..8a446802d9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/blameRowActor.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Sync Service+ * Document sync service JSON control plane+ * OpenAPI spec version: 0.1.0+ */++/**+ * Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans.+ */+export type BlameRowActor = string | null;diff --git a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/index.ts b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/index.tsindex ed87fd9d01..764a437970 100644--- a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/index.ts@@ -8,6 +8,7 @@export * from './binaryBody';export * from './blameRow';+export * from './blameRowActor';export * from './blameRowUserId';export * from './copyDocumentRequest';export * from './copyDocumentRequestVersionId';@@ -18,6 +19,7 @@ export * from './getSnapshotRequest';export * from './getSnapshotRequestVersionId';export * from './peerResponse';export * from './peerWithUserId';+export * from './peerWithUserIdActor';export * from './snapshotResponse';export * from './updateRequest';export * from './updateResponse';diff --git a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserId.ts b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserId.tsindex 8b3c4b0625..7a7772f39a 100644--- a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserId.ts+++ b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserId.ts@@ -5,8 +5,11 @@* Document sync service JSON control plane* OpenAPI spec version: 0.1.0*/+import type { PeerWithUserIdActor } from './peerWithUserIdActor';export interface PeerWithUserId {+ /** Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans. */+ actor?: PeerWithUserIdActor;peer_id: string;user_id: string;}diff --git a/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserIdActor.ts b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserIdActor.tsnew file mode 100644index 0000000000..24e16fb996--- /dev/null+++ b/apps/web/src/lib/service-clients/service-sync/generated/http/schemas/peerWithUserIdActor.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Sync Service+ * Document sync service JSON control plane+ * OpenAPI spec version: 0.1.0+ */++/**+ * Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans.+ */+export type PeerWithUserIdActor = string | null;diff --git a/apps/web/src/lib/service-clients/service-sync/openapi.json b/apps/web/src/lib/service-clients/service-sync/openapi.jsonindex f7266c5393..867b566e43 100644--- a/apps/web/src/lib/service-clients/service-sync/openapi.json+++ b/apps/web/src/lib/service-clients/service-sync/openapi.json@@ -564,6 +564,10 @@"type": "object","required": ["peer_id", "timestamp_ms"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans."+ },"peer_id": {"type": "string"},@@ -644,6 +648,10 @@"type": "object","required": ["peer_id", "user_id"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans."+ },"peer_id": {"type": "string"},diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 07d21c5a26..713feeed69 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -3006,6 +3006,10 @@ selected version into a separate document. **Close history** or Escape returnsto the mounted editor without losing its scroll position. The two columns scrollindependently, and other app splits remain available.+Sessions, diffs, and blame tooltips name AI edits by who made them: an agent's+edits show the agent's name, and other AI-editor writes show+`<user> (AI)` for the user they were made for.+## Side panelRight side of a doc (toggle with `Hide/Show Side Panel`):diff --git a/packages/collaboration/src/collab/ai-peer.ts b/packages/collaboration/src/collab/ai-peer.tsindex 0cf9cd1f9b..139413cd6e 100644--- a/packages/collaboration/src/collab/ai-peer.ts+++ b/packages/collaboration/src/collab/ai-peer.ts@@ -1,12 +1,20 @@/**- * AI editors connect to the sync service with peer ids drawn from a reserved- * block, so they can be recognized from the peer id alone (no peer→user- * mapping required).+ * AI editors connect to the sync service with peer ids drawn at random from a+ * reserved 2^40-wide block under the `0xA1A1A1` prefix, so they can be+ * recognized from the peer id alone, and a peer id is never reused by a later+ * edit session (its recorded identity is never overwritten).+ *+ * Older AI edits used a 1000-wide block of 15 leading 9s plus 3 digits; those+ * peers stay in document history, so they are still recognized.** Keep in sync with `sync-service` (`ai_peer.rs`).*/-export const AI_PEER_COUNT = 1000;-export const AI_PEER_BASE = 999_999_999_999_999_000n;+export const AI_PEER_COUNT = 1n << 40n;+export const AI_PEER_BASE = 0xa1a1_a100_0000_0000n;+const LEGACY_AI_PEER_COUNT = 1000n;+const LEGACY_AI_PEER_BASE = 999_999_999_999_999_000n;export const isAiPeer = (peer: bigint): boolean =>- peer >= AI_PEER_BASE && peer < AI_PEER_BASE + BigInt(AI_PEER_COUNT);+ (peer >= AI_PEER_BASE && peer < AI_PEER_BASE + AI_PEER_COUNT) ||+ (peer >= LEGACY_AI_PEER_BASE &&+ peer < LEGACY_AI_PEER_BASE + LEGACY_AI_PEER_COUNT);diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.mdindex aedf300c7e..b3a81e5db3 100644--- a/services/ai-editing-worker/AI_EDITING.md+++ b/services/ai-editing-worker/AI_EDITING.md@@ -145,11 +145,15 @@ writer also gets one of a few accent colors; the cursor lingers ~700ms after thewriter finishes, then clears. We have some ugly code that manages resolving ablock id to the `LoroText` that actually owns the characters for this :/-**The peer id** Human peers get random ids from the whole 64b range, and we have-it so that AI commits use a small reserved range in-(`999999999999999000`–`999999999999999999`). This makes Markdown AI authorship easy to-detect (`isAiPeer`) which history can use for grouping. Canvas instead uses-full-width random session IDs and signed actor attribution, as described below.+**The peer id** Human peers get random ids from the whole 64b range; AI commits+draw a random id from a reserved 2^40 block under the `0xA1A1A1` prefix+(`nextAiPeerId`), so Markdown AI authorship is easy to detect (`isAiPeer`). Never+reuse an AI peer id: the sync service records the user and signed agent actor+each peer registers with (`peer_user_map`), and history and blame label edits+from that record, so a reused id would re-attribute every earlier edit made+under it. The old `999999999999999000`–`999999999999999999` block is still+recognized for existing history. Canvas instead uses full-width random session+IDs and signed actor attribution, as described below.## Comment marksdiff --git a/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.test.ts b/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.test.tsnew file mode 100644index 0000000000..59e9bc7af1--- /dev/null+++ b/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.test.ts@@ -0,0 +1,10 @@+import { describe, expect, it } from 'vitest';+import { isAiPeer, nextAiPeerId } from './ai-peer';++describe('nextAiPeerId', () => {+ it('draws recognizable AI peers that are never reused', () => {+ const ids = Array.from({ length: 1000 }, nextAiPeerId);+ expect(ids.every(isAiPeer)).toBe(true);+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.ts b/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.tsindex b2b06aa6b3..90b72530c6 100644--- a/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.ts+++ b/services/ai-editing-worker/src/ai-editing/awareness/ai-peer.ts@@ -1,16 +1,14 @@/**- * AI editors draw their Loro peer id from a small reserved block whose decimal- * form is 15 leading 9s followed by a 3-digit identity, i.e.- * `999999999999999000 ... 999999999999999999`.+ * AI editors draw their Loro peer id at random from a reserved 2^40-wide block+ * (see `@macro-inc/collaboration/collab/ai-peer`). The sync service records the+ * identity each peer edits as, so a peer id must never be reused by another+ * edit session: a reuse would re-attribute every earlier edit made under it.*- * A human's peer id is random across all 2^64 values, so the chance one lands in- * this 1000-wide window is basically zero.+ * A human's peer id is random across all 2^64 values, so the chance one lands+ * in this block is 2^-24.*/-import {- AI_PEER_BASE,- AI_PEER_COUNT,-} from '@macro-inc/collaboration/collab/ai-peer';+import { AI_PEER_BASE } from '@macro-inc/collaboration/collab/ai-peer';export {AI_PEER_BASE,@@ -18,14 +16,10 @@ export {isAiPeer,} from '@macro-inc/collaboration/collab/ai-peer';-// the worker's lifecycle is naturally short-lived enough that this should be fine-let nextOffset = 0;--/** Hand out the next AI peer id, cycling through the block. Sequential, so- * consecutive editors never share an id; with concurrency far below- * AI_PEER_COUNT, two live editors can never collide. */+/** A fresh AI peer id. Uniform over the 2^40 block, so two editors (live or+ * across isolates) sharing one is vanishingly unlikely. */export const nextAiPeerId = (): bigint => {- const id = AI_PEER_BASE + BigInt(nextOffset);- nextOffset = (nextOffset + 1) % AI_PEER_COUNT;- return id;+ const [high, low] = crypto.getRandomValues(new Uint32Array(2));+ const offset = (BigInt(high & 0xff) << 32n) | BigInt(low);+ return AI_PEER_BASE + offset;};diff --git a/services/sync-service/AGENTS.md b/services/sync-service/AGENTS.mdindex 39b5cd4dbb..8aeff35521 100644--- a/services/sync-service/AGENTS.md+++ b/services/sync-service/AGENTS.md@@ -48,7 +48,9 @@ updates over WebSocket.`src/inbound/durable_object/surface_migration.rs` if it changes stored shape.Active-peer queries with `include_ai=false` exclude signed agent actors and the-legacy reserved AI peer range; Canvas workers use random full-width peer IDs.+reserved AI peer blocks (`ai_peer.rs`); Canvas workers use random full-width+peer IDs. `peer_user_map` records each peer's user and agent actor; history and+blame attribute edits from it, so never reuse an AI peer id.Document read/write/debug handlers declare their minimum session grant throughAxum extractors; atomic reads/updates require a signed document grant even when@@ -78,8 +80,10 @@ to the requested surface. These are scoped sync JWTs, not app-session tokens.makes the front worker fail connects, which clients see as close 1006.- Document history names each Loro peer from D1 `peer_user_map`, so everypath that writes operations maps the peers it writes with: WebSocket and- HTTP `/update` writes to their user, `/initialize` snapshots to the system- author (`SYSTEM_AUTHOR_ID`), and `/copy` copies the source's mappings first.+ HTTP `/update` writes to their user and signed agent actor, `/initialize`+ snapshots to the system author (`SYSTEM_AUTHOR_ID`), and `/copy` copies the+ source's mappings first. A peer's first owner keeps it; registration only+ claims peers the system author holds.A new write path does the same (`tests/peer_authors.test.ts`).- `migration-test-hooks` is test-only fault injection — never enable it in adeployed worker (see the feature's doc comment in `Cargo.toml`).diff --git a/services/sync-service/README.md b/services/sync-service/README.mdindex 380a8b477e..8a67d0377a 100644--- a/services/sync-service/README.md+++ b/services/sync-service/README.md@@ -197,7 +197,12 @@ Deploy DSS before Sync to enable Activity hints immediately. If an older DSSrejects the optional `editors` field, Sync retries once without it so searchcontinues working. Old Sync requests and old Kafka events remain supported.+Each registered peer is recorded in D1 `peer_user_map` with the token's user and+signed agent actor (NULL for humans); the metadata and blame endpoints return+both, and the web labels agent edits with the agent's name and other AI-peer+edits as `<user> (AI)`.+Active peer queries (`include_ai=false`) exclude both signed agent actors and-legacy reserved AI peer IDs. Canvas workers use independent full-width random+reserved AI peer IDs. Canvas workers use independent full-width randomLoro peer identities across worker isolates; signed actor claims still supplydurable provenance. Cursor names remain untrusted ephemeral presentation.diff --git a/services/sync-service/database/user-peer-mapping/migrations/0003_add_peer_actor.sql b/services/sync-service/database/user-peer-mapping/migrations/0003_add_peer_actor.sqlnew file mode 100644index 0000000000..9af0abbb33--- /dev/null+++ b/services/sync-service/database/user-peer-mapping/migrations/0003_add_peer_actor.sql@@ -0,0 +1,2 @@+-- The signed agent actor (e.g. `bot|<uuid>`) a peer edited as, NULL for humans.+ALTER TABLE peer_user_map ADD COLUMN actor TEXT;diff --git a/services/sync-service/src/ai_peer.rs b/services/sync-service/src/ai_peer.rsindex f7c1da8162..77f8a8d0ed 100644--- a/services/sync-service/src/ai_peer.rs+++ b/services/sync-service/src/ai_peer.rs@@ -1,11 +1,22 @@-//! AI editors draw their Loro peer id from a reserved block: 15 leading 9s-//! followed by a 3-digit identity (`999_999_999_999_999_000 ..= ...999`). A-//! human's peer id is random across all of u64, so a collision is ~nil.+//! AI editors draw their Loro peer id at random from a reserved 2^40-wide block+//! under the `0xA1A1A1` prefix. Random draws never repeat in practice, so a+//! peer's recorded identity (`peer_user_map`) is never overwritten by a later+//! edit session. A human's peer id is random across all of u64, so the chance+//! one lands in the block is 2^-24.+//!+//! Older AI edits used a 1000-wide block of 15 leading 9s plus 3 digits; their+//! peers stay in document history, so they are still recognized.//! Keep in sync with the TS definition (`isAiPeer` / `AI_PEER_BASE`).-pub const AI_PEER_COUNT: u64 = 1000;-pub const AI_PEER_BASE: u64 = 999_999_999_999_999_000;+pub const AI_PEER_COUNT: u64 = 1 << 40;+pub const AI_PEER_BASE: u64 = 0xA1A1_A100_0000_0000;+const LEGACY_AI_PEER_COUNT: u64 = 1000;+const LEGACY_AI_PEER_BASE: u64 = 999_999_999_999_999_000;pub fn is_ai_peer(peer: u64) -> bool {(AI_PEER_BASE..AI_PEER_BASE + AI_PEER_COUNT).contains(&peer)+ || (LEGACY_AI_PEER_BASE..LEGACY_AI_PEER_BASE + LEGACY_AI_PEER_COUNT).contains(&peer)}++#[cfg(test)]+mod test;diff --git a/services/sync-service/src/ai_peer/test.rs b/services/sync-service/src/ai_peer/test.rsnew file mode 100644index 0000000000..4b6a67746f--- /dev/null+++ b/services/sync-service/src/ai_peer/test.rs@@ -0,0 +1,15 @@+use super::*;++#[test]+fn recognizes_current_and_legacy_ai_blocks_but_not_their_neighbours() {+ assert!(is_ai_peer(0xA1A1_A100_0000_0000));+ assert!(is_ai_peer(0xA1A1_A1FF_FFFF_FFFF));+ assert!(is_ai_peer(999_999_999_999_999_000));+ assert!(is_ai_peer(999_999_999_999_999_999));++ assert!(!is_ai_peer(0xA1A1_A0FF_FFFF_FFFF));+ assert!(!is_ai_peer(0xA1A1_A200_0000_0000));+ assert!(!is_ai_peer(999_999_999_999_998_999));+ assert!(!is_ai_peer(1_000_000_000_000_000_000));+ assert!(!is_ai_peer(42));+}diff --git a/services/sync-service/src/domain/models.rs b/services/sync-service/src/domain/models.rsindex c582cd4d14..defcc8e10b 100644--- a/services/sync-service/src/domain/models.rs+++ b/services/sync-service/src/domain/models.rs@@ -39,6 +39,8 @@ pub struct PeerResponse {pub struct PeerWithUserId {pub peer_id: String,pub user_id: String,+ /// Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans.+ pub actor: Option<String>,}#[derive(serde::Deserialize, serde::Serialize)]@@ -46,5 +48,7 @@ pub struct PeerWithUserId {pub struct BlameRow {pub peer_id: String,pub user_id: Option<String>,+ /// Signed agent actor (`bot|<uuid>`) the peer edited as; null for humans.+ pub actor: Option<String>,pub timestamp_ms: i64,}diff --git a/services/sync-service/src/inbound/durable_object.rs b/services/sync-service/src/inbound/durable_object.rsindex 18d3e25129..c68220565b 100644--- a/services/sync-service/src/inbound/durable_object.rs+++ b/services/sync-service/src/inbound/durable_object.rs@@ -226,7 +226,14 @@ impl<'a> Wsm<'a> {// if user is not-anonif let Some(user_id) = meta.user_id {let db = self.dss.env.d1(USER_PEER_D1_BINDING)?;- insert_user_mapping(db, &user_id, peerid, document_id).await?;+ let span = tracing::info_span!(+ "peer.register",+ document.id = document_id,+ peer.id = peerid+ );+ insert_user_mapping(db, &user_id, meta.actor.as_deref(), peerid, document_id)+ .instrument(span)+ .await?;}}Ok(())@@ -381,7 +388,8 @@ impl SyncSession {let writers = writing_peers(&body.snapshot).map_err(|error| Error::from(format!("invalid initial snapshot: {error}")))?;let db = self.env.d1(USER_PEER_D1_BINDING)?;- insert_missing_user_mappings(&db, document_id, SYSTEM_AUTHOR_ID, &writers).await?;+ insert_missing_user_mappings(&db, document_id, SYSTEM_AUTHOR_ID, None, &writers)+ .await?;storage.store_snapshot(&body.snapshot).await?;*self.document_iddiff --git a/services/sync-service/src/inbound/durable_object/document_api.rs b/services/sync-service/src/inbound/durable_object/document_api.rsindex 5d2716658f..d4508e7220 100644--- a/services/sync-service/src/inbound/durable_object/document_api.rs+++ b/services/sync-service/src/inbound/durable_object/document_api.rs@@ -162,7 +162,14 @@ impl SyncSession {Err(error) => return error_response(error),};let db = self.env.d1(USER_PEER_D1_BINDING)?;- insert_missing_user_mappings(&db, document_id, &author, &writers).await?;+ insert_missing_user_mappings(+ &db,+ document_id,+ &author,+ stored_attribution.map(|attribution| attribution.actor.as_str()),+ &writers,+ )+ .await?;Response::from_json(&UpdateResponse {revision: STANDARD.encode(prepared.revision),applied: prepared.applied,diff --git a/services/sync-service/src/inbound/durable_object/peer_ids.rs b/services/sync-service/src/inbound/durable_object/peer_ids.rsindex 9fdf6e21c9..336dbd189d 100644--- a/services/sync-service/src/inbound/durable_object/peer_ids.rs+++ b/services/sync-service/src/inbound/durable_object/peer_ids.rs@@ -26,13 +26,13 @@ impl Wsm<'_> {pub async fn add_writing_peerids(&mut self, peerids: &[u64], document_id: &str) -> Result<()> {self.maybe_update_ws_meta_map().await?;let ws_id = self.get_ws_id()?.to_string();- let user_id = {+ let (user_id, actor) = {let wmm = self.dss.ws_meta_map.lock("Wsm::add_writing_peerids get");let meta = wmm.get(&ws_id).ok_or(Error::from("missing ws metadata"))?;let Some(user_id) = meta.user_id.clone() else {return Ok(());};- user_id+ (user_id, meta.actor.clone())};let new_peers: Vec<u64> = {let mapped = self@@ -49,7 +49,8 @@ impl Wsm<'_> {return Ok(());}let db = self.dss.env.d1(USER_PEER_D1_BINDING)?;- insert_missing_user_mappings(&db, document_id, &user_id, &new_peers).await?;+ insert_missing_user_mappings(&db, document_id, &user_id, actor.as_deref(), &new_peers)+ .await?;// Remembered only once stored, so a failed write is retried with the// client's resent update.self.dssdiff --git a/services/sync-service/src/outbound/d1.rs b/services/sync-service/src/outbound/d1.rsindex aeba5fe453..752e99294d 100644--- a/services/sync-service/src/outbound/d1.rs+++ b/services/sync-service/src/outbound/d1.rs@@ -1,20 +1,34 @@-use crate::timeit;+use crate::{constants::SYSTEM_AUTHOR_ID, timeit};use tracing::{error, trace};+use wasm_bindgen::JsValue;use worker::D1Database;++/// Records who a peer edits as: the user whose token registered it, and the+/// signed agent actor when the edit came from an agent acting for that user.+/// The first owner keeps the peer, so a later registration of the same id can't+/// re-attribute its edits; only a peer the system author holds (one an+/// initialized snapshot wrote) is claimed by the user who registers it.pub async fn insert_user_mapping(db: D1Database,user_id: &str,+ actor: Option<&str>,peer_id: u64,document_id: &str,) -> worker::Result<()> {let elapsed = timeit!({let dbres = db.prepare(- "INSERT OR REPLACE INTO peer_user_map (document_id, peer_id, user_id) VALUES (?, ?, ?);",+ "INSERT INTO peer_user_map (document_id, peer_id, user_id, actor) VALUES (?, ?, ?, ?) \+ ON CONFLICT(document_id, peer_id) DO UPDATE SET \+ user_id = excluded.user_id, \+ actor = excluded.actor \+ WHERE peer_user_map.user_id = ?;",).bind(&[document_id.into(),peer_id.to_string().into(),user_id.into(),+ actor.map_or(JsValue::NULL, JsValue::from),+ SYSTEM_AUTHOR_ID.into(),])?.run().await?;@@ -41,12 +55,14 @@ pub async fn insert_user_mapping(Ok(())}-/// Map peers that wrote operations to `user_id`, keeping any mapping a peer-/// already has: a peer that registered explicitly stays with its owner.+/// Map peers that wrote operations to `user_id` (and the agent `actor` they+/// wrote as), keeping any mapping a peer already has: a peer that registered+/// explicitly stays with its owner.pub async fn insert_missing_user_mappings(db: &D1Database,document_id: &str,user_id: &str,+ actor: Option<&str>,peer_ids: &[u64],) -> worker::Result<()> {for chunk in peer_ids.chunks(BATCH_CHUNK_SIZE) {@@ -54,9 +70,14 @@ pub async fn insert_missing_user_mappings(.iter().map(|peer_id| {db.prepare(- "INSERT OR IGNORE INTO peer_user_map (document_id, peer_id, user_id) VALUES (?, ?, ?);",+ "INSERT OR IGNORE INTO peer_user_map (document_id, peer_id, user_id, actor) VALUES (?, ?, ?, ?);",)- .bind(&[document_id.into(), peer_id.to_string().into(), user_id.into()])+ .bind(&[+ document_id.into(),+ peer_id.to_string().into(),+ user_id.into(),+ actor.map_or(JsValue::NULL, JsValue::from),+ ])}).collect::<worker::Result<Vec<_>>>()?;db.batch(statements).await?;@@ -72,8 +93,8 @@ pub async fn copy_user_mappings(target_document_id: &str,) -> worker::Result<()> {db.prepare(- "INSERT OR IGNORE INTO peer_user_map (document_id, peer_id, user_id) \- SELECT ?, peer_id, user_id FROM peer_user_map WHERE document_id = ?;",+ "INSERT OR IGNORE INTO peer_user_map (document_id, peer_id, user_id, actor) \+ SELECT ?, peer_id, user_id, actor FROM peer_user_map WHERE document_id = ?;",).bind(&[target_document_id.into(), source_document_id.into()])?.run()@@ -112,7 +133,7 @@ pub async fn get_peers_for_document_id() -> worker::Result<Vec<PeerWithUserId>> {let statement = db.prepare("- SELECT peer_id, user_id+ SELECT peer_id, user_id, actorFROM peer_user_mapWHERE document_id = ?;",@@ -198,6 +219,7 @@ pub async fn get_blame_for_node("SELECT b.peer_id AS peer_id,p.user_id AS user_id,+ p.actor AS actor,b.timestamp_ms AS timestamp_msFROM blame bLEFT JOIN peer_user_map pdiff --git a/services/sync-service/tests/peer_attribution.test.ts b/services/sync-service/tests/peer_attribution.test.tsnew file mode 100644index 0000000000..2c1d59c738--- /dev/null+++ b/services/sync-service/tests/peer_attribution.test.ts@@ -0,0 +1,140 @@+import jwt from "jsonwebtoken";+import { LoroDoc } from "loro-crdt";+import { Miniflare } from "miniflare";+import { beforeEach, expect, test } from "vitest";+import { FromPeer, FromRemote, InitializeFromSnapshotRequest } from "../bebop/generated/schema";+import { copyDocument, createTestWebSocket, getTokenForDocument, setupMiniflare } from "./utils";++let mf: Miniflare;++beforeEach(async () => {+ mf = await setupMiniflare();+});++const documentId = "attribution-doc";++/** Connect with `claims`, register `peer`, and write one edit under it. The+ * edit's ack proves the registration before it has been handled. */+async function editAs(claims: Record<string, string>, peer: bigint, text: string) {+ const token = jwt.sign(+ { document_id: documentId, access_level: "edit", exp: Math.floor(Date.now() / 1000) + 60, ...claims },+ "local",+ );+ const response = await mf.dispatchFetch(+ `http://localhost:8787/document/${documentId}/connect?token=${token}`,+ { headers: { Upgrade: "websocket" } },+ );+ const ws = response.webSocket!;+ const socket = createTestWebSocket(ws);+ ws.accept();+ const initialSync = FromRemote.decode(new Uint8Array((await socket.waitForNextMessage()) as ArrayBuffer));+ expect(initialSync.isRemoteInitialSync()).toBe(true);+ const doc = new LoroDoc();+ doc.setPeerId(peer);+ if (initialSync.isRemoteInitialSync()) doc.import(initialSync.value.snapshot);+ socket.send(FromPeer.fromPeerRegisterId({ peerid: peer }).encode());+ doc.getText("content").insert(0, text);+ doc.commit();+ socket.send(FromPeer.fromPeerUpdate({ updates: [doc.export({ mode: "update" })], id: crypto.randomUUID() }).encode());+ const ack = FromRemote.decode(new Uint8Array((await socket.waitForNextMessage()) as ArrayBuffer));+ expect(ack.isRemoteUpdateAck()).toBe(true);+ ws.close();+}++const authorized = (path: string) =>+ mf.dispatchFetch(`http://localhost:8787/document/${documentId}/${path}`, {+ headers: { Authorization: `Bearer ${getTokenForDocument(documentId, "reader", "view")}` },+ });++test("an agent's AI peer resolves to the agent in metadata and blame", async () => {+ const aiPeer = 0xa1a1_a100_0000_0001n;+ const humanPeer = 4242n;+ await editAs({ user_id: "macro|[email protected]", actor: "bot|agent-1" }, aiPeer, "agent ");+ await editAs({ user_id: "macro|[email protected]" }, humanPeer, "human ");++ const metadata = (await (await authorized("metadata")).json()) as {+ peers: { peer_id: string; user_id: string; actor: string | null }[];+ };+ expect(metadata.peers).toEqual(+ expect.arrayContaining([+ { peer_id: aiPeer.toString(), user_id: "macro|[email protected]", actor: "bot|agent-1" },+ { peer_id: humanPeer.toString(), user_id: "macro|[email protected]", actor: null },+ ]),+ );++ const db = await mf.getD1Database("USER_PEER_MAPPING");+ await db+ .prepare("INSERT INTO blame (document_id, node_id, peer_id, timestamp_ms) VALUES (?, 'node', ?, 7)")+ .bind(documentId, aiPeer.toString())+ .run();+ expect(await (await authorized("blame/node")).json()).toEqual({+ peer_id: aiPeer.toString(),+ user_id: "macro|[email protected]",+ actor: "bot|agent-1",+ timestamp_ms: 7,+ });+});++test("an agent's HTTP update records the agent, and a copy keeps it", async () => {+ const doc = new LoroDoc();+ doc.setPeerId(5001n);+ doc.getText("content").insert(0, "start");+ doc.commit();+ const initialized = await mf.dispatchFetch(`http://localhost:8787/document/${documentId}/initialize`, {+ method: "POST",+ headers: {+ "Content-Type": "application/octet-stream",+ Authorization: `Bearer ${getTokenForDocument(documentId, "importer", "owner")}`,+ },+ body: InitializeFromSnapshotRequest.encode({ snapshot: doc.export({ mode: "snapshot" }) }),+ });+ expect(initialized.status).toBe(200);++ const from = doc.version();+ const aiPeer = 0xa1a1_a100_0000_0002n;+ doc.setPeerId(aiPeer);+ doc.getText("content").insert(0, "agent ");+ doc.commit();+ const agentToken = jwt.sign(+ {+ user_id: "macro|[email protected]",+ actor: "bot|agent-1",+ document_id: documentId,+ access_level: "edit",+ exp: Math.floor(Date.now() / 1000) + 60,+ },+ "local",+ );+ const updated = await mf.dispatchFetch(`http://localhost:8787/document/${documentId}/update`, {+ method: "POST",+ headers: { Authorization: `Bearer ${agentToken}`, "Content-Type": "application/json" },+ body: JSON.stringify({+ expectedRevision: Buffer.from(from.encode()).toString("base64"),+ update: Buffer.from(doc.export({ mode: "update", from })).toString("base64"),+ }),+ });+ expect(updated.status).toBe(200);++ const agentPeer = { peer_id: aiPeer.toString(), user_id: "macro|[email protected]", actor: "bot|agent-1" };+ const metadata = (await (await authorized("metadata")).json()) as { peers: unknown[] };+ expect(metadata.peers).toContainEqual(agentPeer);++ expect((await copyDocument(mf, documentId, "attribution-copy")).status).toBe(200);+ const copied = await mf.dispatchFetch("http://localhost:8787/document/attribution-copy/metadata", {+ headers: { Authorization: `Bearer ${getTokenForDocument("attribution-copy", "reader", "view")}` },+ });+ expect(((await copied.json()) as { peers: unknown[] }).peers).toContainEqual(agentPeer);+});++test("re-registering a peer someone else owns keeps its original author", async () => {+ const peer = 0xa1a1_a100_0000_0003n;+ await editAs({ user_id: "macro|[email protected]", actor: "bot|agent-1" }, peer, "agent ");+ await editAs({ user_id: "macro|[email protected]" }, peer, "other ");++ const metadata = (await (await authorized("metadata")).json()) as { peers: unknown[] };+ expect(metadata.peers).toContainEqual({+ peer_id: peer.toString(),+ user_id: "macro|[email protected]",+ actor: "bot|agent-1",+ });+});