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(agents): label agent edit cursors with the agent's own name (#9329)
Wolf Mermelsteina87dcedd7235
diff --git a/Cargo.lock b/Cargo.lockindex 7f4fcac614..2d703aebb5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1186,6 +1186,7 @@ dependencies = ["macro_authorization","macro_aws_config","macro_db_client",+ "macro_db_migrator","macro_entrypoint","macro_env","macro_env_var",diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex 6fd57785b6..c5b0711f69 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -136,6 +136,7 @@ macro_service_urls = { path = "../macro_service_urls" }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }calendar_scheduling = { path = "../calendar_scheduling", features = ["inbound"] }macro_authorization = { path = "../macro_authorization", features = ["axum"] }model_user = { path = "../model_user" }diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex d684c219c6..14b6040862 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -81,6 +81,7 @@ use teams::{inbound::toolset::TeamToolContext, outbound::team_repo::TeamRepositouse tokio_util::task::TaskTracker;mod activity_metadata;+mod agent_name;mod channel_media;#[cfg(any(test, feature = "test-support"))]pub use channel_media::build_channel_media_upload_tool_context_test;@@ -2193,12 +2194,20 @@ impl ToolServiceContext {}/// Run the tools for `caller`, as the public MCP authenticated it: an- /// agent writes as itself; an MCP client writes as the Macro bot with its- /// name on the post, shown as the author ("Claude Code · Agent"); a pasted- /// API key writes as the Macro bot.- pub fn for_caller(self, caller: &ai_toolset::ToolCaller) -> Self {+ /// agent writes as itself, under its own name; an MCP client writes as the+ /// Macro bot with its name on the post, shown as the author ("Claude Code ·+ /// Agent"); a pasted API key writes as the Macro bot.+ pub async fn for_caller(self, caller: &ai_toolset::ToolCaller) -> Self {match caller {- ai_toolset::ToolCaller::Agent(agent) => self.with_actor(*agent),+ ai_toolset::ToolCaller::Agent(agent) => {+ let name =+ agent_name::agent_name(self.bot_tool_context.service.as_ref(), *agent).await;+ let context = self.with_actor(*agent);+ match name {+ Some(name) => context.with_actor_name(&name),+ None => context,+ }+ }ai_toolset::ToolCaller::McpClient { .. } | ai_toolset::ToolCaller::ApiKey => {match caller.via() {Some(client) => self.with_via(client),diff --git a/crates/ai_tools/src/tool_context/agent_name.rs b/crates/ai_tools/src/tool_context/agent_name.rsnew file mode 100644index 0000000000..229eaf2b5f--- /dev/null+++ b/crates/ai_tools/src/tool_context/agent_name.rs@@ -0,0 +1,32 @@+//! The name an agent's writes are presented under while they happen.+use bot_id::BotId;+use bots::domain::ports::BotService;++#[cfg(test)]+mod test;++/// The display name of `agent`, a user- or team-owned bot a credential was+/// signed for, so the cursor the editing worker draws reads that agent's name.+/// `None` for a first-party bot, whose constant name the tools already know,+/// and for a bot that no longer exists or could not be read.+#[tracing::instrument(+ name = "mcp.agent_name",+ skip_all,+ fields(bot_id = %agent.as_uuid(), found = tracing::field::Empty)+)]+pub(crate) async fn agent_name<Bots: BotService>(bots: &Bots, agent: BotId) -> Option<String> {+ if bot_id::system_bot(agent).is_some() {+ return None;+ }+ match bots.get_self(agent).await {+ Ok(bot) => {+ tracing::Span::current().record("found", true);+ Some(bot.name)+ }+ Err(error) => {+ tracing::Span::current().record("found", false);+ tracing::warn!(?error, "could not read the calling agent's name");+ None+ }+ }+}diff --git a/crates/ai_tools/src/tool_context/agent_name/test.rs b/crates/ai_tools/src/tool_context/agent_name/test.rsnew file mode 100644index 0000000000..a00b502f7d--- /dev/null+++ b/crates/ai_tools/src/tool_context/agent_name/test.rs@@ -0,0 +1,70 @@+use super::*;+use bots::{+ domain::{models::CreateBotRequest, service::BotServiceImpl},+ outbound::pg_bots_repo::PgBotsRepo,+};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_event_broker::NoopMacroEventBroker;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn agents_are_named_by_their_own_bot_rows(pool: PgPool) -> anyhow::Result<()> {+ let macro_user_id = uuid::Uuid::now_v7();+ sqlx::query(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, '[email protected]', '[email protected]', 'stripe_owner')",+ )+ .bind(macro_user_id)+ .execute(&pool)+ .await?;+ sqlx::query(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ('macro|[email protected]', '[email protected]', $1)"#,+ )+ .bind(macro_user_id)+ .execute(&pool)+ .await?;+ let owner = MacroUserIdStr::try_from("macro|[email protected]".to_owned())?;++ let bots = BotServiceImpl::new(PgBotsRepo::new(pool.clone()), NoopMacroEventBroker);+ let grunk = bots+ .create_bot(+ owner.clone(),+ CreateBotRequest {+ team_id: None,+ name: "Grunk".to_owned(),+ handle: "grunk".to_owned(),+ description: None,+ avatar_url: None,+ has_agent: Some(true),+ },+ )+ .await?;+ let cursor = bots+ .create_bot(+ owner,+ CreateBotRequest {+ team_id: None,+ name: "Cursor".to_owned(),+ handle: "my-cursor".to_owned(),+ description: None,+ avatar_url: None,+ has_agent: Some(true),+ },+ )+ .await?;++ // Two agents editing the same document are told apart by name.+ assert_eq!(agent_name(&bots, grunk.id).await, Some("Grunk".to_owned()));+ assert_eq!(+ agent_name(&bots, cursor.id).await,+ Some("Cursor".to_owned())+ );+ // First-party bots keep their constant names; no lookup.+ assert_eq!(agent_name(&bots, bot_id::MACRO_AI_BOT_ID).await, None);+ // A deleted or unknown agent has no name to present.+ assert_eq!(+ agent_name(&bots, BotId::new_from_uuid(uuid::Uuid::now_v7())).await,+ None+ );+ Ok(())+}diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex 3fa271e4f1..90c06969bd 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -152,12 +152,13 @@ listener failure shuts down the process so ECS can replace the task.- Public MCP tool calls run for the `ToolCaller` the bearer middleware(`mcp_auth_proxy`) attached, and a call without one is refused: `Agent` (aMacro API token's signed `agent_id`, which egress mints from the session's- `agent_session.bot_id`) writes as that agent; `McpClient` (OAuth) writes as- the Macro bot labelled with the client's name (shown as the author); `ApiKey`- writes as the Macro bot. Public `ExecuteCode` builds its context per call from- the caller and signs the same attribution into its SDK token: the agent, or- the Macro bot plus the client name as `agent_via`. Never read a bot id or- client name from the request itself.+ `agent_session.bot_id`) writes as that agent, under the bot's own name (read+ per call, so its document edits label their live cursors with it);+ `McpClient` (OAuth) writes as the Macro bot labelled with the client's name+ (shown as the author); `ApiKey` writes as the Macro bot. Public `ExecuteCode`+ builds its context per call from the caller and signs the same attribution+ into its SDK token: the agent, or the Macro bot plus the client name as+ `agent_via`. Never read a bot id or client name from the request itself.- The public MCP server is stateless, so tool calls carry no `clientInfo`; theclient is identified per call by its `User-Agent` / `x-anthropic-client`headers and per session by `$mcp_initialize`.diff --git a/services/agent_harness_service/src/public_mcp/tool_service.rs b/services/agent_harness_service/src/public_mcp/tool_service.rsindex 6028dbd2cb..de8b6a1a66 100644--- a/services/agent_harness_service/src/public_mcp/tool_service.rs+++ b/services/agent_harness_service/src/public_mcp/tool_service.rs@@ -46,17 +46,17 @@ fn definitions<Context>(toolset: &AsyncToolCollection<Context>) -> impl Iterator/// A tool context that runs its tools for the caller the request authenticated.pub trait CalledBy {/// Run mutating tools for `caller`, still on the authenticated user's behalf.- fn called_by(self, caller: &ToolCaller) -> Self;+ fn called_by(self, caller: &ToolCaller) -> impl Future<Output = Self> + Send;}impl CalledBy for ai_tools::ToolServiceContext {- fn called_by(self, caller: &ToolCaller) -> Self {- self.for_caller(caller)+ async fn called_by(self, caller: &ToolCaller) -> Self {+ self.for_caller(caller).await}}impl CalledBy for () {- fn called_by(self, _caller: &ToolCaller) -> Self {}+ async fn called_by(self, _caller: &ToolCaller) -> Self {}}/// Code mode for flagged users: `tools/list` is the SDK entrypoints only.@@ -356,7 +356,7 @@ wherelet result = match self.toolset.try_tool_call(- self.context.clone().called_by(&caller),+ self.context.clone().called_by(&caller).await,request_context,&request.name,&arguments,diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.mdindex b3a81e5db3..cf21f33b82 100644--- a/services/ai-editing-worker/AI_EDITING.md+++ b/services/ai-editing-worker/AI_EDITING.md@@ -138,8 +138,8 @@ ephemeral awareness channel, so the website renders a remote cursor walkingthrough the text. The cursor's label is the editor `POST /edit` names(`editor: { name }`): the agent or persona that asked for the edit, so a`Macro` or `Grunk` session's edits read `Macro (AI)` / `Grunk (AI)` on every-cursor they draw (`PeerPool.forEditor`). A request that names nobody falls back-to the pool of distinct names (`Sam (AI)`, `Alex (AI)`). Every label ends in+cursor they draw (`PeerPool.forEditor`). A request that names nobody labels its+cursors `Macro (AI)` (`DEFAULT_EDITOR_NAME`), never a person's name. Every label ends in`(AI)`; the website keys off that suffix to keep AI name tags pinned. Eachwriter 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 adiff --git a/services/ai-editing-worker/scripts/typer.ts b/services/ai-editing-worker/scripts/typer.tsindex 0faa22932e..54f0f4830c 100644--- a/services/ai-editing-worker/scripts/typer.ts+++ b/services/ai-editing-worker/scripts/typer.ts@@ -1,116 +1,143 @@// This is a small helper that uses the helpers of the ai worker to type random// gibberish into a document-import "../src/globals";-import yargs from "yargs";-import { hideBin } from "yargs/helpers";-import { $getRoot } from "lexical";-import type { SerializedEditorState } from "lexical";-import { $getId, $updateAllNodeIds } from "@macro-inc/lexical-core/plugins/nodeIdPlugin";+import '../src/globals';+import type { InferType } from '@loro-mirror/core';+import { SyncEngine } from '@macro-inc/collaboration/collab/engine';+import { LoroManager } from '@macro-inc/collaboration/collab/manager';+import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';import {- createEditingSession,- loadSnapshot,- toSnapshot,-} from "../src/ai-editing/ai-toolkit";-import { Doc } from "../src/ai-editing/doc/doc";-import { nextAiPeerId } from "../src/ai-editing/awareness/ai-peer";+ InMemoryWALStore,+ WALSyncer,+} from '@macro-inc/collaboration/collab/wal';import {- AI_NAMES,- COLORS,- realAwarenessSource,-} from "../src/ai-editing/awareness/awareness-source";-import { DocumentEditor } from "../src/ai-editing/editor/document-editor";-import { type CodeRunner, runEditorCode } from "../src/ai-editing/runtime";-import { MARKDOWN_LORO_SCHEMA, type MarkdownLoroSchemaType } from "@macro-inc/lexical-core/markdown-loro-schema";-import type { InferType } from "@loro-mirror/core";-import { createWorkerSyncSource, createWorkerAwareness } from "../src/sources";-import { LoroManager } from "@macro-inc/collaboration/collab/manager";-import { SyncEngine } from "@macro-inc/collaboration/collab/engine";-import { InMemoryWALStore, WALSyncer } from "@macro-inc/collaboration/collab/wal";-import type { RawUpdate } from "@macro-inc/collaboration/collab/shared";+ MARKDOWN_LORO_SCHEMA,+ type MarkdownLoroSchemaType,+} from '@macro-inc/lexical-core/markdown-loro-schema';+import {+ $getId,+ $updateAllNodeIds,+} from '@macro-inc/lexical-core/plugins/nodeIdPlugin';+import type { SerializedEditorState } from 'lexical';+import { $getRoot } from 'lexical';+import yargs from 'yargs';+import { hideBin } from 'yargs/helpers';+import {+ createEditingSession,+ loadSnapshot,+ toSnapshot,+} from '../src/ai-editing/ai-toolkit';+import { nextAiPeerId } from '../src/ai-editing/awareness/ai-peer';+import {+ aiLabel,+ COLORS,+ DEFAULT_EDITOR_NAME,+ realAwarenessSource,+} from '../src/ai-editing/awareness/awareness-source';+import { Doc } from '../src/ai-editing/doc/doc';+import { DocumentEditor } from '../src/ai-editing/editor/document-editor';+import { type CodeRunner, runEditorCode } from '../src/ai-editing/runtime';+import { createWorkerAwareness, createWorkerSyncSource } from '../src/sources';-const argv = await yargs(hideBin(process.argv)).usage("$0 <wss-url>").help().parse();+const argv = await yargs(hideBin(process.argv))+ .usage('$0 <wss-url>')+ .help()+ .parse();const wssUrl = argv._[0] as string | undefined;-if (!wssUrl) { yargs().showHelp(); process.exit(1); }+if (!wssUrl) {+ yargs().showHelp();+ process.exit(1);+}-const source = createWorkerSyncSource(wssUrl, "", undefined);+const source = createWorkerSyncSource(wssUrl, '', undefined);const initial = await source.doInitialSync();-if (initial.isErr()) throw new Error(`initial sync failed: ${initial.error.type}`);+if (initial.isErr())+ throw new Error(`initial sync failed: ${initial.error.type}`);const { snapshot } = initial.value;-const manager = new LoroManager(MARKDOWN_LORO_SCHEMA, { documentId: "" });+const manager = new LoroManager(MARKDOWN_LORO_SCHEMA, { documentId: '' });let engine: SyncEngine<typeof MARKDOWN_LORO_SCHEMA, unknown> | undefined;manager.onStateChange((u) => queueMicrotask(() => engine?.onStateUpdate(u)));const initResult = await manager.initializeFromSnapshot(snapshot);-if (initResult.isErr()) throw new Error(`failed to initialize: ${initResult.error[0]?.message}`);+if (initResult.isErr())+ throw new Error(`failed to initialize: ${initResult.error[0]?.message}`);const session = createEditingSession();-loadSnapshot(session, manager.mirror!.getState() as unknown as SerializedEditorState);+loadSnapshot(+ session,+ manager.mirror!.getState() as unknown as SerializedEditorState+);const workerAwareness = createWorkerAwareness(manager.peerIdStr);-const wal = new WALSyncer<RawUpdate>(new InMemoryWALStore<RawUpdate>(), (updates) => source.pushUpdate(updates));+const wal = new WALSyncer<RawUpdate>(+ new InMemoryWALStore<RawUpdate>(),+ (updates) => source.pushUpdate(updates)+);engine = new SyncEngine({- loroManager: manager,- awareness: workerAwareness,- syncs: { wal, live: source },- bindings: { onRemoteState: () => {} },+ loroManager: manager,+ awareness: workerAwareness,+ syncs: { wal, live: source },+ bindings: { onRemoteState: () => {} },});engine.start();let chain: Promise<void> = Promise.resolve();const propagate = () => {- chain = chain.then(async () => {- const newPeer = nextAiPeerId();- manager.doc.commit();- manager.doc.setPeerId(newPeer);- source.registerPeerId(newPeer);- session.editor.update(() => $updateAllNodeIds(session.ids), { discrete: true });- await engine!.syncStateToLoro(toSnapshot(session) as unknown as InferType<MarkdownLoroSchemaType>);- });+ chain = chain.then(async () => {+ const newPeer = nextAiPeerId();+ manager.doc.commit();+ manager.doc.setPeerId(newPeer);+ source.registerPeerId(newPeer);+ session.editor.update(() => $updateAllNodeIds(session.ids), {+ discrete: true,+ });+ await engine!.syncStateToLoro(+ toSnapshot(session) as unknown as InferType<MarkdownLoroSchemaType>+ );+ });};const awareness = realAwarenessSource({- mirror: manager.mirror!,- doc: manager.doc,- send: (bytes) => source.pushAwareness(bytes),- name: AI_NAMES[0]!,- color: COLORS[0]!,+ mirror: manager.mirror!,+ doc: manager.doc,+ send: (bytes) => source.pushAwareness(bytes),+ name: aiLabel(DEFAULT_EDITOR_NAME),+ color: COLORS[0]!,});-const firstId = session.editor.getEditorState().read(() =>- $getId($getRoot().getFirstChildOrThrow()),-);-if (!firstId) throw new Error("document has no nodes");+const firstId = session.editor+ .getEditorState()+ .read(() => $getId($getRoot().getFirstChildOrThrow()));+if (!firstId) throw new Error('document has no nodes');const paragraphs = [- "The quick brown fox jumps over the lazy dog, and then, having completed that particular feat of athletic prowess, paused to reflect on the existential implications of being a fox in a world that seemingly only exists to test the typographic completeness of font families and keyboard layouts.",- "It was a dark and stormy night, or at least that is what the weather forecast had suggested earlier in the week, though by the time the actual evening arrived the clouds had largely dispersed, leaving behind only a faint drizzle and the lingering sense that meteorology is, at its core, an exercise in optimistic uncertainty.",- "The history of human civilization can be understood, if one squints sufficiently and ignores a great many inconvenient counterexamples, as a long and winding journey from sitting in caves wondering what that rustling noise was, all the way to sitting in offices wondering what that notification sound was, which is to say the fundamental anxieties have remained remarkably consistent.",+ 'The quick brown fox jumps over the lazy dog, and then, having completed that particular feat of athletic prowess, paused to reflect on the existential implications of being a fox in a world that seemingly only exists to test the typographic completeness of font families and keyboard layouts.',+ 'It was a dark and stormy night, or at least that is what the weather forecast had suggested earlier in the week, though by the time the actual evening arrived the clouds had largely dispersed, leaving behind only a faint drizzle and the lingering sense that meteorology is, at its core, an exercise in optimistic uncertainty.',+ 'The history of human civilization can be understood, if one squints sufficiently and ignores a great many inconvenient counterexamples, as a long and winding journey from sitting in caves wondering what that rustling noise was, all the way to sitting in offices wondering what that notification sound was, which is to say the fundamental anxieties have remained remarkably consistent.',];const inserts = paragraphs- .map(- (text, i) =>- i === 0- ? `const ref0 = editor.insertParagraphAfter('${firstId}', ${JSON.stringify(text)});`- : `const ref${i} = editor.insertParagraphAfter(ref${i - 1}, ${JSON.stringify(text)});`,- )- .join("\n");+ .map((text, i) =>+ i === 0+ ? `const ref0 = editor.insertParagraphAfter('${firstId}', ${JSON.stringify(text)});`+ : `const ref${i} = editor.insertParagraphAfter(ref${i - 1}, ${JSON.stringify(text)});`+ )+ .join('\n');const runner: CodeRunner = (validIds, code) => {- const refs = Array.from({ length: 128 }, (_, i) => `ref-${i + 1}`);- const editor = new DocumentEditor({ validIds, refs });- new Function("editor", code)(editor);- return editor.drain();+ const refs = Array.from({ length: 128 }, (_, i) => `ref-${i + 1}`);+ const editor = new DocumentEditor({ validIds, refs });+ new Function('editor', code)(editor);+ return editor.drain();};await runEditorCode({- session,- doc: new Doc(session, propagate),- code: inserts,- awarenessSource: awareness,- runner,+ session,+ doc: new Doc(session, propagate),+ code: inserts,+ awarenessSource: awareness,+ runner,});await chain;diff --git a/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.test.ts b/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.test.tsindex 06c4d54200..8f46a3fde8 100644--- a/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.test.ts+++ b/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.test.ts@@ -1,8 +1,8 @@import { EphemeralStore } from 'loro-crdt';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {- AI_NAMES,aiLabel,+ DEFAULT_EDITOR_NAME,realAwarenessSource,resolveTextOwner,} from './awareness-source';@@ -23,8 +23,8 @@ describe('aiLabel', () => {expect(label).toBe(`${'x'.repeat(64)} (AI)`);});- it('is what the pooled names are built with', () => {- for (const name of AI_NAMES) expect(name.endsWith('(AI)')).toBe(true);+ it('labels an edit that names no editor as Macro', () => {+ expect(aiLabel(DEFAULT_EDITOR_NAME)).toBe('Macro (AI)');});});diff --git a/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.ts b/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.tsindex 5efde30364..5fae94450c 100644--- a/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.ts+++ b/services/ai-editing-worker/src/ai-editing/awareness/awareness-source.ts@@ -35,22 +35,11 @@ export function aiLabel(name: string): string {return shown.endsWith(AI_NAME_SUFFIX) ? shown : `${shown} ${AI_NAME_SUFFIX}`;}-/** Labels writers draw when the caller names no editor. */-export const AI_NAMES = [- 'Wolf',- 'Teo',- 'Julia',- 'Seamus',- 'Evan',- 'Gab',- 'Austin',- 'Peter',- 'Sean',- 'Eric',- 'Jacob',- 'Aiden',- 'Hutch',-].map(aiLabel);+/**+ * The editor a request that names nobody runs as: the Macro agent, the same+ * default the canvas path and the web client use. Never a person's name.+ */+export const DEFAULT_EDITOR_NAME = 'Macro';/** Palette names must resolve to `--color-<name>` (see collaboration/color.ts). */export const COLORS = ['cyan', 'red', 'yellow', 'green', 'violet', 'pink'];diff --git a/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.test.ts b/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.test.tsindex d4a939ad45..e77bea3ab2 100644--- a/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.test.ts+++ b/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.test.ts@@ -1,48 +1,50 @@import { describe, expect, it } from 'vitest';import { PeerPool } from './peer-pool';-const names = ['A', 'B', 'C'];const colors = ['red', 'green'];describe('PeerPool', () => {- it('borrowing N peers yields N distinct names', async () => {- const pool = new PeerPool({ names, colors });+ it('labels every concurrent writer with the editor', async () => {+ const pool = PeerPool.forEditor('Macro', { colors });const peers = await Promise.all([pool.borrow(),pool.borrow(),pool.borrow(),]);- expect(new Set(peers.map((p) => p.name)).size).toBe(3);- expect(peers.map((p) => p.name).sort()).toEqual(['A', 'B', 'C']);+ expect(peers.map((p) => p.name)).toEqual([+ 'Macro (AI)',+ 'Macro (AI)',+ 'Macro (AI)',+ ]);expect(pool.outstanding).toBe(3);});- it('releasing then borrowing reuses a freed name', async () => {- const pool = new PeerPool({ names, colors });+ it('labels two editors distinctly', async () => {+ const grunk = await PeerPool.forEditor('Grunk', { colors }).borrow();+ const cursor = await PeerPool.forEditor('Cursor', { colors }).borrow();+ expect(grunk.name).toBe('Grunk (AI)');+ expect(cursor.name).toBe('Cursor (AI)');+ });++ it('hands out distinct peer ids and cycles colors', async () => {+ const pool = PeerPool.forEditor('Grunk', { colors });const a = await pool.borrow();const b = await pool.borrow();- pool.release(a);- const c = await pool.borrow();- expect(c.name).toBe(a.name);- expect(c.name).not.toBe(b.name);- expect(pool.outstanding).toBe(2);+ expect(a.peerId).not.toBe(b.peerId);+ expect(a.color).not.toBe(b.color);});- it('grows with still-unique names when the base list is exhausted', async () => {- const pool = new PeerPool({ names, colors, max: 5 });- const peers = await Promise.all([- pool.borrow(),- pool.borrow(),- pool.borrow(),- pool.borrow(),- pool.borrow(),- ]);- expect(new Set(peers.map((p) => p.name)).size).toBe(5);- expect(pool.outstanding).toBe(5);+ it('reuses a released writer', async () => {+ const pool = PeerPool.forEditor('Cursor', { colors, max: 1 });+ const a = await pool.borrow();+ pool.release(a);+ const b = await pool.borrow();+ expect(b).toBe(a);+ expect(b.name).toBe('Cursor (AI)');});it('release of an unknown peer is a no-op', async () => {- const pool = new PeerPool({ names, colors });+ const pool = PeerPool.forEditor('Macro', { colors });const a = await pool.borrow();pool.release({ name: 'X', color: 'blue', peerId: 0n }); // never borrowedpool.release(a);@@ -50,100 +52,21 @@ describe('PeerPool', () => {expect(pool.outstanding).toBe(0);});- it('outstanding tracks borrows and releases', async () => {- const pool = new PeerPool({ names, colors });- expect(pool.outstanding).toBe(0);- const a = await pool.borrow();- const b = await pool.borrow();- expect(pool.outstanding).toBe(2);- pool.release(b);- expect(pool.outstanding).toBe(1);- pool.release(a);- expect(pool.outstanding).toBe(0);- });-- it('prefers distinct colors while the palette lasts', async () => {- const pool = new PeerPool({ names, colors });- const a = await pool.borrow();- const b = await pool.borrow();- expect(a.color).not.toBe(b.color);- });-- it('caps concurrent borrows at max, releasing a slot for the next waiter', async () => {- const pool = new PeerPool({ names, colors, max: 2 });- const a = await pool.borrow();- const b = await pool.borrow();- expect(pool.outstanding).toBe(2);- expect(b.name).not.toBe(a.name);+ it('blocks borrows past max until a slot frees', async () => {+ const pool = PeerPool.forEditor('Macro', { colors, max: 2 });+ const [a] = await Promise.all([pool.borrow(), pool.borrow()]);- // A third borrow must wait — the pool is full.let third: { name: string } | undefined;const pending = pool.borrow().then((p) => {third = p;return p;});- await Promise.resolve(); // give the queue a tick; still blocked- expect(third).toBeUndefined();+ await Promise.resolve();+ expect(third).toBeUndefined(); // never acquires while fullexpect(pool.outstanding).toBe(2);- // Releasing one opens the slot; the waiter resolves and reuses the name.- pool.release(a);- const c = await pending;- expect(third).toBe(c);- expect(c.name).toBe(a.name);+ pool.release(a!);+ expect(await pending).toBe(a);expect(pool.outstanding).toBe(2);});-- it('blocks borrows past max until a slot frees, reusing the freed name', async () => {- const pool = new PeerPool({ names: ['A', 'B', 'C', 'D'], colors, max: 3 });- const three = await Promise.all([- pool.borrow(),- pool.borrow(),- pool.borrow(),- ]);- expect(pool.outstanding).toBe(3);-- const fourth = pool.borrow(); // blocks: no slot is free- await Promise.resolve();- expect(pool.outstanding).toBe(3); // never acquires while full-- pool.release(three[0]!);- const p = await fourth; // slot opened → resolves- expect(p.name).toBe(three[0]!.name);- expect(pool.outstanding).toBe(3);- });-});--describe('PeerPool.forEditor', () => {- it('labels every concurrent writer with the editor, never a pooled name', async () => {- const pool = PeerPool.forEditor('Macro', { colors });- const peers = await Promise.all([- pool.borrow(),- pool.borrow(),- pool.borrow(),- ]);- expect(peers.map((p) => p.name)).toEqual([- 'Macro (AI)',- 'Macro (AI)',- 'Macro (AI)',- ]);- expect(pool.outstanding).toBe(3);- });-- it('still hands out distinct peer ids and cycles colors', async () => {- const pool = PeerPool.forEditor('Grunk', { colors });- const a = await pool.borrow();- const b = await pool.borrow();- expect(a.peerId).not.toBe(b.peerId);- expect(a.color).not.toBe(b.color);- });-- it('a released writer is reused under the same name', async () => {- const pool = PeerPool.forEditor('Cursor', { colors, max: 1 });- const a = await pool.borrow();- pool.release(a);- const b = await pool.borrow();- expect(b).toBe(a);- expect(b.name).toBe('Cursor (AI)');- });});diff --git a/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.ts b/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.tsindex f5f50eaae2..ecb1cd7d53 100644--- a/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.ts+++ b/services/ai-editing-worker/src/ai-editing/awareness/peer-pool.ts@@ -1,53 +1,39 @@import PQueue from 'p-queue';import { nextAiPeerId } from './ai-peer';-import { AI_NAMES, aiLabel, COLORS } from './awareness-source';+import { aiLabel, COLORS } from './awareness-source';export type Peer = { name: string; color: string; peerId: bigint };export type PeerPoolOptions = {- names?: string[];colors?: string[];max?: number;- /**- * Whether every outstanding peer needs its own name (default). Off, the- * pool cycles through `names` and lets writers share one: how a single- * persona edits with several cursors at once.- */- distinctNames?: boolean;};+/**+ * Hands out writer identities for one edit. Every writer is labelled with the+ * editor — the agent or persona that asked for the edit — so readers see its+ * name on each cursor; writers differ only by peer id and color.+ */export class PeerPool {- private readonly names: string[];+ private readonly name: string;private readonly colors: string[];- private readonly distinctNames: boolean;private readonly free: Peer[] = []; // released, ready to reuseprivate readonly out = new Set<Peer>();private readonly releasers = new Map<Peer, () => void>(); // peer → free its slotprivate readonly gate: PQueue;- constructor(opts?: PeerPoolOptions) {- this.names = [...(opts?.names ?? AI_NAMES)];+ private constructor(editor: string, opts?: PeerPoolOptions) {+ this.name = aiLabel(editor);this.colors = [...(opts?.colors ?? COLORS)];- this.distinctNames = opts?.distinctNames ?? true;this.gate = new PQueue({ concurrency: opts?.max ?? 6 });}- /**- * A pool whose every writer is `editor` — the agent or persona that asked for- * the edit — so readers see its name on each cursor, not a pooled one.- */- static forEditor(- editor: string,- opts?: Omit<PeerPoolOptions, 'names' | 'distinctNames'>- ): PeerPool {- return new PeerPool({- ...opts,- names: [aiLabel(editor)],- distinctNames: false,- });+ /** A pool whose every writer is labelled `editor`. */+ static forEditor(editor: string, opts?: PeerPoolOptions): PeerPool {+ return new PeerPool(editor, opts);}- /** Acquire a unique identity, waiting if `max` are already out (semaphore). */+ /** Acquire a writer identity, waiting if `max` are already out (semaphore). */public borrow(): Promise<Peer> {return new Promise<Peer>((handOut) => {// The queued task holds a concurrency slot until its promise resolves; we@@ -79,34 +65,10 @@ export class PeerPool {return this.out.size;}- /** A never-before-issued identity: next unused base name, else a suffixed one. */+ /** A never-before-issued identity: a fresh peer id and the next color. */private mint(): Peer {- const color = this.colors[this.issued() % this.colors.length] ?? '';- if (!this.distinctNames) {- const name = this.names[this.issued() % this.names.length] ?? 'AI';- return { name, color, peerId: nextAiPeerId() };- }-- const used = new Set([...this.out, ...this.free].map((p) => p.name));- const unusedBaseName = this.names.find((name) => !used.has(name));- let name = unusedBaseName;-- if (!name) {- const baseNames = this.names.length > 0 ? this.names : ['AI'];- let generation = Math.floor(this.issued() / baseNames.length) + 1;- let candidate = `${baseNames[this.issued() % baseNames.length]} ${generation}`;-- while (used.has(candidate)) {- generation += 1;- candidate = `${baseNames[this.issued() % baseNames.length]} ${generation}`;- }- name = candidate;- }-- return { name, color, peerId: nextAiPeerId() };- }-- private issued(): number {- return this.out.size + this.free.length;+ const issued = this.out.size + this.free.length;+ const color = this.colors[issued % this.colors.length] ?? '';+ return { name: this.name, color, peerId: nextAiPeerId() };}}diff --git a/services/ai-editing-worker/src/editing-workspace.ts b/services/ai-editing-worker/src/editing-workspace.tsindex ebb3b12e7c..be1eb598e2 100644--- a/services/ai-editing-worker/src/editing-workspace.ts+++ b/services/ai-editing-worker/src/editing-workspace.ts@@ -18,6 +18,7 @@ import {} from './ai-editing/ai-toolkit';import {type AwarenessSource,+ DEFAULT_EDITOR_NAME,nextAiPeerId,type Peer,PeerPool,@@ -44,7 +45,7 @@ export class EditingWorkspace {wal: WALSyncer<RawUpdate>,opts: EditingWorkspaceOptions = {}) {- this.pool = opts.pool ?? new PeerPool();+ this.pool = opts.pool ?? PeerPool.forEditor(DEFAULT_EDITOR_NAME);// Seed the editing surface from the merged state.this.session = createEditingSession();loadSnapshot(diff --git a/services/ai-editing-worker/src/endpoints/edit.ts b/services/ai-editing-worker/src/endpoints/edit.tsindex 79c38152d2..5334ae55ab 100644--- a/services/ai-editing-worker/src/endpoints/edit.ts+++ b/services/ai-editing-worker/src/endpoints/edit.ts@@ -85,8 +85,8 @@ const EditBody = zmode: z.enum(['supervised', 'fast']).default('supervised'),/*** The agent or persona the edit runs as. Its name labels every cursor the- * edit draws, so readers see who is editing; omitted, cursors draw pooled- * names.+ * edit draws, so readers see who is editing; omitted, cursors read+ * `Macro (AI)`.*/editor: z.object({ name: z.string().trim().min(1) }).optional(),typingAnimations: z.boolean().optional(),diff --git a/services/ai-editing-worker/src/run-edit.ts b/services/ai-editing-worker/src/run-edit.tsindex d072fd3170..64534baa37 100644--- a/services/ai-editing-worker/src/run-edit.ts+++ b/services/ai-editing-worker/src/run-edit.ts@@ -74,7 +74,7 @@ export type RunEditArgs = {prompt: string;models: ResolvedModels;mode?: EditMode;- /** Names the cursors; absent, writers draw pooled names instead. */+ /** Names the cursors; absent, they read `Macro (AI)`. */editor?: Editor;/** Snippet runner — QuickJS sandbox in prod, `new Function` in local dev. */runner?: CodeRunner;