Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(ai): AI document edits are presented under the initiating agent's name (#6965)

teodd5d58e2b01f
diff --git a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
index 870ecbc802..0fa1f18273 100644
--- a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
+++ b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
@@ -1,6 +1,7 @@
import type { DocumentOp } from '@ai-ops/editor';
import { resumeDocumentSpan } from '@block-md/observability';
import { toast } from '@core/component/Toast/Toast';
+import { MACRO_AGENT_NAME } from '@core/constant/macroAgent';
import { Telemetry } from '@macro-inc/observability';
import { getDocumentPermissionToken } from '@service-storage/client';
import { createSignal } from 'solid-js';
@@ -133,6 +134,9 @@ export async function requestAiEdit(args: {
prompt: args.prompt,
models: MODELS,
mode: args.mode,
+ // Inline edits are Macro's own; its name labels the cursors readers
+ // watch, the same way an agent's edits carry the agent's name.
+ editor: { name: MACRO_AGENT_NAME },
interpret: false,
propagate: args.onOps === undefined ? undefined : false,
}),
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index b3d04c8a9d..39ca2aca3e 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -20,6 +20,7 @@ ai_usage = { path = "../ai_usage" }
bytes = { workspace = true }
async-trait = { workspace = true }
axum = { workspace = true }
+bot_id = { path = "../bot_id" }
chat = { path = "../chat", default-features = false }
dashmap = { workspace = true }
futures = { workspace = true }
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index 18b5e19a17..eb9325e79b 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -5,6 +5,7 @@ use std::sync::Arc;
use agent::types::ChatMessage;
use agent::{AgentError, StreamPart};
use ai_tools::user_tool_review::UserToolReviewer;
+use bot_id::BotId;
use mcp_toolset::RemoteMcpToolSet;
use model_owner::Owner;
use tokio::sync::mpsc;
@@ -12,9 +13,17 @@ use tokio_util::sync::CancellationToken;
use super::user_input::SharedUserInputRequester;
-/// The agent's display name and `@` handle, for the turn's system prompt.
+/// Who the agent is: the bot a session belongs to, by id and by name.
+///
+/// The name and handle go into the turn's system prompt so the model knows
+/// who it is; the id and name also make the turn's tools act as that bot, so
+/// what the agent writes is attributed to it - and presented under its name
+/// wherever a reader sees the write happen, such as the cursor the editing
+/// worker draws - rather than to Macro.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentIdentity {
+ /// The bot the session belongs to.
+ pub bot: BotId,
/// Display name, e.g. `Grunk`.
pub name: String,
/// Stable `@` handle without a leading `@`, e.g. `grunk`.
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index 4751f27908..6f561ac9a2 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -121,6 +121,7 @@ fn facts_with_instructions(id: AgentSessionId, instructions: &str) -> SessionFac
fn facts_with_identity(id: AgentSessionId, name: &str, handle: &str) -> SessionFacts {
SessionFacts {
identity: Some(AgentIdentity {
+ bot: BotId::TEST_A,
name: name.to_owned(),
handle: handle.to_owned(),
}),
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rs
index 8398a6e618..038a19c748 100644
--- a/crates/agent_inmem/src/outbound/rig_engine/test.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs
@@ -43,6 +43,7 @@ fn instructions_are_a_delimited_section_after_the_standing_prompt() {
#[test]
fn identity_precedes_the_standing_prompt_and_does_not_need_instructions() {
let identity = AgentIdentity {
+ bot: bot_id::BotId::TEST_A,
name: "Grunk".to_owned(),
handle: "grunk".to_owned(),
};
diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
index a04deaca8f..9c6b65f39f 100644
--- a/crates/agent_inmem/src/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -171,6 +171,13 @@ async fn drive_turn(
// Carry the feature on the context so tool-spawned subagents attribute to it.
let mut tool_context = base_context.clone();
tool_context.usage_context = usage_ctx.clone();
+ // The tools act as the session's bot, delegated for the owner: its writes
+ // are attributed to it and presented under its name, not Macro's.
+ if let Some(identity) = &identity {
+ tool_context = tool_context
+ .with_actor(identity.bot)
+ .with_actor_name(&identity.name);
+ }
let tool_context = InMemToolContext {
base: tool_context,
ask_user: AskUserContext {
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 90a8ae89d2..a63288279e 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1470,6 +1470,16 @@ impl ToolServiceContext {
self.channel_tool_context = self.channel_tool_context.with_actor(actor);
self
}
+
+ /// Name the actor set with [`Self::with_actor`], so what the tools write
+ /// is presented under the agent's own name where a reader sees it live -
+ /// the cursor the editing worker draws while it types. First-party bots
+ /// present under their constant names without this; a user- or
+ /// team-owned bot has no name the tools can find on their own.
+ pub fn with_actor_name(mut self, name: &str) -> Self {
+ self.document_tool_context = self.document_tool_context.with_actor_name(name);
+ self
+ }
}
impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
diff --git a/crates/documents/src/domain/ports/editing.rs b/crates/documents/src/domain/ports/editing.rs
index 2f44166f6d..e0fe9dfb16 100644
--- a/crates/documents/src/domain/ports/editing.rs
+++ b/crates/documents/src/domain/ports/editing.rs
@@ -25,6 +25,25 @@ pub struct EditUsage {
pub output_tokens: u32,
}
+/// The name readers see on an edit as it happens: the agent or persona the
+/// edit runs as, labelling every cursor the worker draws. Never blank - a
+/// blank name is no name, and the worker then chooses its own.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EditorName(String);
+
+impl EditorName {
+ /// A trimmed, non-blank name; `None` when `name` is blank.
+ pub fn new(name: &str) -> Option<Self> {
+ let name = name.trim();
+ (!name.is_empty()).then(|| Self(name.to_owned()))
+ }
+
+ /// The name as readers see it.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
/// Which pipeline the editing worker runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditMode {
@@ -84,12 +103,17 @@ pub trait EditingWorkerService: Send + Sync + 'static {
) -> impl Future<Output = anyhow::Result<()>> + Send;
/// Apply AI-driven edits to `document_id` using a pre-minted `document_token`.
+ ///
+ /// `editor` names the agent or persona the edit runs as; the worker labels
+ /// every cursor it draws with it, so readers watching the document see
+ /// who is editing. `None` leaves the worker to its own names.
fn edit(
&self,
document_id: &str,
document_token: &DocumentPermissionToken,
instructions: &str,
mode: EditMode,
+ editor: Option<EditorName>,
) -> impl Future<Output = anyhow::Result<EditResult>> + Send;
/// Delete all AI edit trace records for `document_id`. Called during
diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rs
index 8c68305269..aa48614717 100644
--- a/crates/documents/src/inbound/toolset.rs
+++ b/crates/documents/src/inbound/toolset.rs
@@ -21,7 +21,7 @@ use crate::{
domain::create::DocumentCreator,
domain::ports::DocumentService,
domain::ports::create::DocumentCreationService,
- domain::ports::editing::EditingWorkerService,
+ domain::ports::editing::{EditingWorkerService, EditorName},
domain::ports::mentions::NoOpDocumentMentionTracker,
inbound::toolset::{
comment_on_document_text::CommentOnDocumentText,
@@ -104,6 +104,13 @@ pub struct DocumentToolContext<
/// The bot these tools act as, on behalf of the requesting user. Defaults
/// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].
pub actor: BotId,
+
+ /// The display name of [`Self::actor`] as the host knows it, set with
+ /// [`Self::with_actor_name`]. First-party bots need none: their names are
+ /// compile-time constants. A user- or team-owned bot is a row the host has
+ /// already read, so it hands the name over rather than have every tool
+ /// look it up again.
+ actor_name: Option<EditorName>,
}
impl<
@@ -126,6 +133,7 @@ impl<
document_permission_jwt_secret: self.document_permission_jwt_secret.clone(),
recorder: self.recorder.clone(),
actor: self.actor,
+ actor_name: self.actor_name.clone(),
}
}
}
@@ -182,6 +190,7 @@ impl<
document_permission_jwt_secret,
recorder: Arc::new(ai_usage::NoOpUsageRecorder),
actor: bot_id::MACRO_AI_BOT_ID,
+ actor_name: None,
}
}
@@ -197,6 +206,23 @@ impl<
self
}
+ /// Set the display name of the bot these tools act as. A blank name is
+ /// no name: the actor's own is used, when it has one.
+ pub fn with_actor_name(mut self, name: &str) -> Self {
+ self.actor_name = EditorName::new(name);
+ self
+ }
+
+ /// The name readers see on what these tools write as it happens - the
+ /// label on the cursor the editing worker draws: the host-supplied name,
+ /// else the first-party bot's own. `None` for a user- or team-owned bot
+ /// the host did not name.
+ pub fn actor_editor_name(&self) -> Option<EditorName> {
+ self.actor_name
+ .clone()
+ .or_else(|| bot_id::system_bot(self.actor).and_then(|bot| EditorName::new(bot.name)))
+ }
+
/// Mint the bot's comment capability on the document on behalf of the
/// requesting user: the same comment access the web composer requires.
pub async fn require_comment_write(
diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rs
index 4c9a438d1a..76524b614a 100644
--- a/crates/documents/src/inbound/toolset/edit_document.rs
+++ b/crates/documents/src/inbound/toolset/edit_document.rs
@@ -144,6 +144,11 @@ where
internal_error: e.into(),
})?;
+ // The edit is presented as the bot this tool acts as: readers watching
+ // the document see its name on the cursor, the same name the activity
+ // feed attributes the edit to.
+ let editor = ctx.actor_editor_name();
+
// Honor user cancellation: if the request is cancelled mid-edit, drop the
// in-flight worker call (closing the HTTP connection so the worker aborts
// its own LLM work) and surface a `cancelled` tool error -- matching how
@@ -155,7 +160,7 @@ where
internal_error: anyhow::anyhow!("edit cancelled by user. document might be left in a partially edited state."),
});
}
- r = ctx.editing.edit(&self.document_id, &document_token, &self.instructions, self.mode()) => r,
+ r = ctx.editing.edit(&self.document_id, &document_token, &self.instructions, self.mode(), editor) => r,
}
.map_err(|e| ToolCallError {
description: e.to_string(),
diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rs
index dcf6ef4718..00c6035824 100644
--- a/crates/documents/src/inbound/toolset/edit_document/test.rs
+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs
@@ -11,7 +11,7 @@ use crate::domain::models::{
};
use crate::domain::permission_token::decode_permission_token;
use crate::domain::ports::editing::{
- CommentMarkPlacement, EditMode, EditResult, EditingWorkerService,
+ CommentMarkPlacement, EditMode, EditResult, EditingWorkerService, EditorName,
};
use crate::domain::response::{
CreateDocumentResponseData, DocumentResponse, GetDocumentResponseData, LocationResponseV3,
@@ -412,6 +412,8 @@ pub(in crate::inbound::toolset) struct FakeEditingWorker {
edit_calls: Arc<Mutex<Vec<String>>>,
modes: Arc<Mutex<Vec<EditMode>>>,
tokens: Arc<Mutex<Vec<DocumentPermissionToken>>>,
+ /// The editor name each edit was presented as.
+ editors: Arc<Mutex<Vec<Option<EditorName>>>>,
/// Answer every comment mark placement with this refusal.
comment_mark_refusal: Option<String>,
/// Fail every comment mark placement as a worker whose push was never acked.
@@ -503,6 +505,7 @@ impl EditingWorkerService for FakeEditingWorker {
document_token: &DocumentPermissionToken,
_instructions: &str,
mode: EditMode,
+ editor: Option<EditorName>,
) -> anyhow::Result<EditResult> {
self.edit_calls
.lock()
@@ -516,6 +519,10 @@ impl EditingWorkerService for FakeEditingWorker {
.lock()
.expect("edit tokens lock poisoned")
.push(document_token.clone());
+ self.editors
+ .lock()
+ .expect("edit editors lock poisoned")
+ .push(editor);
Ok(EditResult {
edits_applied: 1,
@@ -576,6 +583,18 @@ async fn call_edit_document_with(
file_type: &str,
actor: Option<BotId>,
fast: bool,
+) -> (ToolResult<EditDocumentResponse>, FakeEditingWorker) {
+ call_edit_document_in(file_type, fast, |context| match actor {
+ Some(actor) => context.with_actor(actor),
+ None => context,
+ })
+ .await
+}
+
+async fn call_edit_document_in(
+ file_type: &str,
+ fast: bool,
+ configure: impl FnOnce(TestToolContext) -> TestToolContext,
) -> (ToolResult<EditDocumentResponse>, FakeEditingWorker) {
let editing = FakeEditingWorker::default();
let tool = EditDocument {
@@ -585,14 +604,27 @@ async fn call_edit_document_with(
};
let mut context = tool_context(FakeDocumentService::new(file_type), editing.clone());
- if let Some(actor) = actor {
- context.0 = context.0.with_actor(actor);
- }
+ context.0 = configure(context.0);
let result = tool.call(context, request_context()).await;
(result, editing)
}
+fn presented_editor(editing: &FakeEditingWorker) -> Option<String> {
+ editing
+ .editors
+ .lock()
+ .expect("edit editors lock poisoned")
+ .first()
+ .expect("edit reached the worker")
+ .as_ref()
+ .map(|editor| editor.as_str().to_owned())
+}
+
+fn editor_name(name: &str) -> Option<String> {
+ EditorName::new(name).map(|editor| editor.as_str().to_owned())
+}
+
fn minted_token_actor(editing: &FakeEditingWorker) -> Option<String> {
let token = editing
.tokens
@@ -703,6 +735,83 @@ async fn edit_token_carries_the_context_actor() {
);
}
+/// The default actor is Macro AI, a first-party bot whose name is a constant,
+/// so the cursor readers watch is labelled `Macro` without any host wiring.
+#[tokio::test]
+async fn edit_is_presented_as_the_default_actor_by_name() {
+ let (result, editing) = call_edit_document("md").await;
+ result.expect("a markdown document should be editable");
+
+ assert_eq!(
+ presented_editor(&editing).as_deref(),
+ Some(bot_id::MACRO_AI_NAME)
+ );
+}
+
+/// A host running a named agent hands its name over with the actor, and that
+/// is the name the edit is presented under - not Macro's, not a pooled one.
+#[tokio::test]
+async fn edit_is_presented_as_the_named_actor() {
+ let (result, editing) = call_edit_document_in("md", false, |context| {
+ context.with_actor(BotId::TEST_A).with_actor_name("Grunk")
+ })
+ .await;
+ result.expect("a markdown document should be editable");
+
+ assert_eq!(presented_editor(&editing).as_deref(), Some("Grunk"));
+ assert_eq!(
+ minted_token_actor(&editing).as_deref(),
+ Some(BotId::TEST_A.into_storage_id().as_ref())
+ );
+}
+
+/// A user-owned bot the host never named has no name to present; the worker
+/// then falls back to its own labels rather than mislabelling the edit.
+#[tokio::test]
+async fn edit_by_an_unnamed_custom_bot_presents_no_editor() {
+ let (result, editing) = call_edit_document_as("md", Some(BotId::TEST_A)).await;
+ result.expect("a markdown document should be editable");
+
+ assert_eq!(presented_editor(&editing), None);
+}
+
+#[test]
+fn a_blank_actor_name_is_no_name() {
+ let context = tool_context(FakeDocumentService::new("md"), FakeEditingWorker::default());
+
+ let named = context.0.clone().with_actor_name(" ");
+ assert_eq!(
+ named.actor_editor_name(),
+ EditorName::new(bot_id::MACRO_AI_NAME)
+ );
+
+ let named = context.0.with_actor(BotId::TEST_A).with_actor_name("");
+ assert_eq!(named.actor_editor_name(), None);
+}
+
+/// The host's name wins over the first-party constant, and every first-party
+/// bot presents under its own name.
+#[test]
+fn actor_editor_name_prefers_the_host_name_then_the_first_party_name() {
+ let context = tool_context(FakeDocumentService::new("md"), FakeEditingWorker::default());
+
+ let cursor = context.0.clone().with_actor(bot_id::CURSOR_BOT_ID);
+ assert_eq!(
+ cursor.actor_editor_name(),
+ EditorName::new(bot_id::CURSOR_NAME)
+ );
+
+ let renamed = cursor.with_actor_name(" Cursor (dev) ");
+ assert_eq!(renamed.actor_editor_name(), EditorName::new("Cursor (dev)"));
+}
+
+#[test]
+fn editor_name_is_trimmed_and_never_blank() {
+ assert_eq!(editor_name(" Grunk "), Some("Grunk".to_owned()));
+ assert_eq!(editor_name(" "), None);
+ assert_eq!(editor_name(""), None);
+}
+
#[test]
fn tool_writes_are_delegated_from_the_context_actor_to_the_requesting_user() {
let user = MacroUserIdStr::try_from(TEST_USER_ID.to_string()).expect("valid user");
diff --git a/crates/documents/src/outbound/editing_worker_client.rs b/crates/documents/src/outbound/editing_worker_client.rs
index a1eb633584..330178feeb 100644
--- a/crates/documents/src/outbound/editing_worker_client.rs
+++ b/crates/documents/src/outbound/editing_worker_client.rs
@@ -1,6 +1,8 @@
//! Outbound adapter for the AI editing worker.
-use crate::domain::ports::editing::{EditMode, EditResult, EditUsage, EditingWorkerService};
+use crate::domain::ports::editing::{
+ EditMode, EditResult, EditUsage, EditingWorkerService, EditorName,
+};
use macro_sync_service_jwt::DocumentPermissionToken;
use reqwest::Client;
use std::sync::Arc;
@@ -167,8 +169,9 @@ impl EditingWorkerService for ReqwestEditingWorkerClient {
document_token: &DocumentPermissionToken,
instructions: &str,
mode: EditMode,
+ editor: Option<EditorName>,
) -> anyhow::Result<EditResult> {
- let request_body = serde_json::json!({
+ let mut request_body = serde_json::json!({
"documentToken": document_token.as_str(),
"documentId": document_id,
"prompt": instructions,
@@ -212,6 +215,9 @@ impl EditingWorkerService for ReqwestEditingWorkerClient {
},
"interpret": false,
});
+ if let Some(editor) = editor {
+ request_body["editor"] = serde_json::json!({ "name": editor.as_str() });
+ }
// Propagate the current trace so the worker's spans join this
// service's trace instead of rooting their own.
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 6172811007..b900091be5 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -445,8 +445,10 @@ access to the title and property controls.
1. Click `Edit with AI` (button directly under the editor body).
2. A focused prompt box appears (placeholder `Describe the edit…`). Type the instruction,
press Enter (or click `Send`).
-3. While running, the button row shows an author chip (e.g. `Wolf (AI)`) and a `Stop` button
- (a11y text `Stop AI edit`). Edits stream directly into the document — there is no
+3. While running, the button row shows a `Stop` button (a11y text `Stop AI edit`), and the
+ live cursor walking the text is labelled with the editor's name: `Macro (AI)` for an
+ inline edit, or the name of the agent or persona whose session asked for the edit
+ (e.g. `Grunk (AI)`). Edits stream directly into the document — there is no
accept/reject step. The editor can insert the same `@` mention chips a person can:
dates/times, people, documents, channels, agent sessions (including the expanded
Magic Chip card), and the other chip types.
diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rs
index 05e4313caa..7af25ca259 100644
--- a/services/agent_harness_service/src/containers.rs
+++ b/services/agent_harness_service/src/containers.rs
@@ -84,7 +84,9 @@ pub struct RoutedContainers<Sessions> {
#[derive(Debug)]
enum Route {
Sandbox,
- InMem(SessionFacts),
+ /// Boxed: the facts dwarf the dataless `Sandbox` variant, and a route is
+ /// resolved once per container operation, not on a hot path.
+ InMem(Box<SessionFacts>),
}
impl<Sessions> RoutedContainers<Sessions>
@@ -126,17 +128,18 @@ where
.session_bot(row.bot_id)
.await
.map_err(HarnessError::Session)?;
- return Ok(Route::InMem(SessionFacts {
+ return Ok(Route::InMem(Box::new(SessionFacts {
id: session,
owner: row.owner_id,
model: row.model,
identity: Some(AgentIdentity {
+ bot: row.bot_id,
name: bot.name,
handle: bot.handle,
}),
instructions: row.instructions,
acp_session_id: row.acp_session_id,
- }));
+ })));
}
if AgentKind::for_session(row.bot_id, &row.harness) == AgentKind::InMemory {
return Err(HarnessError::Container(format!(
@@ -168,7 +171,7 @@ where
RoutedTransport::InMem(
self.inmem()
.manager
- .attach(facts, Some(command.egress.session_token))
+ .attach(*facts, Some(command.egress.session_token))
.await,
),
)),
@@ -203,7 +206,7 @@ where
) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match self.route(session).await? {
Route::InMem(facts) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
- RoutedTransport::InMem(self.inmem().manager.attach(facts, None).await),
+ RoutedTransport::InMem(self.inmem().manager.attach(*facts, None).await),
)),
Route::Sandbox => self
.sandbox
diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.md
index bd616a5dcc..3433808a01 100644
--- a/services/ai-editing-worker/AI_EDITING.md
+++ b/services/ai-editing-worker/AI_EDITING.md
@@ -135,10 +135,15 @@ node ids. It is what turns DocumentOps into actual edits to the lexical document
**The live cursor** is ephemeral. While a writer works, `realAwarenessSource`
encodes its caret/selection as a Loro cursor and broadcasts it over the
ephemeral awareness channel, so the website renders a remote cursor walking
-through the text. Each writer draws a name from a pool (`Sam (AI)`, `Alex (AI)`)
-and one of a few accent colors; the cursor lingers ~700ms after the writer
-finishes, then clears. We have some ugly code that manages resolving a block id
-to the `LoroText` that actually owns the characters for this :/
+through 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
+`(AI)`; the website keys off that suffix to keep AI name tags pinned. Each
+writer also gets one of a few accent colors; the cursor lingers ~700ms after the
+writer finishes, then clears. We have some ugly code that manages resolving a
+block 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
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.ts
index 5825222593..06c4d54200 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,5 +1,32 @@
+import { EphemeralStore } from 'loro-crdt';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { realAwarenessSource, resolveTextOwner } from './awareness-source';
+import {
+ AI_NAMES,
+ aiLabel,
+ realAwarenessSource,
+ resolveTextOwner,
+} from './awareness-source';
+import { PeerPool } from './peer-pool';
+
+describe('aiLabel', () => {
+ it('suffixes the editor name so the web client pins its cursor tag', () => {
+ expect(aiLabel('Macro')).toBe('Macro (AI)');
+ expect(aiLabel(' Grunk ')).toBe('Grunk (AI)');
+ });
+
+ it('does not double the suffix', () => {
+ expect(aiLabel('Wolf (AI)')).toBe('Wolf (AI)');
+ });
+
+ it('cuts an overlong name instead of rejecting it', () => {
+ const label = aiLabel('x'.repeat(200));
+ 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);
+ });
+});
// Duck-typed fake loro containers (kind/get), matching what resolveTextOwner reads.
function textC() {
@@ -94,6 +121,32 @@ describe('realAwarenessSource (no live mirror)', () => {
expect(send).not.toHaveBeenCalled();
});
+ it('broadcasts the borrowed peer name as the cursor user readers see', async () => {
+ const sent: Uint8Array[] = [];
+ const { mirror, doc } = fakeLoro({ c1: mapC('t1', { text: textC() }) });
+ const pool = PeerPool.forEditor('Macro');
+ const [a, b] = await Promise.all([pool.borrow(), pool.borrow()]);
+ for (const peer of [a, b]) {
+ realAwarenessSource({
+ mirror,
+ doc,
+ send: (bytes) => sent.push(bytes),
+ name: peer.name,
+ color: peer.color,
+ }).apply({ type: 'cursor', node: 't1', at: 3 });
+ }
+
+ // Decode what a reader's client would: two cursors, both labelled Macro.
+ const reader = new EphemeralStore<
+ Record<string, { user: { userId: string } }>
+ >(30_000);
+ for (const bytes of sent) reader.apply(bytes);
+ const users = Object.values(reader.getAllStates()).map(
+ (state) => state?.user.userId
+ );
+ expect(users).toEqual(['Macro (AI)', 'Macro (AI)']);
+ });
+
it('keeps live awareness alive until clear removes it', () => {
const send = vi.fn();
const { mirror, doc } = fakeLoro({ c1: mapC('t1', { text: textC() }) });
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.ts
index 53d68c94fd..5efde30364 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
@@ -20,6 +20,22 @@ import {
import { match } from 'ts-pattern';
import type { Awareness } from '../queue';
+/**
+ * Marks a cursor as an AI writer's. The web client keys off this suffix to keep
+ * the cursor's name tag pinned while the writer works (remote-cursor.tsx), so
+ * every AI label — pooled or persona — must end with it.
+ */
+export const AI_NAME_SUFFIX = '(AI)';
+/** Longest editor name shown on a cursor; anything past this is cut, not rejected. */
+const MAX_EDITOR_NAME_LENGTH = 64;
+
+/** The cursor label for an AI writer named `name`, e.g. `Macro (AI)`. */
+export function aiLabel(name: string): string {
+ const shown = name.trim().slice(0, MAX_EDITOR_NAME_LENGTH).trimEnd();
+ 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',
@@ -34,7 +50,7 @@ export const AI_NAMES = [
'Jacob',
'Aiden',
'Hutch',
-].map((n) => `${n} (AI)`);
+].map(aiLabel);
/** 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.ts
index 3dee1500ba..d4a939ad45 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
@@ -113,3 +113,37 @@ describe('PeerPool', () => {
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.ts
index 951bf30d07..f5f50eaae2 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,23 +1,52 @@
import PQueue from 'p-queue';
import { nextAiPeerId } from './ai-peer';
-import { AI_NAMES, COLORS } from './awareness-source';
+import { AI_NAMES, 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;
+};
+
export class PeerPool {
private readonly names: string[];
private readonly colors: string[];
+ private readonly distinctNames: boolean;
private readonly free: Peer[] = []; // released, ready to reuse
private readonly out = new Set<Peer>();
private readonly releasers = new Map<Peer, () => void>(); // peer → free its slot
private readonly gate: PQueue;
- constructor(opts?: { names?: string[]; colors?: string[]; max?: number }) {
+ constructor(opts?: PeerPoolOptions) {
this.names = [...(opts?.names ?? AI_NAMES)];
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,
+ });
+ }
+
/** Acquire a unique identity, waiting if `max` are already out (semaphore). */
public borrow(): Promise<Peer> {
return new Promise<Peer>((handOut) => {
@@ -52,6 +81,12 @@ export class PeerPool {
/** A never-before-issued identity: next unused base name, else a suffixed one. */
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;
@@ -68,7 +103,6 @@ export class PeerPool {
name = candidate;
}
- const color = this.colors[this.issued() % this.colors.length] ?? '';
return { name, color, peerId: nextAiPeerId() };
}
diff --git a/services/ai-editing-worker/src/endpoints/edit.ts b/services/ai-editing-worker/src/endpoints/edit.ts
index 0bdf54ee98..1342f6e92b 100644
--- a/services/ai-editing-worker/src/endpoints/edit.ts
+++ b/services/ai-editing-worker/src/endpoints/edit.ts
@@ -83,6 +83,12 @@ const EditBody = z
* small inline edits. Requires `models.fast`.
*/
mode: 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.
+ */
+ editor: z.object({ name: z.string().trim().min(1) }).optional(),
typingAnimations: z.boolean().optional(),
/** Animation speed multiplier applied while nobody is watching the doc. */
unwatchedSpeed: z.number().min(1).default(2.0),
@@ -168,6 +174,7 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
prompt,
models,
mode,
+ editor,
typingAnimations,
unwatchedSpeed,
interpret,
@@ -208,6 +215,7 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
span.setAttr('edit.mode', mode);
span.setAttr('edit.interpret', interpret);
span.setAttr('edit.propagate', propagate);
+ span.setAttr('edit.editor_named', editor !== undefined);
let modelFallbacks = 0;
try {
const result = await runEditSession({
@@ -216,6 +224,7 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
prompt,
models: buildModels(env, models, mode, () => modelFallbacks++),
mode,
+ editor,
typingAnimations,
sleep,
interpret,
diff --git a/services/ai-editing-worker/src/run-edit.ts b/services/ai-editing-worker/src/run-edit.ts
index 26fe5db91a..d072fd3170 100644
--- a/services/ai-editing-worker/src/run-edit.ts
+++ b/services/ai-editing-worker/src/run-edit.ts
@@ -13,6 +13,7 @@ import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-sche
import { Telemetry } from '@macro-inc/observability';
import type { LanguageModel } from 'ai';
import { fastEditor, supervisor } from './ai-editing/agents';
+import { PeerPool } from './ai-editing/awareness';
import type { DocumentOp } from './ai-editing/editor';
import type { CodeRunner } from './ai-editing/runtime';
import type { UsageEntry } from './ai-editing/token-tracker';
@@ -60,6 +61,12 @@ export type ResolvedModels = {
fast?: LanguageModel;
};
+/** Who readers see editing: the agent or persona the edit runs as. */
+export type Editor = {
+ /** Display name, e.g. `Macro`; every cursor this edit draws carries it. */
+ name: string;
+};
+
export type RunEditArgs = {
/** Live sync source, already constructed by the caller (ws in prod). */
source: SyncServiceSource;
@@ -67,6 +74,8 @@ export type RunEditArgs = {
prompt: string;
models: ResolvedModels;
mode?: EditMode;
+ /** Names the cursors; absent, writers draw pooled names instead. */
+ editor?: Editor;
/** Snippet runner — QuickJS sandbox in prod, `new Function` in local dev. */
runner?: CodeRunner;
typingAnimations?: boolean;
@@ -149,7 +158,9 @@ export async function runEditSession(
const { workspace, initialDocument } = await Telemetry.span(
'edit.hydrate',
async (span) => {
- const workspace = new EditingWorkspace(manager, liveSource, wal);
+ const workspace = new EditingWorkspace(manager, liveSource, wal, {
+ pool: args.editor ? PeerPool.forEditor(args.editor.name) : undefined,
+ });
const initialDocument = serializeWithXml(workspace.session);
span.setAttr('document.chars', initialDocument.length);
return { workspace, initialDocument };
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 3049646afe..c90c4a50da 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -245,6 +245,15 @@ impl InfraEnv {
"OVERRIDE_STATIC_FILE_SERVICE_URL".into(),
"http://static-file-service:8080".into(),
);
+ // Same split for the AI editing worker: `AiEditingWorkerUrl`'s Local
+ // default is http://localhost:8933, the worker's host port. Every
+ // container hosting the document tools (document cognition, the agent
+ // harness's in-process agent, the MCP server) calls EditDocument
+ // through this, so without it an agent's edit dials the caller itself.
+ env.insert(
+ "OVERRIDE_AI_EDITING_WORKER_URL".into(),
+ "http://ai-editing-worker:8933".into(),
+ );
// The alias LocalStack provisions for the Cursor API key CMK. Named by
// alias rather than key id because `CreateKey` mints a random id every
// run, and KMS accepts an alias anywhere a key id goes. Required by
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index 0099834127..1257bee72c 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -228,6 +228,10 @@ fn emits_in_network_service_url_overrides() {
"OVERRIDE_STATIC_FILE_SERVICE_URL",
"http://static-file-service:8080",
),
+ (
+ "OVERRIDE_AI_EDITING_WORKER_URL",
+ "http://ai-editing-worker:8933",
+ ),
] {
assert_eq!(env.get(key).map(String::as_str), Some(expected));
}