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.

wolf: inline ai editing (#4911)

Wolf Mermelstein86705b9e2a12
diff --git a/apps/web/src/features/block-md/ai-edit/applyAiOps.ts b/apps/web/src/features/block-md/ai-edit/applyAiOps.ts
new file mode 100644
index 0000000000..d04f68c435
--- /dev/null
+++ b/apps/web/src/features/block-md/ai-edit/applyAiOps.ts
@@ -0,0 +1,15 @@
+import { Doc } from '@ai-ops/doc';
+import type { DocumentOp } from '@ai-ops/editor';
+import type { NodeIdMappings } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
+import type { LexicalEditor } from 'lexical';
+
+export function applyAiOps(
+ editor: LexicalEditor,
+ mapping: NodeIdMappings,
+ ops: DocumentOp[]
+): void {
+ const doc = new Doc({ editor, ids: mapping });
+ for (const op of ops) {
+ doc.apply(op);
+ }
+}
diff --git a/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
new file mode 100644
index 0000000000..9124c03404
--- /dev/null
+++ b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
@@ -0,0 +1,155 @@
+import { applyAiOps } from '@block-md/ai-edit/applyAiOps';
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import { toast } from '@core/component/Toast/Toast';
+import clickOutside from '@core/directive/clickOutside';
+import { TOKENS } from '@core/hotkey/tokens';
+import { AnimatedStarIcon } from '@icon/wide-star';
+import { cancelAiEdit, requestAiEdit } from '@service-ai-editing/client';
+import { Button, SendButton, Surface } from '@ui';
+import { createSignal, Show } from 'solid-js';
+
+false && clickOutside;
+
+/**
+ * Right-aligned "Edit with AI" pill above the document discussion that expands
+ * into a prompt card matching the Discussion composer.
+ */
+export function DocumentAiEditBar(props: { documentId: string }) {
+ const md = mdStore.get;
+
+ const [expanded, setExpanded] = createSignal(false);
+ const [editing, setEditing] = createSignal(false);
+ const [hovering, setHovering] = createSignal(false);
+ const [focused, setFocused] = createSignal(false);
+ const [prompt, setPrompt] = createSignal('');
+
+ const editor = buildChatEditor();
+
+ const collapse = () => {
+ setExpanded(false);
+ md.editor?.focus();
+ };
+
+ const submit = () => {
+ const value = prompt().trim();
+ if (!value || editing()) return;
+ editor.controls.clear();
+ setPrompt('');
+ collapse();
+ setEditing(true);
+
+ requestAiEdit({
+ documentId: props.documentId,
+ prompt: value,
+ onOps: (ops) => {
+ const target = md.editor;
+ const mapping = md.mapping;
+ if (target && mapping) applyAiOps(target, mapping, ops);
+ },
+ })
+ .then((result) => {
+ if (result === 'failed') toast.failure('AI edit failed');
+ })
+ .finally(() => setEditing(false));
+ };
+
+ editor
+ .onEnter(() => {
+ submit();
+ return true;
+ })
+ .onEscape(() => {
+ collapse();
+ return true;
+ })
+ .onChange((markdown) => setPrompt(markdown));
+
+ return (
+ <div class="flex justify-end">
+ {/* breathe keyframe for the star while an edit runs */}
+ <style>{`
+ @keyframes ai-edit-breathe {
+ 0%, 100% { transform: scale(1); }
+ 50% { transform: scale(1.18); }
+ }
+ .ai-edit-star-breathing {
+ animation: ai-edit-breathe 1.8s ease-in-out infinite;
+ transform-origin: center;
+ }
+ `}</style>
+ <Show
+ when={expanded()}
+ fallback={
+ <Button
+ onClick={() => {
+ if (editing()) cancelAiEdit(props.documentId);
+ else setExpanded(true);
+ }}
+ onMouseEnter={() => setHovering(true)}
+ onMouseLeave={() => setHovering(false)}
+ tooltip={editing() ? 'Stop AI edit' : 'Ask AI to edit'}
+ hotkey={editing() ? undefined : TOKENS.chat.input.focus}
+ variant="ghost"
+ size="sm"
+ depth={2}
+ class="gap-1.5 rounded-full px-2.5 ring ring-edge-muted"
+ >
+ <span
+ class="flex size-4 shrink-0 items-center justify-center"
+ classList={{
+ 'ai-edit-star-breathing text-accent': editing(),
+ }}
+ >
+ <AnimatedStarIcon triggerAnimation={hovering() && !editing()} />
+ </span>
+ <span
+ class="text-xs font-medium"
+ classList={{ 'text-ink-muted': editing() && !hovering() }}
+ >
+ {editing() ? (hovering() ? 'Stop' : 'Editing…') : 'Edit with AI'}
+ </span>
+ </Button>
+ }
+ >
+ <Surface
+ onFocusIn={() => setFocused(true)}
+ onFocusOut={(event) => {
+ const next = event.relatedTarget as Node | null;
+ if (next && event.currentTarget.contains(next)) return;
+ setFocused(false);
+ }}
+ use:clickOutside={collapse}
+ active={focused()}
+ class="w-96 max-w-full rounded-xl"
+ depth={2}
+ solid
+ >
+ <div class="flex flex-col gap-2 p-3">
+ <div class="flex items-start gap-2">
+ <span class="mt-0.5 flex size-4 shrink-0 items-center justify-center text-accent">
+ <AnimatedStarIcon triggerAnimation={focused()} />
+ </span>
+ <div class="min-w-0 grow text-sm text-ink">
+ <MarkdownShell
+ config={editor}
+ placeholder="Describe the edit…"
+ autofocus
+ />
+ </div>
+ </div>
+ <div class="flex items-center justify-end">
+ <SendButton
+ tooltip="Send edit"
+ shortcut="enter"
+ disabled={prompt().trim().length === 0}
+ onClick={submit}
+ />
+ </div>
+ </div>
+ </Surface>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
index c5fa91a98c..698c5a6657 100644
--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
@@ -310,6 +310,7 @@ export function MarkdownEditor(props: {
const [state, setState] = createSignal<EditorState>(editor.getEditorState());
setMdStore('editor', editor);
+ setMdStore('mapping', lexicalWrapper.mapping);
setMdStore('plugins', plugins);
const [editorFocus, setEditorFocus] = createSignal(false);
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index e58eb2cfbe..90070c27f4 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -1,9 +1,10 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { applyAiOps } from '@block-md/ai-edit/applyAiOps';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useIsAuthenticated } from '@core/auth';
import { useBlockId } from '@core/block';
import type { Completion } from '@core/client/completion';
import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
-// import { AskAi } from '@core/component/GeneralizedPopup/AskAI';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
import { LocationHighlight } from '@core/component/LexicalMarkdown/component/core/Highlights';
import {
@@ -38,6 +39,10 @@ import {
} from '@core/component/LexicalMarkdown/plugins/popup/popupPlugin';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { toast } from '@core/component/Toast/Toast';
+import {
+ INLINE_AI_EDITING_FLAG,
+ INLINE_AI_EDITING_OVERRIDE,
+} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { isMobile } from '@core/mobile/isMobile';
import { blockElementSignal } from '@core/signal/blockElement';
@@ -48,15 +53,22 @@ import { debouncedDependent } from '@core/util/debounce';
import { getScrollParentElement } from '@core/util/scrollParent';
import MacroGridLoader from '@icon/macro-grid-noise-loader-4.svg';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
+import { $getId } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
import GridIcon from '@phosphor/grid-four.svg';
import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
+import SparkleIcon from '@phosphor-icons/core/bold/sparkle-bold.svg?component-solid';
import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import PaperPlaneRight from '@phosphor-icons/core/fill/paper-plane-right-fill.svg?component-solid';
import CheckSquareIcon from '@phosphor-icons/core/regular/check-square.svg?component-solid';
import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';
import PencilIcon from '@phosphor-icons/core/regular/pencil.svg?component-solid';
+import {
+ cancelAiEdit,
+ hasActiveAiEdit,
+ requestAiEdit,
+} from '@service-ai-editing/client';
import { generateTitle } from '@service-cognition/client';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import { createCallback } from '@solid-primitives/rootless';
@@ -106,11 +118,36 @@ export function MarkdownPopup(props: {
const [highlightLocation, setHighlightLocation] =
createSignal<PersistentLocation | null>(null);
const [highlightRect, setHighlightRect] = createSignal<DOMRect | null>(null);
+ // The selected range, painted with the accent highlight whenever the prompt
+ // box holds focus (focusing it drops the native selection paint) and kept on
+ // as the loading indicator while an edit session runs.
+ const [aiEditLocation, setAiEditLocation] =
+ createSignal<PersistentLocation | null>(null);
+ const [aiEditRunning, setAiEditRunning] = createSignal(false);
+ const [aiInputFocused, setAiInputFocused] = createSignal(false);
+
+ onMount(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') cancelAiEdit(blockId);
+ };
+ window.addEventListener('keydown', onKeyDown);
+ onCleanup(() => {
+ window.removeEventListener('keydown', onKeyDown);
+ });
+ });
+
+ // Derive the highlight from the selection at the point it's set, rather
+ // than mirroring it reactively; an in-flight edit keeps it alive past the
+ // popup (see the onCleanup below).
+ const setSelectionAndHighlight = (value: EnhancedSelection | null) => {
+ setSelection(value);
+ setAiEditLocation(editor.read(() => $getSelectionLocation()));
+ };
plugins.use(
popupPlugin({
setIsPopupVisible: setPopupVisible,
- setSelection: setSelection,
+ setSelection: setSelectionAndHighlight,
})
);
@@ -118,6 +155,9 @@ export function MarkdownPopup(props: {
const showPopup = debouncedDependent(popupVisible, 100);
const canEdit = useCanEdit();
+ const inlineAiEditing = useFeatureFlag(INLINE_AI_EDITING_FLAG, {
+ enabledOverride: INLINE_AI_EDITING_OVERRIDE,
+ });
const canComment = useCanComment();
const currentUserId = useUserId();
@@ -337,6 +377,64 @@ export function MarkdownPopup(props: {
const handleRewrite = (_instructions: string) => {};
+ const [aiEditInput, setAiEditInput] = createSignal('');
+ let aiInputRef: HTMLTextAreaElement | undefined;
+
+ onCleanup(() => {
+ if (!aiEditRunning()) setAiEditLocation(null);
+ });
+
+ // Resolves the loro-mirror node ids of every top-level block touched by
+ // the selection, via the nodeIdPlugin's node state / key mapping.
+ const resolveSelectedNodeIds = (): string[] => {
+ const lexicalSelection = selection()?.lexicalSelection;
+ if (!lexicalSelection) return [];
+ return editor.read(() => {
+ const topNodes = new Set(
+ lexicalSelection
+ .getNodes()
+ .map((node) => node.getTopLevelElement() ?? node)
+ );
+ const ids = new Set<string>();
+ for (const node of topNodes) {
+ const id =
+ $getId(node) ??
+ props.lexicalMapping.nodeKeyToIdMap.get(node.getKey());
+ if (id) ids.add(id);
+ }
+ return [...ids];
+ });
+ };
+
+ const handleAiEditSubmit = () => {
+ if (aiEditRunning()) return;
+ const instruction = aiEditInput().trim();
+ if (!instruction) return;
+ const nodeIds = resolveSelectedNodeIds();
+ if (nodeIds.length === 0) {
+ toast.failure('Could not resolve the selected nodes');
+ return;
+ }
+ // The highlight is already tracking the selection; flagging the run
+ // keeps it alive (as the loading indicator) after the popup closes.
+ setAiEditRunning(true);
+ // Apply ops locally so the edit lands in this client's undo stack.
+ requestAiEdit({
+ documentId: blockId,
+ prompt: `Request: ${instruction}\nUser is selecting nodes ${nodeIds.join(' ')}. Proceed with requested edit`,
+ onOps: (ops) => applyAiOps(editor, props.lexicalMapping, ops),
+ })
+ .then((result) => {
+ if (result === 'failed') toast.failure('AI edit failed');
+ })
+ .finally(() => {
+ setAiEditLocation(null);
+ setAiEditRunning(false);
+ });
+ setAiEditInput('');
+ setPopupVisible(false);
+ };
+
createEffect(
on([completionType, rewriteInputRef], () => {
if (highlightLocation()) {
@@ -475,6 +573,65 @@ export function MarkdownPopup(props: {
</Button>
</div>
+ <Show when={inlineAiEditing().enabled && canEdit()}>
+ <div class="mt-1 flex w-full min-w-72 items-center gap-1 border-t border-edge p-1 pt-1.5 pr-2">
+ <SparkleIcon class="size-4 shrink-0 text-ink-extra-muted" />
+ <textarea
+ class="grow resize-none overflow-hidden bg-transparent text-sm placeholder:text-ink-placeholder focus:outline-none"
+ rows={1}
+ placeholder="Ask Macro to edit this selection"
+ ref={(el) => {
+ aiInputRef = el;
+ }}
+ onFocus={() => setAiInputFocused(true)}
+ onBlur={() => setAiInputFocused(false)}
+ onInput={(e) => {
+ setAiEditInput(e.currentTarget.value);
+ e.currentTarget.style.height = 'auto';
+ e.currentTarget.style.height = `${e.currentTarget.scrollHeight}px`;
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleAiEditSubmit();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ setAiEditInput('');
+ aiInputRef?.blur();
+ }
+ }}
+ />
+ <Show
+ when={hasActiveAiEdit(blockId)}
+ fallback={
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Ask Macro"
+ disabled={!aiEditInput().trim()}
+ onClick={handleAiEditSubmit}
+ >
+ <CheckIcon class="size-4" />
+ </Button>
+ }
+ >
+ <Button
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Stop AI edit"
+ onClick={() => cancelAiEdit(blockId)}
+ >
+ <div class="size-2.5 rounded-xs bg-current" />
+ </Button>
+ </Show>
+ </div>
+ </Show>
+
<Show when={!completion() && completionType() === 'rewrite'}>
<div class="flex flex-col border-t border-edge mt-1 pt-2 w-full">
<p class="text-ink-muted font-medium pt-1 pl-3 text-sm">
@@ -702,6 +859,34 @@ export function MarkdownPopup(props: {
captureBoundingDomRect={setHighlightRect}
/>
</Show>
+ <Show when={(aiInputFocused() || aiEditRunning()) && aiEditLocation()}>
+ <style>{`
+ .ai-edit-highlight {
+ background: var(--color-accent);
+ opacity: 0.25;
+ border-radius: 3px;
+ }
+ @keyframes ai-edit-pulse {
+ 0%, 100% { opacity: 0.2; }
+ 50% { opacity: 0.6; }
+ }
+ .ai-edit-highlight-running {
+ animation: ai-edit-pulse 1.4s ease-in-out infinite;
+ }
+ `}</style>
+ <LocationHighlight
+ editor={editor}
+ mountRef={props.highlightLayerRef}
+ location={aiEditLocation()!}
+ mapping={props.lexicalMapping}
+ padding={[0, 2]}
+ class={
+ aiEditRunning()
+ ? 'ai-edit-highlight ai-edit-highlight-running'
+ : 'ai-edit-highlight'
+ }
+ />
+ </Show>
</>
);
}
diff --git a/apps/web/src/features/block-md/component/Notebook.tsx b/apps/web/src/features/block-md/component/Notebook.tsx
index 4429f3153c..35b814da0e 100644
--- a/apps/web/src/features/block-md/component/Notebook.tsx
+++ b/apps/web/src/features/block-md/component/Notebook.tsx
@@ -1,4 +1,5 @@
import { AskMacroButton } from '@app/features/chat/ChatWithAgentButton';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { CommentMargin } from '@block-md/comments/CommentMargin';
import {
commentsStore,
@@ -18,6 +19,8 @@ import {
DEV_MODE_ENV,
ENABLE_HISTORY_COMPONENT,
ENABLE_MARKDOWN_COMMENTS,
+ INLINE_AI_EDITING_FLAG,
+ INLINE_AI_EDITING_OVERRIDE,
LOCAL_ONLY,
} from '@core/constant/featureFlags';
import { useIsMacroTeam } from '@core/context/team';
@@ -29,6 +32,7 @@ import {
blockHotkeyScopeSignal,
} from '@core/signal/blockElement';
import { tempRedirectLocation } from '@core/signal/location';
+import { useCanEdit } from '@core/signal/permissions';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
@@ -45,6 +49,7 @@ import {
import { useHistory } from '../history/HistoryContext';
import { HistoryOverlay } from '../history/HistoryOverlay';
import { DispatchAgentButton } from './DispatchAgentMenu';
+import { DocumentAiEditBar } from './DocumentAiEditBar';
import { DocumentDiscussion } from './DocumentDiscussion';
import { InlineTaskGithubPullRequests } from './InlineTaskGithubPullRequests';
import { InlineTaskProperties } from './InlineTaskProperties';
@@ -124,6 +129,10 @@ export function Notebook(props: {
const history = useHistory();
const { navigatedFromJK } = useNavigatedFromJK();
const documentId = props.documentId;
+ const canEdit = useCanEdit();
+ const inlineAiEditing = useFeatureFlag(INLINE_AI_EDITING_FLAG, {
+ enabledOverride: INLINE_AI_EDITING_OVERRIDE,
+ });
let notebookRef!: HTMLDivElement;
let commentMarginRef: HTMLDivElement | undefined;
@@ -398,6 +407,11 @@ export function Notebook(props: {
</Show>
</div>
<Show when={!history.isOpen()}>
+ <Show when={inlineAiEditing().enabled && canEdit() && !isMobile()}>
+ <div class="mb-2">
+ <DocumentAiEditBar documentId={props.documentId} />
+ </div>
+ </Show>
<DocumentDiscussion />
</Show>
</ParamsProvider>
diff --git a/apps/web/src/features/block-md/signal/markdownBlockData.ts b/apps/web/src/features/block-md/signal/markdownBlockData.ts
index bff2a71d04..9d7acd1d74 100644
--- a/apps/web/src/features/block-md/signal/markdownBlockData.ts
+++ b/apps/web/src/features/block-md/signal/markdownBlockData.ts
@@ -4,6 +4,7 @@ import type {
SelectionData,
WordcountStats,
} from '@core/component/LexicalMarkdown/plugins';
+import type { NodeIdMappings } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
import { createCallback } from '@solid-primitives/rootless';
import type { LexicalEditor } from 'lexical';
import type { Store } from 'solid-js/store';
@@ -24,6 +25,8 @@ export const blockDataSignal = blockDataSignalAs<MarkdownData>('md');
*/
export type MdData = {
editor?: LexicalEditor;
+ /** Durable nodeId <-> nodeKey mapping for the main editor (from the nodeId plugin). */
+ mapping?: NodeIdMappings;
titleEditor?: LexicalEditor;
plugins?: PluginManager;
selection?: Store<SelectionData>;
diff --git a/apps/web/src/features/block-pdf/component/PDFPopup.tsx b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
index cfe7a3175a..566d33c292 100644
--- a/apps/web/src/features/block-pdf/component/PDFPopup.tsx
+++ b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
@@ -3,7 +3,6 @@ import { useSplitLayout } from '@components/app/split-layout/layout';
import { useIsAuthenticated } from '@core/auth';
import { useBlockId } from '@core/block';
import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
-// import { AskAi } from '@core/component/GeneralizedPopup/AskAI';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
import { blockElementSignal } from '@core/signal/blockElement';
import { createMarkdownFile } from '@core/util/create';
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index d87a6a9f2b..2f3543cfaf 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -341,6 +341,13 @@ export const ENABLE_UNIFIED_LIST_AI_INPUT = resolveFeatureFlag(
true
);
+// Inline AI editing: the floating document AI edit pill and the AI editing
+// tool in the selection formatting menu. Gated by PostHog; use the reactive
+// `useFeatureFlag(INLINE_AI_EDITING_FLAG, { enabledOverride: INLINE_AI_EDITING_OVERRIDE })`.
+export const INLINE_AI_EDITING_FLAG = 'inline-ai-editing';
+export const INLINE_AI_EDITING_OVERRIDE =
+ resolveFeatureFlag('INLINE_AI_EDITING', DEV_MODE_ENV) || undefined;
+
export const ENABLE_EMAIL_SCHEDULED_SEND = resolveFeatureFlag(
'ENABLE_EMAIL_SCHEDULED_SEND',
true
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
new file mode 100644
index 0000000000..98429ae98d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
@@ -0,0 +1,132 @@
+import type { DocumentOp } from '@ai-ops/editor';
+import { toast } from '@core/component/Toast/Toast';
+import { getDocumentPermissionToken } from '@service-storage/client';
+import { createSignal } from 'solid-js';
+
+// Full-URL override (scheme included) for pointing at a local wrangler dev
+// worker, e.g. VITE_AI_EDITING_WORKER_URL=http://localhost:8788 bun run dev
+const overrideUrl: string | undefined = import.meta.env
+ .VITE_AI_EDITING_WORKER_URL;
+
+const AI_EDITING_WORKER_HOST =
+ overrideUrl?.replace(/\/$/, '') ??
+ (import.meta.env.MODE === 'development'
+ ? 'https://ai-editing-worker-dev.macroverse.workers.dev'
+ : 'https://ai-editing-worker.macroverse.workers.dev');
+
+/**
+ * Model fallback chains per worker role. Mirrors the chains the backend
+ * EditDocument tool sends (crates/documents editing_worker_client.rs).
+ */
+const MODELS = {
+ supervisor: [
+ { provider: 'anthropic', model: 'claude-opus-4-8' },
+ { provider: 'anthropic', model: 'claude-sonnet-4-6' },
+ { provider: 'openai', model: 'gpt-5.5' },
+ ],
+ interpret: [
+ { provider: 'cerebras', model: 'zai-glm-4.7' },
+ { provider: 'anthropic', model: 'claude-sonnet-4-6' },
+ ],
+ coding: [
+ { provider: 'cerebras', model: 'gpt-oss-120b' },
+ { provider: 'anthropic', model: 'claude-haiku-4-5' },
+ ],
+} as const;
+
+export type AiEditResult = 'ok' | 'failed' | 'cancelled';
+
+// In-flight edits by document id. Aborting the fetch cancels the session
+// server-side too: the worker threads the request signal into runEditSession
+// (needs enable_request_signal, so only on deployed Cloudflare, not workerd).
+const editControllers = new Map<string, AbortController>();
+const [activeEditDocs, setActiveEditDocs] = createSignal<ReadonlySet<string>>(
+ new Set()
+);
+const syncActiveEditDocs = () =>
+ setActiveEditDocs(new Set(editControllers.keys()));
+
+/** Reactive: whether an AI edit is in flight for this document. */
+export function hasActiveAiEdit(documentId: string): boolean {
+ return activeEditDocs().has(documentId);
+}
+
+/** Cancel the in-flight AI edit for this document, if any. */
+export function cancelAiEdit(documentId: string): void {
+ editControllers.get(documentId)?.abort();
+}
+
+/**
+ * Run an AI edit session directly on the ai-editing-worker.
+ *
+ * The edit arrives via live sync; the worker only responds once the session
+ * finishes, so the returned promise doubles as a completion signal. Cancelable
+ * via `cancelAiEdit` (a later edit on the same document takes over the
+ * registry slot). Failures are logged. Never rejects.
+ *
+ * Pass `onOps` to instead have the worker compute ops WITHOUT committing them
+ * to the shared doc — the full op list is handed back once the session
+ * finishes, and `onOps` applies them locally (via `applyAiOps`), so the edit
+ * lands in the caller's own undo stack (Ctrl+Z) and syncs out attributed to
+ * the user.
+ */
+export async function requestAiEdit(args: {
+ documentId: string;
+ prompt: string;
+ onOps?: (ops: DocumentOp[]) => void;
+}): Promise<AiEditResult> {
+ const controller = new AbortController();
+ editControllers.set(args.documentId, controller);
+ syncActiveEditDocs();
+ try {
+ const token = await getDocumentPermissionToken(args.documentId);
+ const res = await fetch(`${AI_EDITING_WORKER_HOST}/edit`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ documentToken: token,
+ documentId: args.documentId,
+ prompt: args.prompt,
+ models: MODELS,
+ interpret: false,
+ propagate: args.onOps === undefined ? undefined : false,
+ }),
+ signal: controller.signal,
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ console.error('ai edit request failed', res.status, body);
+ return 'failed';
+ }
+ if (args.onOps) {
+ const { ops } = (await res.json()) as { ops: DocumentOp[] };
+ args.onOps(ops);
+ }
+ return 'ok';
+ } catch (e) {
+ if (controller.signal.aborted) return 'cancelled';
+ console.error('ai edit request failed', e);
+ return 'failed';
+ } finally {
+ if (editControllers.get(args.documentId) === controller) {
+ editControllers.delete(args.documentId);
+ syncActiveEditDocs();
+ }
+ }
+}
+
+/**
+ * `requestAiEdit` wrapper that toasts `'AI edit failed'` on failure (a user
+ * cancel stays silent). The caller supplies a `finally` callback for any
+ * post-edit cleanup (e.g. clearing a loading signal).
+ */
+export function requestAiEditWithToast(
+ args: { documentId: string; prompt: string },
+ onSettled: () => void
+): void {
+ requestAiEdit(args)
+ .then((result) => {
+ if (result === 'failed') toast.failure('AI edit failed');
+ })
+ .finally(onSettled);
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 9c08d490a8..7080138da6 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -188,7 +188,9 @@ export function dssFetch<T extends Record<string, any> = never>(
return fetchWithToken<T>(`${dssHost}${url}`, init);
}
-async function getDocumentPermissionToken(documentId: string): Promise<string> {
+export async function getDocumentPermissionToken(
+ documentId: string
+): Promise<string> {
const token = await fetchWithToken<GetDocumentPermissionsTokenResponse>(
`${SYNC_PERMISSION_TOKEN_DSS_HOST}/documents/permissions_token/${documentId}`,
{
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index ca357d9d7c..d77ddbe14c 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -104,6 +104,12 @@
"@service-cognition/*": [
"./src/lib/service-clients/service-cognition/*"
],
+ "@service-ai-editing/*": [
+ "./src/lib/service-clients/ai-editing-worker/*"
+ ],
+ "@ai-ops/*": [
+ "../../services/ai-editing-worker/src/ai-editing/*"
+ ],
"@service-connection/*": [
"./src/lib/service-clients/service-connection/*"
],
diff --git a/packages/collaboration/src/collab/source.ts b/packages/collaboration/src/collab/source.ts
index 02be281aa8..968d9fdc76 100644
--- a/packages/collaboration/src/collab/source.ts
+++ b/packages/collaboration/src/collab/source.ts
@@ -1,6 +1,6 @@
import type { Listen } from '@solid-primitives/event-bus';
import type { VersionVector } from 'loro-crdt';
-import type { ResultAsync } from 'neverthrow';
+import { okAsync, type ResultAsync } from 'neverthrow';
import type { Accessor } from 'solid-js';
import type { RawUpdate } from './shared';
@@ -82,3 +82,23 @@ export type LiveSyncSource = {
reconnect: () => void;
cleanup: () => void;
};
+
+/**
+ * A {@link LiveSyncSource} that acks everything and forwards nothing. For
+ * callers that want to skip live propagation without threading a boolean
+ * through every method that would otherwise push to the server.
+ */
+export function createNoopLiveSyncSource(documentId: string): LiveSyncSource {
+ return {
+ documentId,
+ listen: () => () => {},
+ pushUpdate: async () => true,
+ pushAwareness: () => {},
+ registerPeerId: () => {},
+ status: () => SyncSourceStatus.Connected,
+ requestUpdatesSince: () => okAsync(new Uint8Array()),
+ requestSnapshot: () => okAsync(new Uint8Array()),
+ reconnect: () => {},
+ cleanup: () => {},
+ };
+}
diff --git a/services/ai-editing-worker/src/ai-editing/prompts/CODER.md b/services/ai-editing-worker/src/ai-editing/prompts/CODER.md
index 700a1da9d4..fc5e551f6c 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/CODER.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/CODER.md
@@ -35,7 +35,7 @@ editor.bold('b5', 'Bluejay');
When you do need `insertLineBreak`, the `at` offset counts only characters (inline objects don't count). Append each line with `insertTextAfterInline(brRef, text)` and accumulate the running text length manually.
- Pass **plain text only** -- you MUST NOT ever use XML/markdown syntax. `editor.setText(id, '# x')` inserts the literal characters `# x`, it does not make a heading. We do not support or understand Markdown or XML in our editor.
- **`setText(id, text)` fully replaces a node's content and clears all inline formatting** -- use it whenever you want to overwrite a text node entirely with plain text. `replace(id, find, to)` is only for partial substitutions where `find` is a known substring and you want to preserve surrounding formatting. **For a code block, always rewrite its whole body with `setText` -- never use `replace` on a code block.**
-- **All text content goes in the `snippets` argument of your runCode call** -- `runCode({ code: "editor.setText('b3', snippets.intro)", snippets: { intro: "Your composed text." } })` -- referenced as `snippets.KEY` in the code. NEVER embed prose as a string literal inside `code`; quotes and apostrophes break the script. This applies both to text you compose and to exact text from the task or user request, which you must copy character-for-character into your `snippets` values.
+- **All text content goes in the `snippets` argument of your runCode call** -- `runCode({ code: "editor.setText('b3', snippets.intro)", snippets: { intro: "Your composed text." } })` -- referenced as `snippets.KEY` in the code. NEVER embed prose as a string literal inside `code`, so that quotes and apostrophes don't break the code. Use snippets. **Snippet values are raw plain text, so do not escape anything inside them.** Write a literal `"` for a quote, never `\"`; a literal `'` for an apostrophe, never `\'`. Backslash-escaping a snippet value inserts a literal backslash into the document.
- If a call references an id that doesn't exist, you get an error back naming it -- re-read the regions shown, pick the right id, and try again. Don't repeat a failing call.
- If the instruction refers to a node you **cannot see** in your window, do NOT guess or invent an id. First call `readDocument` to view the whole document and locate the real id. Only if it is genuinely absent should you call `reportBlocked({ message })` to hand the problem back to the supervisor -- that ends your task, so don't also call `runCode`.
- You may use ordinary JS (loops, arrays) to drive many calls. You have the full power of plain JavaScript at your disposal.
diff --git a/services/ai-editing-worker/src/ai-editing/tools/run-code.ts b/services/ai-editing-worker/src/ai-editing/tools/run-code.ts
index c0ba7b6fcd..b8578f1526 100644
--- a/services/ai-editing-worker/src/ai-editing/tools/run-code.ts
+++ b/services/ai-editing-worker/src/ai-editing/tools/run-code.ts
@@ -33,7 +33,7 @@ export function createRunCodeTool(opts: RunCodeToolOptions) {
.record(z.string(), z.string())
.optional()
.describe(
- 'all text content your code inserts: key -> exact content. reference each as `snippets.KEY` in `code` instead of embedding it as a string literal (avoids escaping errors).'
+ 'all text content your code relies on. referenced as `snippets.KEY` in code rather than embedded in code. No escaping is necessary for snippet definitions, just use raw loose text.'
),
}),
execute: async ({ code, snippets }) => {
diff --git a/services/ai-editing-worker/src/editing-workspace.ts b/services/ai-editing-worker/src/editing-workspace.ts
index b3ccbacdb6..ebb3b12e7c 100644
--- a/services/ai-editing-worker/src/editing-workspace.ts
+++ b/services/ai-editing-worker/src/editing-workspace.ts
@@ -2,8 +2,8 @@ import type { InferType } from '@loro-mirror/core';
import { SyncEngine } from '@macro-inc/collaboration/collab/engine';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';
+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';
import type { WALSyncer } from '@macro-inc/collaboration/collab/wal';
-import type { SyncServiceSource } from '@macro-inc/collaboration/sync-service/source';
import type {
MARKDOWN_LORO_SCHEMA,
MarkdownLoroSchemaType,
@@ -40,7 +40,7 @@ export class EditingWorkspace {
constructor(
private readonly manager: LoroManager<typeof MARKDOWN_LORO_SCHEMA>,
- private readonly source: SyncServiceSource,
+ private readonly source: LiveSyncSource,
wal: WALSyncer<RawUpdate>,
opts: EditingWorkspaceOptions = {}
) {
diff --git a/services/ai-editing-worker/src/endpoints/edit.ts b/services/ai-editing-worker/src/endpoints/edit.ts
index b5e1925129..4fe87c747c 100644
--- a/services/ai-editing-worker/src/endpoints/edit.ts
+++ b/services/ai-editing-worker/src/endpoints/edit.ts
@@ -7,9 +7,10 @@ import { createFallback } from 'ai-fallback';
import { Hono } from 'hono';
import * as z from 'zod';
import { type Bindings, getEnv } from '../env';
-import { type Model, runEditSession } from '../run-edit';
+import { type Model, type ResolvedModels, runEditSession } from '../run-edit';
import { runInSandbox } from '../sandbox';
import { watchPresenceSpeed } from '../service-clients';
+import { createWorkerSyncSource } from '../sources';
import { renderTraceMarkdown } from '../trace-log';
import { insertEditTrace } from '../traces-db';
@@ -51,8 +52,43 @@ const EditBody = z.object({
unwatchedSpeed: z.number().min(1).default(2.0),
interpret: z.boolean().default(true),
debug: z.boolean().default(false),
+ /**
+ * Commit edits to the shared Loro doc (default true). Set false to have the
+ * worker compute ops without committing them. This gives you the flexibility
+ * to apply them on your own.
+ */
+ propagate: z.boolean().default(true),
});
+/** Resolve each role's model list into a live model (single) or a fallback
+ * chain (multiple, advancing on provider errors/rate limits). */
+function buildModels(
+ env: ReturnType<typeof getEnv>,
+ models: EditModels
+): ResolvedModels {
+ const resolveOne = ({ provider, model }: Model) => {
+ const apiKey = env[PROVIDERS[provider].key];
+ return PROVIDERS[provider].create({ apiKey })(model);
+ };
+ const resolveModel = (specs: Model[]): LanguageModel => {
+ const resolved = specs.map(resolveOne);
+ if (resolved.length === 1) return resolved[0];
+ return createFallback({
+ models: resolved,
+ onError: (error, modelId) =>
+ console.error(`edit model ${modelId} failed, falling back:`, error),
+ });
+ };
+ return {
+ supervisor: resolveModel(models.supervisor),
+ interpret: resolveModel(models.interpret),
+ // Fresh fallback per coder — see ResolvedModels.coding.
+ coding: () => resolveModel(models.coding),
+ };
+}
+
+type EditModels = z.infer<typeof EditBody>['models'];
+
const edit = new Hono<{ Bindings: Bindings }>();
edit.post('/', zValidator('json', EditBody), async (c) => {
@@ -66,25 +102,9 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
unwatchedSpeed,
interpret,
debug,
+ propagate,
} = c.req.valid('json');
- const resolveOne = ({ provider, model }: Model) => {
- const apiKey = env[PROVIDERS[provider].key];
- return PROVIDERS[provider].create({ apiKey })(model);
- };
-
- // A single model resolves directly; multiple wrap in a fallback that advances
- // to the next model on provider errors/rate limits.
- const resolveModel = (specs: Model[]): LanguageModel => {
- const resolved = specs.map(resolveOne);
- if (resolved.length === 1) return resolved[0];
- return createFallback({
- models: resolved,
- onError: (error, modelId) =>
- console.error(`edit model ${modelId} failed, falling back:`, error),
- });
- };
-
// FYI cancellation only works on live cloudflare not workerd. And it requires enable_request_signal.
const signal = c.req.raw.signal;
signal.addEventListener('abort', () => {
@@ -93,6 +113,7 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
try {
const wsUrl = `${env.SYNC_WS_BASE}/document/${documentId}/connect?token=${documentToken}`;
+ const source = createWorkerSyncSource(wsUrl, documentId, signal);
// Animations play at 1x while a human is watching and speed up to
// `unwatchedSpeed` when nobody is, so unseen edits finish faster without
@@ -111,19 +132,15 @@ edit.post('/', zValidator('json', EditBody), async (c) => {
);
const { usage, ops, session, clarification } = await runEditSession({
- wsUrl,
+ source,
documentId,
prompt,
- models: {
- supervisor: resolveModel(models.supervisor),
- interpret: resolveModel(models.interpret),
- // Fresh fallback per coder — see ResolvedModels.coding.
- coding: () => resolveModel(models.coding),
- },
+ models: buildModels(env, models),
typingAnimations,
sleep,
interpret,
debug,
+ propagate,
runner: runInSandbox,
signal,
}).finally(presence.stop);
diff --git a/services/ai-editing-worker/src/index.ts b/services/ai-editing-worker/src/index.ts
index 5bbe5bcdac..5d143d4eac 100644
--- a/services/ai-editing-worker/src/index.ts
+++ b/services/ai-editing-worker/src/index.ts
@@ -1,10 +1,56 @@
import './globals';
import { Hono } from 'hono';
+import { cors } from 'hono/cors';
import endpoints from './endpoints';
import type { Bindings } from './env';
+// Mirrors crates/macro_cors's ALLOWED_ORIGINS/is_allowed_origin.
+const ALLOWED_ORIGINS = new Set([
+ 'http://localhost:5173',
+ 'https://dashboarddev.macro.com',
+ 'https://dashboard.macro.com',
+ 'http://host.local:3000',
+ 'https://dev.macro.com',
+ 'https://www.macro.com',
+ 'https://macro.com',
+ 'http://tauri.localhost',
+ 'tauri://localhost',
+]);
+
+function isOriginAllowed(origin: string): boolean {
+ if (ALLOWED_ORIGINS.has(origin)) return true;
+
+ try {
+ const { protocol, hostname } = new URL(origin);
+ if (
+ protocol === 'https:' &&
+ (hostname === 'preview.macro.com' ||
+ hostname.endsWith('.preview.macro.com'))
+ ) {
+ return true;
+ }
+ } catch {
+ // Not a valid URL; fall through to the other checks.
+ }
+
+ const localhostPort = origin.match(/^http:\/\/localhost:(\d+)$/)?.[1];
+ if (localhostPort) {
+ const port = Number(localhostPort);
+ return (port >= 3000 && port <= 3999) || (port >= 20000 && port <= 60000);
+ }
+ return false;
+}
+
const app = new Hono<{ Bindings: Bindings }>();
+// The web app calls /edit directly from the browser; auth is the document
+// permission token in the body, so we scope CORS to known Macro origins.
+app.use(
+ '*',
+ cors({
+ origin: (origin) => (isOriginAllowed(origin) ? origin : null),
+ })
+);
app.route('/', endpoints);
export default app;
diff --git a/services/ai-editing-worker/src/run-edit.ts b/services/ai-editing-worker/src/run-edit.ts
index b31d9c2bf7..1a29efc736 100644
--- a/services/ai-editing-worker/src/run-edit.ts
+++ b/services/ai-editing-worker/src/run-edit.ts
@@ -1,9 +1,14 @@
import { LoroManager } from '@macro-inc/collaboration/collab/manager';
import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';
+import {
+ createNoopLiveSyncSource,
+ type LiveSyncSource,
+} from '@macro-inc/collaboration/collab/source';
import {
InMemoryWALStore,
WALSyncer,
} from '@macro-inc/collaboration/collab/wal';
+import type { SyncServiceSource } from '@macro-inc/collaboration/sync-service/source';
import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
import type { LanguageModel } from 'ai';
import { supervisor } from './ai-editing/agents';
@@ -13,7 +18,6 @@ import type { UsageEntry } from './ai-editing/token-tracker';
import type { CoderRunCode, DispatchEditTrace } from './ai-editing/tools';
import { serializeWithXml } from './ai-editing/utils';
import { EditingWorkspace } from './editing-workspace';
-import { createWorkerSyncSource } from './sources';
import { buildTraceSession, type TraceSession } from './trace-log';
export type Model = {
@@ -34,7 +38,8 @@ export type ResolvedModels = {
};
export type RunEditArgs = {
- wsUrl: string;
+ /** Live sync source, already constructed by the caller (ws in prod). */
+ source: SyncServiceSource;
documentId: string;
prompt: string;
models: ResolvedModels;
@@ -48,6 +53,11 @@ export type RunEditArgs = {
interpret?: boolean;
/** Include a markdown trace of all supervisor steps in the result. */
debug?: boolean;
+ /**
+ * Commit edits to the shared Loro doc (default true). Set false to have the
+ * caller receive the returned `ops` without them being committed.
+ */
+ propagate?: boolean;
};
export type { UsageEntry };
@@ -63,11 +73,7 @@ export type RunEditResult = {
export async function runEditSession(
args: RunEditArgs
): Promise<RunEditResult> {
- const source = createWorkerSyncSource(
- args.wsUrl,
- args.documentId,
- args.signal
- );
+ const source = args.source;
const initialResult = await source.doInitialSync();
if (initialResult.isErr()) {
source.cleanup();
@@ -89,14 +95,22 @@ export async function runEditSession(
);
}
+ // When the caller applies the returned ops locally instead, propagating
+ // here too would double the content — so route live sync to a no-op sink
+ // that acks everything and forwards nothing.
+ const shouldPropagate = args.propagate ?? true;
+ const liveSource: LiveSyncSource = shouldPropagate
+ ? source
+ : createNoopLiveSyncSource(args.documentId);
+
const wal = new WALSyncer<RawUpdate>(
new InMemoryWALStore<RawUpdate>(),
- (updates) => source.pushUpdate(updates)
+ (updates) => liveSource.pushUpdate(updates)
);
// The workspace owns the editing surface + its two-way sync with Loro, and
// hands out per-coder writers. Under debug it also records a replay trace.
- const workspace = new EditingWorkspace(manager, source, wal);
+ const workspace = new EditingWorkspace(manager, liveSource, wal);
const allOps: DocumentOp[] = [];
const coderCodeBlocks: CoderRunCode[][][] = [];
@@ -125,7 +139,8 @@ export async function runEditSession(
});
// Drain the queued propagates (plus a final catch-all sync) and ensure every
- // commit reached the server before we disconnect.
+ // commit reached the server before we disconnect. No-op sink when not
+ // propagating, so this is harmless either way.
await workspace.flush();
await wal.flush();