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(web): block and context access outside of provider scope causing errors (#6663)

dev-rb8fa42a7ba005
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 47d410681f..42eaf27f7a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -99,7 +99,10 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
### Misc
- If you create a Lexical Node or make breaking changes to a Lexical Node, you must increment the lexical version counter (in src/lib/core/component/LexicalMarkdown/version.ts) along with a brief note about changes.
-- Avoid `blockSignals`, `blockEffects`, `blockMemos` etc...
+- Do not add dependencies on the legacy block state system. Read it only at an
+ existing block-adapter boundary, then pass identity, permissions, state, and
+ lifecycle through feature context or explicit props; see FE-34 in
+ `docs/STYLE_GUIDE.md`.
### Good Reference
- https://github.com/solidjs-community/solid-primitives
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
index 36e999ae40..802a3f647e 100644
--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
@@ -20,7 +20,10 @@ import {
import { useUserId } from '@core/context/user';
import type { LoroManager } from '@macro-inc/collaboration/collab/manager';
import type { CommentNode } from '@macro-inc/lexical-core';
-import { useMessageLink } from '@queries/messages/document-messages';
+import {
+ useMessageLink,
+ useMessageRootsQuery,
+} from '@queries/messages/document-messages';
import { usePatchThreadMutation } from '@queries/messages/mutations';
import { onThreadStateUpdated } from '@queries/messages/sync';
import type { MessageThread } from '@service-storage/messages';
@@ -42,7 +45,6 @@ import { createStore, reconcile } from 'solid-js/store';
import { useMarkdownDocument } from '../context/markdown-document-context';
import { useDeleteNewComments } from './commentOperations';
import type { Mark, ThreadStore } from './commentType';
-import { documentMessagesQuery } from './messageCommentsResource';
function getHighlightThread(
highlight: Mark
@@ -91,10 +93,8 @@ export const MessageCommentsProvider: VoidComponent<{
} = useMarkdownDocument();
const { comments: commentState, setCommentState } = state;
const documentId = getDocumentId();
- const target = useMessageLink(
- () => ({ type: 'document', id: documentId }),
- () => props.activeComment?.()
- );
+ const parent = () => ({ type: 'document' as const, id: documentId });
+ const target = useMessageLink(parent, () => props.activeComment?.());
const wrapper = useContext(LexicalWrapperContext);
if (!isWrapperWithIds(wrapper)) {
console.error('Cannot use comment plugin without node ids.');
@@ -147,9 +147,9 @@ export const MessageCommentsProvider: VoidComponent<{
const [mountedMarks, setMountedMarks] = createStore<
Record<string, Record<string, HTMLElement | undefined> | undefined>
>({});
- const messageQuery = documentMessagesQuery();
+ const messageQuery = useMessageRootsQuery(parent);
const commentThreadsData = () =>
- messageQuery?.isSuccess ? (messageQuery.data ?? []) : [];
+ messageQuery.isSuccess ? (messageQuery.data ?? []) : [];
const setCommentsInitialized = (v: boolean) =>
setCommentState('commentMarksInitialized', v);
const highlightedId = () => commentState.highlightedCommentId;
@@ -272,7 +272,7 @@ export const MessageCommentsProvider: VoidComponent<{
if (Object.values(mountedMarks[anchor.mark_id] ?? {}).some(Boolean))
continue;
patchThread.mutate({
- parent: { type: 'document', id: documentId },
+ parent: parent(),
rootId: thread.id,
patch: { detach_anchor: true },
});
@@ -417,7 +417,7 @@ export const MessageCommentsProvider: VoidComponent<{
// Map server comment threads to mark metadata once marks are initialized
createEffect(() => {
if (!commentState.commentMarksInitialized) return;
- if (!messageQuery?.isSuccess) return;
+ if (!messageQuery.isSuccess) return;
detachRemovedThreads();
diff --git a/apps/web/src/features/block-md/comments/messageCommentsResource.ts b/apps/web/src/features/block-md/comments/messageCommentsResource.ts
index 64a302d39f..5b267e3125 100644
--- a/apps/web/src/features/block-md/comments/messageCommentsResource.ts
+++ b/apps/web/src/features/block-md/comments/messageCommentsResource.ts
@@ -1,32 +1,17 @@
-import { createBlockMemo, useBlockId, useBlockName } from '@core/block';
-import {
- enableUnifiedDocumentDiscussions,
- isFeatureEnabled,
-} from '@core/constant/featureFlags';
-import {
- useMessageActions,
- useMessageRootsQuery,
-} from '@queries/messages/document-messages';
+import { useMessageActions } from '@queries/messages/document-messages';
import type { PostMessage } from '@service-storage/messages';
+import { useMarkdownDocument } from '../context/markdown-document-context';
-/** Every root of the document, including tombstones, so marks can be reconciled. */
-export const documentMessagesQuery = createBlockMemo(() => {
- if (
- useBlockName() !== 'md' ||
- !isFeatureEnabled(enableUnifiedDocumentDiscussions)
- )
- return;
- const id = useBlockId();
- return useMessageRootsQuery(() => ({ type: 'document', id }));
-});
-
-function actions() {
- const id = useBlockId();
- return useMessageActions(() => ({ type: 'document', id }));
+function useDocumentMessageActions() {
+ const { documentId } = useMarkdownDocument();
+ return useMessageActions(() => ({
+ type: 'document',
+ id: documentId(),
+ }));
}
export function useCreateMarkedMessageResource() {
- const messages = actions();
+ const messages = useDocumentMessageActions();
return (
content: string,
markId: string,
@@ -42,5 +27,5 @@ export function useCreateMarkedMessageResource() {
}
export function useCreateMessageReplyResource() {
- return actions().post;
+ return useDocumentMessageActions().post;
}
diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
index 5edc1b9763..6dc174a8ae 100644
--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
@@ -1,6 +1,5 @@
import { ChannelInputContainer } from '@channel/Input/ChannelInputContainer';
import { FloatRegion } from '@components/app/mobile/float-regions/FloatRegion';
-import { useBlockAliasedName, useBlockId } from '@core/block';
import {
Discussion,
DiscussionComposer,
@@ -18,12 +17,12 @@ import {
} from '@core/messages/DocumentConversation';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
-import { useCanComment, useIsDocumentOwner } from '@core/signal/permissions';
import { buildSimpleEntityUrl } from '@core/util/url';
import type { MessageParent } from '@service-storage/messages';
import { Show } from 'solid-js';
import { createDocumentDiscussionSource } from '../comments/documentDiscussionSource';
import { URL_PARAMS } from '../constants';
+import { useMarkdownDocument } from '../context/markdown-document-context';
function MobileDiscussionComposer(props: { hidden: boolean }) {
// Preserve the editor and draft while its placement is hidden.
@@ -70,11 +69,11 @@ export function MessageDocumentDiscussion(props: {
floatingComposerOnTouch?: boolean;
editorHasFocus?: boolean;
}) {
- const id = useBlockId();
- const blockName = useBlockAliasedName();
+ const { documentId, kind, permissions } = useMarkdownDocument();
+ const id = documentId();
+ const documentKind = kind();
+ const blockName = documentKind === 'document' ? 'md' : documentKind;
const params = useUrlParams(URL_PARAMS);
- const canWrite = useCanComment();
- const canManage = useIsDocumentOwner();
const parent: MessageParent = { type: 'document', id };
const floating = () =>
props.floatingComposerOnTouch === true && isTouchDevice();
@@ -82,8 +81,8 @@ export function MessageDocumentDiscussion(props: {
<>
<DocumentConversation
parent={parent}
- canWrite={canWrite()}
- canManage={canManage()}
+ canWrite={permissions.canComment()}
+ canManage={permissions.isOwner()}
targetId={params.commentId()}
label={props.label}
buildLink={(message) =>
@@ -95,7 +94,7 @@ export function MessageDocumentDiscussion(props: {
hideComposer={floating()}
hideWhenEmpty={floating()}
/>
- <Show when={floating() && canWrite()}>
+ <Show when={floating() && permissions.canComment()}>
<StaticMarkdownContext>
<MobileMessageComposer
parent={parent}
diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
index db68da7e45..9e859e83e4 100644
--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
@@ -1149,10 +1149,12 @@ export function MarkdownEditor(props: {
</Show>
<Show when={ENABLE_MARKDOWN_COMMENTS}>
- <CommentsProvider
- activeComment={activeCommentIdParam}
- loroManager={props.loroManager}
- />
+ <Suspense>
+ <CommentsProvider
+ activeComment={activeCommentIdParam}
+ loroManager={props.loroManager}
+ />
+ </Suspense>
</Show>
<Show when={canEdit()}>
diff --git a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
index 58e2d5c35d..864f461b46 100644
--- a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
+++ b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
@@ -20,13 +20,22 @@ vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => true }));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanel: () => undefined,
}));
-vi.mock('@core/block', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- useBlockId: () => 'document',
- useBlockAliasedName: () => 'md',
+vi.mock('../context/markdown-document-context', () => ({
+ useMarkdownDocument: () => ({
+ documentId: () => 'document',
+ kind: () => 'task',
+ permissions: {
+ canComment: () => true,
+ isOwner: () => false,
+ },
+ }),
}));
vi.mock('@core/messages/DocumentConversation', () => ({
DocumentConversation: (props: {
+ parent: { type: string; id: string };
+ canWrite: boolean;
+ canManage: boolean;
+ buildLink: (message: { id: string }) => string;
hideComposer?: boolean;
hideWhenEmpty?: boolean;
}) => {
@@ -39,10 +48,6 @@ vi.mock('@core/messages/DocumentConversation', () => ({
return <textarea aria-label="Comment draft" />;
},
}));
-vi.mock('@core/signal/permissions', () => ({
- useCanComment: () => () => true,
- useIsDocumentOwner: () => () => false,
-}));
vi.mock('@core/component/ParamsProvider', () => ({
useUrlParams: () => ({ commentId: () => null }),
}));
@@ -93,11 +98,28 @@ describe('mobile document discussion accessory behind the flag', () => {
it('moves the composer to the accessory and hides an empty conversation', () => {
setup();
expect(mocks.conversation).toHaveBeenCalledWith(
- expect.objectContaining({ hideComposer: true, hideWhenEmpty: true })
+ expect.objectContaining({
+ parent: { type: 'document', id: 'document' },
+ canWrite: true,
+ canManage: false,
+ hideComposer: true,
+ hideWhenEmpty: true,
+ })
);
expect(mocks.mount).toHaveBeenCalledOnce();
});
+ it('builds links from the markdown document kind without a block context', () => {
+ setup();
+ const conversationProps = mocks.conversation.mock.calls[0][0] as {
+ buildLink: (message: { id: string }) => string;
+ };
+ const link = new URL(conversationProps.buildLink({ id: 'comment' }));
+
+ expect(link.pathname).toBe('/app/task/document');
+ expect(link.searchParams.get('comment_id')).toBe('comment');
+ });
+
it('hides during document typing and restores the same draft when the keyboard closes', () => {
const { input, setEditorHasFocus } = setup();
setEditorHasFocus(true);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
index db46b85590..d1f6b63e52 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
@@ -1,10 +1,5 @@
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
-import {
- isInBlock,
- type PreviewState,
- useBlockOwner,
- useMaybeBlockName,
-} from '@core/block';
+import { isInBlock, type PreviewState, useMaybeBlockName } from '@core/block';
import { useItemPreviewData } from '@core/component/ItemPreview';
import { toast } from '@core/component/Toast/Toast';
import { resolveBlockAlias, verifyBlockName } from '@core/constant/allBlocks';
@@ -48,6 +43,7 @@ import {
createMemo,
createRoot,
createSignal,
+ getOwner,
Match,
onCleanup,
runWithOwner,
@@ -188,22 +184,24 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
NonNullable<DocumentCardDecoratorProps['previewComponent']> | undefined
>(undefined);
- const blockOwner = useBlockOwner();
+ // Cached previews outlive individual Lexical decorator instances, so attach
+ // them to the editor lifecycle rather than the decorator lifecycle.
+ const previewOwner = wrapper?.owner ?? getOwner();
const registerPreviewElement = (
nodeId: string,
getElement: () => JSX.Element
) =>
- runWithOwner(blockOwner, () => {
- let disposeOnBlockUnmount: () => void = () => {};
- onCleanup(() => disposeOnBlockUnmount());
+ runWithOwner(previewOwner, () => {
+ let disposeOnOwnerCleanup: () => void = () => {};
+ onCleanup(() => disposeOnOwnerCleanup());
return createRoot((dispose) => {
const element = createMemo(getElement);
setDocumentCardPreviewComponent(nodeId, element, dispose);
- disposeOnBlockUnmount = () => unsetDocumentCardPreviewCache(nodeId);
+ disposeOnOwnerCleanup = () => unsetDocumentCardPreviewCache(nodeId);
return element;
- }, blockOwner);
+ }, previewOwner);
});
createEffect(() => {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/context/LexicalWrapperContext.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/context/LexicalWrapperContext.tsx
index 2d7d383973..8402e33473 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/context/LexicalWrapperContext.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/context/LexicalWrapperContext.tsx
@@ -15,7 +15,7 @@ import {
type EditorThemeClasses,
type LexicalEditor,
} from 'lexical';
-import { createContext } from 'solid-js';
+import { createContext, getOwner, type Owner } from 'solid-js';
import type { Store } from 'solid-js/store';
import {
createPluginManager,
@@ -36,6 +36,8 @@ type LexicalWrapperProps = {
export type LexicalWrapperBase = {
type: EditorType;
+ /** Owner of the editor lifecycle, stable across decorator replacement. */
+ owner: Owner | null;
plugins: PluginManager;
editor: LexicalEditor;
cleanup: () => void;
@@ -83,6 +85,7 @@ export function createLexicalWrapper({
withIds,
theme,
}: LexicalWrapperProps): LexicalWrapper {
+ const owner = getOwner();
_id++;
const nodes = RegisteredNodesByType[type];
@@ -128,6 +131,7 @@ export function createLexicalWrapper({
plugins,
editor,
cleanup,
+ owner,
type,
isInteractable,
mapping,
diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md
index 7acf9c0e3e..527615a509 100644
--- a/docs/STYLE_GUIDE.md
+++ b/docs/STYLE_GUIDE.md
@@ -305,3 +305,14 @@ TypeScript · `[ui]` UI / UX conventions
`ts-/tsx-feature-layers-use-context`, warning; currently scoped to activity.
Separate production composition and source-contract inversion still require
explicit review; the existing rules do not enforce them.)
+- **FE-34** `[arch]` Treat the legacy block state system as adapter-boundary code,
+ not state management for new or refactored surfaces. Do not add new
+ `useBlock*`, `createBlock*`, block-scoped signal/store/memo/resource, or block
+ permission dependencies. An existing block adapter may read legacy state once
+ and translate it into a feature-owned context or explicit props; descendants
+ and reusable components receive identity, permissions, state, and lifecycle
+ owners through those contracts and must remain mountable without `<Block>`.
+ Never add a `<Block>` wrapper merely to satisfy a missing dependency. If shared
+ code needs an owner or other host capability, expose it through the owning
+ surface context instead of borrowing `BlockContext`. (also:
+ apps/web/AGENTS.md)