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.

feat: fancy history scrubber (#4142)

Wolf Mermelsteindbf824bcbbc6
diff --git a/js/app/packages/app/component/side-panel/SidePanel.tsx b/js/app/packages/app/component/side-panel/SidePanel.tsx
index c505e7d9a9..5c39f257bc 100644
--- a/js/app/packages/app/component/side-panel/SidePanel.tsx
+++ b/js/app/packages/app/component/side-panel/SidePanel.tsx
@@ -27,6 +27,7 @@ import {
} from 'solid-js';
import { HeaderIsland } from '../split-layout/components/HeaderIsland';
import { SplitHeaderRight } from '../split-layout/components/SplitHeader';
+import { splitPanelLayer } from '../split-layout/layers';
import {
SidePanelContext,
type SidePanelContextType,
@@ -108,6 +109,7 @@ function Layout(props: ParentProps<{ defaultOpen?: boolean }>) {
setIsOpen,
toggle,
isNarrow,
+ setOpenSectionIds: setOpenIds,
};
return (
@@ -172,15 +174,22 @@ function SidePanelLayoutInner(
maxSize={SIDE_MAX_PX}
index={1}
>
- <SidePanelOutlet
- sections={props.sections}
- openIds={props.openIds}
- setOpenIds={props.setOpenIds}
- />
+ <div class={cn('relative size-full', splitPanelLayer.controls)}>
+ <SidePanelOutlet
+ sections={props.sections}
+ openIds={props.openIds}
+ setOpenIds={props.setOpenIds}
+ />
+ </div>
</Resize.Panel>
</Show>
<Show when={showOverlay()}>
- <div class="absolute inset-0 z-10 flex flex-col bg-surface">
+ <div
+ class={cn(
+ 'absolute inset-0 flex flex-col bg-surface',
+ splitPanelLayer.controls
+ )}
+ >
<Scroll>
{/* Full-frame mobile: the overlay spans the whole panel, so the
content must clear the floating header islands + status bar. */}
@@ -353,6 +362,7 @@ function useSidePanel() {
toggle: ctx.toggle,
isNarrow: ctx.isNarrow,
hasSections: ctx.hasSections,
+ setOpenSectionIds: ctx.setOpenSectionIds,
};
}
diff --git a/js/app/packages/app/component/side-panel/context.ts b/js/app/packages/app/component/side-panel/context.ts
index 0346120086..2fbf441e9f 100644
--- a/js/app/packages/app/component/side-panel/context.ts
+++ b/js/app/packages/app/component/side-panel/context.ts
@@ -27,6 +27,8 @@ export type SidePanelContextType = {
setIsOpen: (next: boolean | ((prev: boolean) => boolean)) => void;
/** Toggle the open state for the current layout mode. */
toggle: () => void;
+ /** Set which section IDs are expanded in the accordion. */
+ setOpenSectionIds: (ids: string[]) => void;
/**
* True when the layout is mobile or narrower than the split threshold.
* In this mode the side panel renders as a full-screen overlay rather than
diff --git a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx b/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
index 2f3274a75b..a656c5bced 100644
--- a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
@@ -28,6 +28,7 @@ import {
SplitPanelContext,
type SplitPanelContextType,
} from '../context';
+import { splitPanelLayer } from '../layers';
import { useSplitLayout } from '../layout';
import type { SplitHandle, SplitState } from '../layoutManager';
import { registerSplitHotkeys } from '../registerSplitHotkeys';
@@ -222,7 +223,8 @@ export function SplitPanel(props: SplitPanelProps) {
>
<Panel.Header
class={cn(
- 'block min-h-10.25 touch:min-h-11.25 p-0 overflow-visible border-b-0!',
+ 'relative block min-h-10.25 touch:min-h-11.25 p-0 overflow-visible border-b-0!',
+ splitPanelLayer.controls,
// On mobile the header collapses to a zero-height grid row;
// SplitHeader overlays the body as floating islands.
'mobile:min-h-0 mobile:border-b-0',
diff --git a/js/app/packages/app/component/split-layout/layers.ts b/js/app/packages/app/component/split-layout/layers.ts
new file mode 100644
index 0000000000..8c607e0dc4
--- /dev/null
+++ b/js/app/packages/app/component/split-layout/layers.ts
@@ -0,0 +1,3 @@
+export const splitPanelLayer = {
+ controls: 'z-30',
+} as const;
diff --git a/js/app/packages/app/component/split-layout/layoutManager.ts b/js/app/packages/app/component/split-layout/layoutManager.ts
index 0a28b4d1a7..fd0ea2bd06 100644
--- a/js/app/packages/app/component/split-layout/layoutManager.ts
+++ b/js/app/packages/app/component/split-layout/layoutManager.ts
@@ -159,6 +159,7 @@ export type ReferredFrom =
| 'hotkey'
| 'quick-access'
| 'file-upload'
+ | 'fork'
| null;
export type SplitState = {
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index 45e40f686f..35193f0b04 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -27,6 +27,8 @@ import {
Suspense,
} from 'solid-js';
import type { MarkdownData } from '../definition';
+import { HistoryProvider } from '../history/HistoryContext';
+import { OldOverlay } from '../history/OldOverlay';
import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
import { FindAndReplace } from './FindAndReplace';
import { MarkdownNameProvider, useMarkdownName } from './MarkdownNameProvider';
@@ -168,56 +170,62 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
tabIndex={-1}
>
<ModalsProvider>
- <SidePanel.Layout>
- <Show when={ENABLE_MARKDOWN_SIDE_PANEL && !isInstructionsMd()}>
- <MarkdownSidePanelSections
- canEdit={canEdit()}
- documentName={displayName() ?? ''}
- />
- </Show>
- <div class="flex flex-col size-full">
- <div class="relative shrink-0">
- <Suspense>
- <Show
- when={!isInstructionsMd()}
- fallback={<InstructionsTopBar />}
- >
- <TopBar name={displayName} />
- </Show>
- </Suspense>
- <Suspense>
- <Show when={!isInstructionsMd()}>
- <div class="absolute right-4 top-1.5 z-action-menu flex justify-end">
- <FindAndReplace />
+ <HistoryProvider documentId={() => blockId}>
+ <OldOverlay />
+ <SidePanel.Layout>
+ <Show when={ENABLE_MARKDOWN_SIDE_PANEL && !isInstructionsMd()}>
+ <MarkdownSidePanelSections
+ canEdit={canEdit()}
+ documentName={displayName() ?? ''}
+ />
+ </Show>
+ <div class="flex flex-col size-full">
+ <div class="relative shrink-0">
+ <Suspense>
+ <Show
+ when={!isInstructionsMd()}
+ fallback={<InstructionsTopBar />}
+ >
+ <TopBar name={displayName} />
+ </Show>
+ </Suspense>
+ <Suspense>
+ <Show when={!isInstructionsMd()}>
+ <div class="absolute right-4 top-1.5 z-action-menu flex justify-end">
+ <FindAndReplace />
+ </div>
+ </Show>
+ </Suspense>
+ </div>
+ <DocumentDebouncedNotificationReadMarker
+ notificationSource={notificationSource}
+ documentId={blockId}
+ />
+ <div
+ class="w-full grow overflow-hidden relative"
+ data-block-content
+ >
+ <Scroll class="relative" ref={setScrollRef}>
+ <div class="relative portal-scope mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">
+ <Suspense>
+ <Show
+ when={!isInstructionsMd()}
+ fallback={
+ <InstructionsNotebook loroManager={loroManager} />
+ }
+ >
+ <Notebook
+ loroManager={loroManager}
+ documentId={blockId}
+ />
+ </Show>
+ </Suspense>
</div>
- </Show>
- </Suspense>
+ </Scroll>
+ </div>
</div>
- <DocumentDebouncedNotificationReadMarker
- notificationSource={notificationSource}
- documentId={blockId}
- />
- <div
- class="w-full grow overflow-hidden relative"
- data-block-content
- >
- <Scroll class="relative" ref={setScrollRef}>
- <div class="relative portal-scope mobile:pt-(--mobile-content-inset-top) mobile:pb-(--mobile-content-inset-bottom)">
- <Suspense>
- <Show
- when={!isInstructionsMd()}
- fallback={
- <InstructionsNotebook loroManager={loroManager} />
- }
- >
- <Notebook loroManager={loroManager} />
- </Show>
- </Suspense>
- </div>
- </Scroll>
- </div>
- </div>
- </SidePanel.Layout>
+ </SidePanel.Layout>
+ </HistoryProvider>
</ModalsProvider>
</div>
</DocumentBlockContainer>
diff --git a/js/app/packages/block-md/component/ModalsProvider.tsx b/js/app/packages/block-md/component/ModalsProvider.tsx
index 467069120f..136918e929 100644
--- a/js/app/packages/block-md/component/ModalsProvider.tsx
+++ b/js/app/packages/block-md/component/ModalsProvider.tsx
@@ -11,7 +11,6 @@ import type { EntityType } from '@core/types';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { blockNameToItemType } from '@service-storage/client';
import { createSignal, type ParentProps } from 'solid-js';
-import { HistoryDrawer } from './History';
export function ModalsProvider(props: ParentProps) {
const blockId = useBlockId();
@@ -38,7 +37,6 @@ export function ModalsProvider(props: ParentProps) {
notificationSource={notificationSource}
/>
<ReferencesDrawer documentId={blockId} documentName={name()} />
- <HistoryDrawer documentId={blockId} />
<DetailsDrawer documentId={blockId} />
<ShareBlockModal />
</ShareDialogContext.Provider>
diff --git a/js/app/packages/block-md/component/Notebook.tsx b/js/app/packages/block-md/component/Notebook.tsx
index b8f64c62fe..6418f91f18 100644
--- a/js/app/packages/block-md/component/Notebook.tsx
+++ b/js/app/packages/block-md/component/Notebook.tsx
@@ -10,10 +10,14 @@ import { useGoToTempRedirect } from '@block-md/signal/location';
import { mdStore } from '@block-md/signal/markdownBlockData';
import { useBlockAliasedName, useBlockId } from '@core/block';
import type { LoroManager } from '@core/collab/manager';
-import { editorFocusSignal } from '@core/component/LexicalMarkdown/utils';
+import {
+ editorFocusSignal,
+ getSaveState,
+} from '@core/component/LexicalMarkdown/utils';
import { ParamsProvider } from '@core/component/ParamsProvider';
import {
DEV_MODE_ENV,
+ ENABLE_HISTORY_COMPONENT,
ENABLE_MARKDOWN_COMMENTS,
LOCAL_ONLY,
} from '@core/constant/featureFlags';
@@ -38,6 +42,8 @@ import {
Show,
untrack,
} from 'solid-js';
+import { useHistory } from '../history/HistoryContext';
+import { HistoryOverlay } from '../history/HistoryOverlay';
import { DispatchAgentButton } from './DispatchAgentMenu';
import { DocumentDiscussion } from './DocumentDiscussion';
import { InlineTaskGithubPullRequests } from './InlineTaskGithubPullRequests';
@@ -95,7 +101,10 @@ function useCanUseLexicalStateDebugger() {
});
}
-export function Notebook(props: { loroManager: LoroManager }) {
+export function Notebook(props: {
+ loroManager: LoroManager;
+ documentId: string;
+}) {
const blockElement = blockElementSignal.get;
const blockId = useBlockId();
const blockAliasedName = useBlockAliasedName();
@@ -104,7 +113,9 @@ export function Notebook(props: { loroManager: LoroManager }) {
const documentName = useBlockDocumentName();
const scopeId = blockHotkeyScopeSignal.get;
const md = mdStore.get;
+ const history = useHistory();
const { navigatedFromJK } = useNavigatedFromJK();
+ const documentId = props.documentId;
let notebookRef!: HTMLDivElement;
let commentMarginRef: HTMLDivElement | undefined;
@@ -120,6 +131,12 @@ export function Notebook(props: { loroManager: LoroManager }) {
if (!ENABLE_MARKDOWN_COMMENTS) return false;
return Object.keys(comments).length > 0;
});
+ const showComments = () => hasComment() && !history.isOpen();
+
+ const currentEditorState = () => {
+ const editor = md.editor;
+ return editor ? getSaveState(editor.getEditorState()) : undefined;
+ };
// Set the refs on the block store.
onMount(() => {
@@ -135,7 +152,7 @@ export function Notebook(props: { loroManager: LoroManager }) {
const observeCallback = () => {
const { width, left } = notebookRef.getBoundingClientRect();
setWidth(width);
- const mode = hasComment() ? widthToMode(width) : CommentLayoutMode.none;
+ const mode = showComments() ? widthToMode(width) : CommentLayoutMode.none;
setLayoutMode(mode);
const leftFloat =
contentRef.getBoundingClientRect().right - left + GapTargetWidth;
@@ -148,9 +165,8 @@ export function Notebook(props: { loroManager: LoroManager }) {
createEffect(() => {
const goToTempRedirect = useGoToTempRedirect();
- const documentId = blockId;
const recentState = tempRedirectLocation();
- if (!documentId || !recentState) return;
+ if (!recentState) return;
setTimeout(() => {
goToTempRedirect(documentId, recentState);
@@ -158,7 +174,7 @@ export function Notebook(props: { loroManager: LoroManager }) {
});
createEffect(() => {
- if (!hasComment()) {
+ if (!showComments()) {
setLayoutMode(CommentLayoutMode.none);
} else {
setLayoutMode(widthToMode(untrack(width)));
@@ -166,8 +182,10 @@ export function Notebook(props: { loroManager: LoroManager }) {
});
createEffect(() => {
- if (hasComment()) {
+ if (showComments()) {
setWideEnoughForComments(width() >= BreaksPoints.md);
+ } else {
+ setWideEnoughForComments(false);
}
});
@@ -291,7 +309,11 @@ export function Notebook(props: { loroManager: LoroManager }) {
return (
<div class={containerClasses()} ref={notebookRef}>
- <div class={contentDivClasses()} ref={contentRef}>
+ <div
+ class={contentDivClasses()}
+ ref={contentRef}
+ classList={{ relative: true }}
+ >
<SidePanel.Section
id="document-ai-actions"
title="Actions"
@@ -320,16 +342,31 @@ export function Notebook(props: { loroManager: LoroManager }) {
<TaskDuplicateMatchPill />
</div>
<ParamsProvider>
- <MarkdownEditor
- loroManager={props.loroManager}
- showLexicalStateDebugger={
- canUseLexicalStateDebugger() && showLexicalStateDebugger()
- }
- onLexicalStateDebuggerClose={() =>
- setShowLexicalStateDebugger(false)
- }
- />
- <DocumentDiscussion />
+ {/* Relative wrapper so the history overlay covers only the body region,
+ leaving the title + properties above it untouched and aligned. */}
+ <div class="relative">
+ <MarkdownEditor
+ loroManager={props.loroManager}
+ showLexicalStateDebugger={
+ canUseLexicalStateDebugger() && showLexicalStateDebugger()
+ }
+ onLexicalStateDebuggerClose={() =>
+ setShowLexicalStateDebugger(false)
+ }
+ />
+ <Show when={ENABLE_HISTORY_COMPONENT}>
+ <HistoryOverlay
+ currentState={currentEditorState}
+ selectedAt={history.selectedAt()}
+ isLive={history.isLive()}
+ visible={history.isOpen()}
+ onExit={history.exit}
+ />
+ </Show>
+ </div>
+ <Show when={!history.isOpen()}>
+ <DocumentDiscussion />
+ </Show>
</ParamsProvider>
</div>
<div
@@ -345,8 +382,8 @@ export function Notebook(props: { loroManager: LoroManager }) {
}}
ref={commentMarginRef}
classList={{
- block: hasComment(),
- hidden: !hasComment(),
+ block: showComments(),
+ hidden: !showComments(),
}}
>
<CommentMargin />
diff --git a/js/app/packages/block-md/component/TopBar.tsx b/js/app/packages/block-md/component/TopBar.tsx
index e2d4b7386b..3bc43afc1a 100644
--- a/js/app/packages/block-md/component/TopBar.tsx
+++ b/js/app/packages/block-md/component/TopBar.tsx
@@ -7,10 +7,8 @@ import {
type BlockTool,
ResponsiveBlockToolbar,
ResponsivePermissionsBadge,
- ToolButton,
} from '@app/component/ResponsiveBlockToolbar';
import { useSidePanel } from '@app/component/side-panel';
-import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
import type { FileOperation } from '@app/component/split-layout/components/SplitFileMenu';
import {
SplitHeaderLeft,
@@ -30,40 +28,26 @@ import {
ShareTrigger,
useShareDialogContext,
} from '@core/component/TopBar/ShareButton';
-import {
- ENABLE_HISTORY_COMPONENT,
- ENABLE_MARKDOWN_LIVE_COLLABORATION,
-} from '@core/constant/featureFlags';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
-import { useCanEdit } from '@core/signal/permissions';
import { copyBranchNameToClipboard } from '@core/util/branchName';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { buildSimpleEntityUrl } from '@core/util/url';
-import ClockIcon from '@phosphor/clock-counter-clockwise.svg';
import Download from '@phosphor/download.svg';
import GitBranch from '@phosphor/git-branch.svg';
import IconLink from '@phosphor/link.svg';
import TerminalWindowIcon from '@phosphor/terminal-window.svg';
import { blockNameToItemType } from '@service-storage/client';
-import {
- type Accessor,
- createEffect,
- For,
- on,
- onCleanup,
- Show,
-} from 'solid-js';
+import { type Accessor, createEffect, on, onCleanup } from 'solid-js';
+import { useHistory } from '../history/HistoryContext';
import {
DispatchAgentButton,
useDispatchAgentSplitFileActions,
} from './DispatchAgentMenu';
-import { HISTORY_DRAWER_ID } from './History';
export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
- const canEdit = useCanEdit();
const blockName = useBlockName();
const blockId = useBlockId();
const scopeId = blockHotkeyScopeSignal.get;
@@ -75,7 +59,6 @@ export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
const downloadAsMarkdownText = useDownloadDocumentAsMarkdownText();
- const historyControl = useDrawerControl(HISTORY_DRAWER_ID);
const shareCtx = useShareDialogContext();
const blockAliasedName = useBlockAliasedName();
const isTask = blockAliasedName === 'task';
@@ -136,6 +119,7 @@ export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
const sidePanel = useSidePanel();
const splitPanel = useSplitPanel();
+ const _history = useHistory();
// Register at the split scope so `]` works from anywhere in the split
// (header, toolbar, drawer), but tie disposal to this TopBar so the
@@ -157,28 +141,6 @@ export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
}
const tools: BlockTool[] = [
- {
- label: 'Ask Macro',
- icon: ChatWithAgentIcon,
- action: () =>
- openChatWithAgent({
- type: 'document',
- id: blockId,
- name: name(),
- fileType: 'md',
- }),
- condition: isMobile,
- },
- {
- label: 'History',
- icon: ClockIcon,
- action: historyControl.toggle,
- isActive: historyControl.isOpen,
- condition: () =>
- ENABLE_MARKDOWN_LIVE_COLLABORATION &&
- ENABLE_HISTORY_COMPONENT &&
- canEdit(),
- },
// {
// label: 'Copy Branch Name',
// icon: GitBranch,
@@ -281,38 +243,9 @@ export function TopBar(props: { name?: Accessor<string | undefined> } = {}) {
}
export function InstructionsTopBar() {
- const canEdit = useCanEdit();
- const historyControl = useDrawerControl(HISTORY_DRAWER_ID);
-
- const tools: BlockTool[] = [
- {
- label: 'History',
- icon: ClockIcon,
- action: historyControl.toggle,
- isActive: historyControl.isOpen,
- condition: () =>
- ENABLE_MARKDOWN_LIVE_COLLABORATION &&
- ENABLE_HISTORY_COMPONENT &&
- canEdit(),
- },
- ];
-
return (
- <>
- <SplitHeaderLeft>
- <StaticSplitLabel label="AI Instructions" iconType="md" />
- </SplitHeaderLeft>
- <For each={tools}>
- {(tool) => (
- <Show when={!tool.condition || tool.condition()}>
- {tool.buttonComponent ? (
- <tool.buttonComponent />
- ) : (
- <ToolButton tool={tool} />
- )}
- </Show>
- )}
- </For>
- </>
+ <SplitHeaderLeft>
+ <StaticSplitLabel label="AI Instructions" iconType="md" />
+ </SplitHeaderLeft>
);
}
diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index 49e2d4540d..19e8721e93 100644
--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -2,6 +2,7 @@ import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import {
GithubPullRequestDetailsRows,
SidePanel,
+ useSidePanel,
} from '@app/component/side-panel';
import { EntityPropertiesSection } from '@app/component/side-panel/properties';
import { useSplitLayout } from '@app/component/split-layout/layout';
@@ -17,7 +18,10 @@ import {
import { Notifications } from '@core/component/Notifications';
import { References } from '@core/component/References';
import { UserIcon } from '@core/component/UserIcon';
-import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
+import {
+ ENABLE_HISTORY_COMPONENT,
+ USE_MACRO_PR_SUMMARY_BLOCK,
+} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import type { Entity, EntityType } from '@core/types';
import { tryMacroId, useDisplayName } from '@core/user';
@@ -25,6 +29,7 @@ import { type DateValue, formatDate } from '@core/util/date';
import { openExternalUrl } from '@core/util/url';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import { useNotificationsForEntity } from '@notifications';
+import CaretRightIcon from '@phosphor/caret-right.svg';
import ClockIcon from '@phosphor/clock.svg';
import {
getDefaultPinnedProperties,
@@ -52,6 +57,9 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import { useHistory } from '../../history/HistoryContext';
+import { HistoryScrubber } from '../../history/HistoryScrubber';
+import { HistorySessionList } from '../../history/HistorySessionList';
import { mdStore } from '../../signal/markdownBlockData';
import { TaskDuplicateMatchesSidePanelSection } from '../TaskDuplicateMatches';
@@ -102,6 +110,11 @@ export function MarkdownSidePanelSections(
<StatsSectionContent />
</SidePanel.Section>
</Show>
+ <Show when={ENABLE_HISTORY_COMPONENT}>
+ <SidePanel.Section id="history" title="History" defaultOpen order={35}>
+ <HistorySectionContent />
+ </SidePanel.Section>
+ </Show>
<GithubSectionConditional documentId={blockId} isTask={isTask()} />
<NotificationsSectionConditional entity={entity()} />
<ReferencesSectionConditional documentId={blockId} />
@@ -112,6 +125,77 @@ export function MarkdownSidePanelSections(
);
}
+function HistorySectionContent() {
+ const history = useHistory();
+ const sidePanel = useSidePanel();
+ const [showSessions, setShowSessions] = createSignal(false);
+
+ createEffect(() => {
+ if (history.isOpen()) {
+ sidePanel?.setOpenSectionIds(['history']);
+ }
+ });
+ const isShowingSessions = () => history.isOpen() || showSessions();
+
+ const totalEdits = createMemo(() => {
+ const sessions = history.sessions();
+ if (!sessions) return 0;
+ return sessions.reduce((sum, s) => sum + s.count, 0);
+ });
+
+ return (
+ <Show
+ when={
+ !history.loading.sessions() && totalEdits() > 1 && history.sessions()
+ }
+ fallback={<p class="text-xs text-ink-muted">No history yet</p>}
+ >
+ {(sessions) => (
+ <div class="hidden min-w-0 overflow-hidden md:block">
+ <HistoryScrubber compact />
+ <Show when={sessions().length > 0}>
+ <div class="mt-3 min-w-0 border-edge-muted border-t pt-2">
+ <button
+ type="button"
+ aria-expanded={isShowingSessions()}
+ class="flex w-full items-center gap-1.5 rounded-md px-1 py-1 text-ink-muted text-xs hover:bg-hover hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
+ onClick={() => {
+ history.enter();
+ setShowSessions(true);
+ }}
+ >
+ <CaretRightIcon
+ class={cn(
+ 'size-3 shrink-0 transition-transform duration-90',
+ isShowingSessions() && 'rotate-90'
+ )}
+ />
+ <span>
+ {isShowingSessions() ? 'Activity' : 'Show activity'}
+ </span>
+ </button>
+ <Show when={isShowingSessions()}>
+ <HistorySessionList
+ sessions={sessions()}
+ selectedAt={history.selectedAt}
+ onSelect={history.enter}
+ onViewSessionDiff={(session) => {
+ if (history.diff.session()?.startMs === session.startMs) {
+ history.diff.clear();
+ } else {
+ history.diff.view(session);
+ }
+ }}
+ />
+ </Show>
+ </div>
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Sharing Section (snippets)
// ─────────────────────────────────────────────────────────────────────────────
@@ -451,7 +535,7 @@ function ReferencesSectionConditional(props: { documentId: string }) {
<SidePanel.Section
id="references"
title={<SidePanel.CountTitle label="References" count={count()} />}
- order={50}
+ order={33}
>
<div class="text-xs">
<References documentId={props.documentId} />
diff --git a/js/app/packages/block-md/history/HistoryContext.tsx b/js/app/packages/block-md/history/HistoryContext.tsx
new file mode 100644
index 0000000000..b44a69cdc3
--- /dev/null
+++ b/js/app/packages/block-md/history/HistoryContext.tsx
@@ -0,0 +1,243 @@
+import { tryMacroId, useDisplayName } from '@core/user';
+import {
+ buildDiffState,
+ buildWhoMap,
+ diffStates,
+ serializedEditorStateToMarkdown,
+} from '@lexical-core';
+import { useDocumentPeersQuery } from '@queries/sync/document-peers';
+import type { HistorySession, HistoryVersionId } from '@service-sync/client';
+import { syncServiceClient } from '@service-sync/client';
+import type { SerializedEditorState } from 'lexical';
+import { LoroDoc } from 'loro-crdt';
+import {
+ type Accessor,
+ createContext,
+ createMemo,
+ createResource,
+ createSignal,
+ type JSX,
+ mapArray,
+ useContext,
+} from 'solid-js';
+import { sessionize } from './sessionize';
+import { buildTimestampIndex } from './timestampIndex';
+import { userColor, userLabel } from './utils';
+
+export type HistoryUser = {
+ userId: string;
+ displayName: () => string;
+ color: string;
+};
+
+type HistoryContextValue = {
+ isOpen: Accessor<boolean>;
+ selectedAt: Accessor<Date | null>;
+ isLive: Accessor<boolean>;
+ open: () => void;
+ enter: (at?: Date) => void;
+ exit: () => void;
+ sessions: Accessor<readonly HistorySession[]>;
+ loading: { sessions: Accessor<boolean>; doc: Accessor<boolean> };
+ checkoutAt: (ms: number) => SerializedEditorState | null;
+ versionIdAt: (ms: number) => HistoryVersionId | null;
+ diff: {
+ session: Accessor<HistorySession | null>;
+ previewState: Accessor<SerializedEditorState | null>;
+ view: (session: HistorySession) => void;
+ clear: () => void;
+ };
+ userByPeer: (peerId: string) => HistoryUser;
+ userById: (userId: string) => HistoryUser;
+};
+
+const HistoryContext = createContext<HistoryContextValue>();
+
+export function HistoryProvider(props: {
+ documentId: Accessor<string>;
+ children: JSX.Element;
+}) {
+ const [isOpen, setIsOpen] = createSignal(false);
+ const [selectedAt, setSelectedAt] = createSignal<Date | null>(null);
+ const [isLive, setIsLive] = createSignal(true);
+ const [diffSession, setDiffSession] = createSignal<HistorySession | null>(
+ null
+ );
+
+ const open = () => setIsOpen(true);
+
+ const enter = (at?: Date) => {
+ setDiffSession(null);
+ setSelectedAt(at ?? null);
+ setIsLive(at === undefined);
+ setIsOpen(true);
+ };
+
+ const exit = () => {
+ setIsOpen(false);
+ setSelectedAt(null);
+ setIsLive(true);
+ setDiffSession(null);
+ };
+
+ // Park the scrubber at the session's end and flip into diff mode. The overlay
+ // renders `diffPreviewState` while a diff is active.
+ const viewSessionDiff = (session: HistorySession) => {
+ setSelectedAt(new Date(session.endMs));
+ setIsLive(false);
+ setIsOpen(true);
+ setDiffSession(session);
+ };
+
+ // Download the full snapshot once and drive both the session timeline and
+ // local scrubbing from it. The full snapshot (not updates) is required so
+ // getAllChanges() carries the per-change timestamp metadata.
+ const [historyDoc] = createResource(
+ () => props.documentId(),
+ async (documentId) => {
+ const result = await syncServiceClient.getSnapshot({ documentId });
+ if (result.isErr()) throw new Error(String(result.error));
+ const doc = new LoroDoc();
+ doc.import(result.value);
+ return doc;
+ }
+ );
+
+ // Peer -> user mapping for labelling sessions; lightweight JSON.
+ const peerMap = useDocumentPeersQuery(props.documentId);
+
+ // One stable useDisplayName per unique userId — batched into a single fetch.
+ const uniqueUserIds = createMemo(() =>
+ peerMap.data ? [...new Set(peerMap.data.values())] : []
+ );
+ const userEntries = mapArray(uniqueUserIds, (userId) => {
+ const [displayName] = useDisplayName(tryMacroId(userId), {
+ emailFallback: 'local-part',
+ });
+ return { userId, displayName, color: userColor(userId) };
+ });
+ const userById = (userId: string): HistoryUser =>
+ userEntries().find((e) => e.userId === userId) ?? {
+ userId,
+ displayName: () => userLabel(userId),
+ color: userColor(userId),
+ };
+ const userByPeer = (peerId: string): HistoryUser =>
+ userById(peerMap.data?.get(peerId) ?? 'unknown');
+
+ const historyIndex = createMemo(() => {
+ const doc = historyDoc();
+ return doc ? buildTimestampIndex(doc) : null;
+ });
+
+ // Sessions derived locally from the oplog: one edit event per change, grouped
+ // per user.
+ const sessions = createMemo<readonly HistorySession[]>(() => {
+ const doc = historyDoc();
+ const peers = peerMap.data;
+ if (!doc || !peers) return [];
+
+ const events: { userId: string; tMs: number }[] = [];
+ for (const [peer, changes] of doc.getAllChanges()) {
+ const userId = peers.get(peer) ?? 'unknown';
+ for (const change of changes) {
+ events.push({ userId, tMs: change.timestamp * 1000 });
+ }
+ }
+
+ const index = historyIndex();
+ if (!index) return sessionize(events);
+ return sessionize(events).filter((s) => {
+ const before = index.checkoutAt(s.startMs - 1);
+ const after = index.checkoutAt(s.endMs);
+ // Can't compute both states (edge frontiers) — keep rather than hide.
+ if (!before || !after) return true;
+ return (
+ // HACK: basically, some deltas are not visually different, and that's confusing
+ serializedEditorStateToMarkdown(before) !==
+ serializedEditorStateToMarkdown(after)
+ );
+ });
+ });
+
+ const checkoutAt = (ms: number): SerializedEditorState | null =>
+ historyIndex()?.checkoutAt(ms) ?? null;
+
+ const versionIdAt = (ms: number): HistoryVersionId | null =>
+ historyIndex()?.versionIdAt(ms) ?? null;
+
+ // Diff a session: the state just before its first edit vs the state at its end,
+ // paired by node id. Each changed block is attributed to whoever last edited it
+ // (via buildWhoMap over the loro op history), falling back to the session author.
+ const diffPreviewState = createMemo<SerializedEditorState | null>(() => {
+ const session = diffSession();
+ if (!session) return null;
+ const before = checkoutAt(session.startMs - 1);
+ const after = checkoutAt(session.endMs);
+ if (!before || !after) return null;
+ // Checking out an arbitrary frontier can yield a structurally-incomplete
+ // lexical state (empty root, or a node whose `type` isn't set yet — the same
+ // states that break the plain scrubbing preview). Skip and degrade to "no
+ // diff" rather than crashing the overlay.
+ if (!before.root.children?.length || !after.root.children?.length)
+ return null;
+ try {
+ const doc = historyDoc();
+ const peers = peerMap.data;
+ const whoMap =
+ doc && peers
+ ? buildWhoMap(doc, (peer) => peers.get(peer) ?? 'unknown')
+ : new Map<string, string>();
+ const diffs = diffStates(
+ before,
+ after,
+ (id) => whoMap.get(id) ?? session.userId
+ );
+ return buildDiffState(before, diffs);
+ } catch (error) {
+ console.warn('[history] could not build the session diff', error);
+ return null;
+ }
+ });
+
+ const value: HistoryContextValue = {
+ isOpen,
+ selectedAt,
+ isLive,
+ open,
+ enter,
+ exit,
+ sessions,
+ loading: {
+ sessions: () => historyDoc() == null || peerMap.isPending,
+ doc: () => historyDoc() == null,
+ },
+ checkoutAt,
+ versionIdAt,
+ userByPeer,
+ userById,
+ diff: {
+ session: diffSession,
+ previewState: diffPreviewState,
+ view: viewSessionDiff,
+ clear: () => {
+ setDiffSession(null);
+ setSelectedAt(null);
+ setIsLive(true);
+ },
+ },
+ };
+
+ return (
+ <HistoryContext.Provider value={value}>
+ {props.children}
+ </HistoryContext.Provider>
+ );
+}
+
+export function useHistory() {
+ const context = useContext(HistoryContext);
+ if (!context)
+ throw new Error('useHistory must be used inside HistoryProvider');
+ return context;
+}
diff --git a/js/app/packages/block-md/history/HistoryOverlay.tsx b/js/app/packages/block-md/history/HistoryOverlay.tsx
new file mode 100644
index 0000000000..43bd9ab43f
--- /dev/null
+++ b/js/app/packages/block-md/history/HistoryOverlay.tsx
@@ -0,0 +1,138 @@
+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import type { DiffStatus } from '@lexical-core';
+import type { SerializedEditorState } from 'lexical';
+import { createMemo, createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { useHistory } from './HistoryContext';
+import { UserHoverTag } from './UserHoverTag';
+import { userColor } from './utils';
+
+export function HistoryOverlay(props: {
+ currentState: () => SerializedEditorState | undefined;
+ selectedAt: Date | null;
+ isLive: boolean;
+ visible: boolean;
+ onExit: () => void;
+}) {
+ const history = useHistory();
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (!props.visible || e.key !== 'Escape' || e.defaultPrevented) return;
+ e.preventDefault();
+ props.onExit();
+ };
+ onMount(() => {
+ document.addEventListener('keydown', onKeyDown);
+ onCleanup(() => document.removeEventListener('keydown', onKeyDown));
+ });
+
+ const currentEditorState = createMemo(() => {
+ if (!props.visible) return undefined;
+ return props.currentState();
+ });
+
+ const targetMs = createMemo<number | undefined>(() => {
+ if (props.isLive) return undefined;
+ return props.selectedAt?.getTime();
+ });
+
+ const previewState = createMemo(() => {
+ if (history.diff.session()) return history.diff.previewState() ?? undefined;
+ if (props.isLive) return currentEditorState();
+ const ms = targetMs();
+ if (ms === undefined) return currentEditorState();
+ return history.checkoutAt(ms) ?? currentEditorState();
+ });
+
+ // Tint inline diff markers with the session author's color
+ const diffAuthorColor = createMemo(() => {
+ const session = history.diff.session();
+ return session ? userColor(session.userId) : undefined;
+ });
+
+ // Hovering a changed run shows who changed it, reusing the scrubber's tag. The
+ // author (a user id) lives on the DiffTextNode's DOM as data-diff-author, so one
+ // delegated handler covers every run — no per-node component bridging Lexical.
+ let rootRef!: HTMLDivElement;
+ const [hoverAuthor, setHoverAuthor] = createSignal<{
+ userId: string;
+ status: DiffStatus | undefined;
+ x: number;
+ y: number;
+ } | null>(null);
+ const onDiffPointerMove = (e: PointerEvent) => {
+ const el = (e.target as HTMLElement | null)?.closest?.<HTMLElement>(
+ '[data-diff-author]'
+ );
+ if (!el) {
+ setHoverAuthor(null);
+ return;
+ }
+ const rect = rootRef.getBoundingClientRect();
+ const rawStatus = el.dataset.diffStatus;
+ setHoverAuthor({
+ userId: el.dataset.diffAuthor ?? 'unknown',
+ status:
+ rawStatus === 'insert' || rawStatus === 'delete'
+ ? rawStatus
+ : undefined,
+ x: e.clientX - rect.left,
+ y: e.clientY - rect.top,
+ });
+ };
+
+ const authorTagLabel = (name: string, status: DiffStatus | undefined) => {
+ if (status === 'delete') return `Deleted by ${name}`;
+ if (status === 'insert') return `Added by ${name}`;
+ return `Edited by ${name}`;
+ };
+
+ return (
+ <div
+ ref={rootRef}
+ class="absolute inset-0 z-20"
+ style={{
+ display: props.visible ? undefined : 'none',
+ '--diff-author': diffAuthorColor(),
+ }}
+ onPointerMove={onDiffPointerMove}
+ onPointerLeave={() => setHoverAuthor(null)}
+ >
+ <div class="absolute inset-y-0 -inset-x-1 -z-10 bg-surface" />
+ <Show keyed when={previewState()}>
+ {(state) => {
+ const config = buildConfig('markdown')
+ .withMentions()
+ .withMedia()
+ .withLinks()
+ .withCode();
+ return (
+ <MarkdownShell
+ config={config}
+ initialState={state}
+ placeholder=""
+ disabled
+ class="ph-no-capture w-full max-w-full pb-20 [&>*:first-child>*:first-child]:mt-0"
+ />
+ );
+ }}
+ </Show>
+ <Show when={hoverAuthor()}>
+ {(hover) => (
+ <UserHoverTag
+ label={authorTagLabel(
+ history.userById(hover().userId).displayName(),
+ hover().status
+ )}
+ color={userColor(hover().userId)}
+ left={Math.max(
+ 0,
+ Math.min((rootRef?.clientWidth ?? 0) - 180, hover().x + 12)
+ )}
+ top={Math.max(0, hover().y - 32)}
+ />
+ )}
+ </Show>
+ </div>
+ );
+}
diff --git a/js/app/packages/block-md/history/HistoryScrubber.tsx b/js/app/packages/block-md/history/HistoryScrubber.tsx
new file mode 100644
index 0000000000..1d5dd6cbdd
--- /dev/null
+++ b/js/app/packages/block-md/history/HistoryScrubber.tsx
@@ -0,0 +1,459 @@
+import type { HistorySession } from '@service-sync/client';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { cn } from '@ui';
+import { group } from 'd3-array';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ on,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { createTimelineScales, type WindowRange } from './createTimelineScales';
+import { useHistory } from './HistoryContext';
+import { buildVolumeShape, VOLUME_BAND_H, type VolumeShape } from './timeline';
+import { UserHoverTag } from './UserHoverTag';
+import { formatTimestamp, userColor } from './utils';
+
+type ScrubberUser = { id: string; displayName: () => string; color: string };
+type ScrubberLane = { user: ScrubberUser; sessions: HistorySession[] };
+const MIN_VIEW = 1;
+const DRAG_THRESHOLD = 4;
+const THUMB_HIT_PX = 12;
+
+export function HistoryScrubber(props: { compact?: boolean }) {
+ const history = useHistory();
+ const sessions = history.sessions;
+ let containerRef!: HTMLDivElement;
+ let hoverLabelRef!: HTMLSpanElement;
+ const size = createElementSize(() => containerRef);
+ const width = () => size.width ?? 0;
+ const [cursorMs, setCursorMs] = createSignal<number | null>(null);
+ const [view, setView] = createSignal<WindowRange | null>(null);
+
+ type Drag =
+ | { mode: 'scrub'; startPx: number }
+ | { mode: 'marquee'; startPx: number; curPx: number };
+ const [drag, setDrag] = createSignal<Drag | null>(null);
+
+ const [hoverPx, setHoverPx] = createSignal<number | null>(null);
+ const [hoverUser, setHoverUser] = createSignal<{
+ user: ScrubberUser;
+ x: number;
+ y: number;
+ } | null>(null);
+ // users (with metadata for displaying them in their tracks)
+ const users = createMemo<ScrubberUser[]>(() => {
+ const ids = [...new Set(sessions().map((session) => session.userId))];
+ return ids.map((id) => ({
+ id,
+ displayName: () => history.userById(id).displayName(),
+ color: userColor(id),
+ }));
+ });
+
+ const lanes = createMemo<ScrubberLane[]>(() => {
+ const byUser = group(sessions(), (session) => session.userId);
+ return users()
+ .filter((user) => byUser.has(user.id))
+ .map((user) => ({ user, sessions: byUser.get(user.id)! }));
+ });
+
+ const {
+ compressedTimeline,
+ visibleWindow,
+ gapMarkers,
+ timestampToWarpedPosition,
+ warpedPositionToTimestamp,
+ containerPositionToWarpedPosition,
+ timestampToContainerPosition,
+ containerPositionToTimestamp,
+ } = createTimelineScales(sessions, width, view);
+
+ const clampView = (start: number, end: number) => {
+ const total = compressedTimeline().total;
+ const span = Math.min(Math.max(MIN_VIEW, end - start), total);
+ let clampedStart = Math.max(0, start);
+ if (clampedStart + span > total) clampedStart = total - span;
+ if (clampedStart < 0) clampedStart = 0;
+ return { start: clampedStart, end: clampedStart + span };
+ };
+
+ // This logic is basically so that we don't update lexical state as they scrub
+ // more often than the screen itself refreshes.
+ let rafId: number | null = null;
+ onCleanup(() => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ });
+ const scheduleSelect = (ms: number) => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ history.enter(new Date(ms));
+ });
+ };
+
+ createEffect(
+ on(history.selectedAt, (selectedDate) => {
+ if (!selectedDate || history.isLive()) return;
+ const warped = timestampToWarpedPosition(selectedDate.getTime());
+ const { start, end } = visibleWindow();
+ if (warped >= start && warped <= end) return;
+ const span = Math.max(end - start, compressedTimeline().total * 0.5);
+ setView(clampView(warped - span / 2, warped + span / 2));
+ })
+ );
+
+ createEffect(
+ on(
+ history.diff.session,
+ (session) => {
+ if (!session) {
+ // Only zoom back out when the diff is truly dismissed (back to live).
+ // Scrubbing to a timestamp also clears the session — don't yank the
+ // zoom out from under the user in that case.
+ if (history.isLive()) {
+ setView({ start: 0, end: compressedTimeline().total });
+ }
+ return;
+ }
+ const warpStart = timestampToWarpedPosition(session.startMs);
+ const warpEnd = timestampToWarpedPosition(session.endMs);
+ const sessionSpan = warpEnd - warpStart;
+ const padding = Math.max(
+ sessionSpan * 0.5,
+ compressedTimeline().total * 0.02
+ );
+ setView(clampView(warpStart - padding, warpEnd + padding));
+ },
+ { defer: true }
+ )
+ );
+
+ // Exiting history drops any scrub/marquee zoom so the next open starts from
+ // the full range. A null view falls back to the full window in the scales.
+ createEffect(
+ on(
+ history.isOpen,
+ (open) => {
+ if (!open) setView(null);
+ },
+ { defer: true }
+ )
+ );
+
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ const { start, end } = visibleWindow();
+ const delta =
+ Math.abs(e.deltaX) >= Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
+ if (delta === 0) return;
+ const shift = (delta / Math.max(1, width())) * (end - start);
+ setView(clampView(start + shift, end + shift));
+ };
+
+ // Converts page clientX to a pixel offset within the container, clamped to [0, width].
+ // Clamping keeps coords valid during pointer capture when the pointer drifts outside.
+ const localPx = (clientX: number) => {
+ const rect = containerRef.getBoundingClientRect();
+ return Math.min(Math.max(0, clientX - rect.left), rect.width);
+ };
+
+ const localY = (clientY: number) =>
+ clientY - containerRef.getBoundingClientRect().top;
+
+ // Converts a pixel offset to a real timestamp: pixel → warped coord → ms.
+ const placeAt = (pointerPx: number) => {
+ if (width() - pointerPx <= THUMB_HIT_PX) {
+ setCursorMs(null);
+ history.enter();
+ return;
+ }
+ const ms = containerPositionToTimestamp(pointerPx);
+ setCursorMs(ms);
+ history.enter(new Date(ms));
+ };
+
+ const thumbPx = createMemo<number | null>(() => {
+ if (!history.isOpen()) return null;
+ if (history.isLive()) return width();
+ const cursor =
+ drag()?.mode === 'scrub'
+ ? cursorMs()
+ : (history.selectedAt()?.getTime() ?? cursorMs());
+ if (cursor === null) return null;
+ const totalWidth = width();
+ const candidatePx = timestampToContainerPosition(cursor);
+ return candidatePx < -0.5 || candidatePx > totalWidth + 0.5
+ ? null
+ : candidatePx;
+ });
+
+ const onPointerDown = (e: PointerEvent) => {
+ containerRef.setPointerCapture(e.pointerId);
+ setHoverPx(null);
+ history.open();
+ const pointerPx = localPx(e.clientX);
+ const thumbPosition = thumbPx();
+ if (
+ thumbPosition !== null &&
+ Math.abs(pointerPx - thumbPosition) <= THUMB_HIT_PX
+ ) {
+ setDrag({ mode: 'scrub', startPx: pointerPx });
+ } else {
+ setDrag({ mode: 'marquee', startPx: pointerPx, curPx: pointerPx });
+ }
+ };
+
+ const onPointerMove = (e: PointerEvent) => {
+ const pointerPx = localPx(e.clientX);
+ const activeDrag = drag();
+ if (!activeDrag) {
+ setHoverPx(pointerPx);
+ return;
+ }
+ if (activeDrag.mode === 'scrub') {
+ const ms = containerPositionToTimestamp(pointerPx);
+ setCursorMs(ms);
+ scheduleSelect(ms);
+ } else {
+ setDrag({ ...activeDrag, curPx: pointerPx });
+ }
+ };
+
+ const onPointerUp = (e: PointerEvent) => {
+ const activeDrag = drag();
+ if (!activeDrag) return;
+ setDrag(null);
+ if (compressedTimeline().intervals.length === 0) return;
+ const pointerPx = localPx(e.clientX);
+ if (activeDrag.mode === 'scrub') {
+ // User was dragging the thumb — commit the cursor position.
+ placeAt(pointerPx);
+ return;
+ }
+ if (Math.abs(activeDrag.curPx - activeDrag.startPx) > DRAG_THRESHOLD) {
+ const warpLeft = containerPositionToWarpedPosition(
+ Math.min(activeDrag.startPx, activeDrag.curPx)
+ );
+ const warpRight = containerPositionToWarpedPosition(
+ Math.max(activeDrag.startPx, activeDrag.curPx)
+ );
+ const padding = (warpRight - warpLeft) * 0.2;
+ setView(clampView(warpLeft - padding, warpRight + padding));
+ } else {
+ placeAt(pointerPx);
+ }
+ };
+
+ // The active marquee drag, but only once it has crossed DRAG_THRESHOLD pixels —
+ // used to render the selection box highlight while the user is drawing a zoom selection.
+ const marquee = createMemo<Extract<Drag, { mode: 'marquee' }> | null>(() => {
+ const activeDrag = drag();
+ return activeDrag?.mode === 'marquee' &&
+ Math.abs(activeDrag.curPx - activeDrag.startPx) > DRAG_THRESHOLD
+ ? activeDrag
+ : null;
+ });
+
+ const volume = createMemo<VolumeShape | null>(() =>
+ buildVolumeShape(sessions(), timestampToContainerPosition, width())
+ );
+
+ return (
+ <div
+ class={cn(
+ 'flex w-full min-w-0 items-start gap-4',
+ props.compact && 'flex-col items-stretch gap-6'
+ )}
+ >
+ <div
+ ref={containerRef}
+ class={cn(
+ 'relative isolate min-w-0 flex-1 touch-none select-none',
+ props.compact ? 'mb-2' : 'mb-4',
+ props.compact ? 'mx-0 w-full' : 'mx-6'
+ )}
+ style={{
+ cursor:
+ drag()?.mode === 'scrub'
+ ? 'grabbing'
+ : thumbPx() !== null &&
+ hoverPx() !== null &&
+ Math.abs(hoverPx()! - thumbPx()!) <= THUMB_HIT_PX
+ ? 'grab'
+ : 'crosshair',
+ }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerLeave={() => {
+ setHoverPx(null);
+ setHoverUser(null);
+ }}
+ onWheel={onWheel}
+ onDblClick={() =>
+ setView({ start: 0, end: compressedTimeline().total })
+ }
+ >
+ {/* Background activity meter */}
+ <Show when={volume()}>
+ {(vol) => (
+ <svg
+ class="pointer-events-none absolute inset-0 -z-10 size-full text-ink-muted"
+ preserveAspectRatio="none"
+ viewBox={`0 0 ${width()} ${VOLUME_BAND_H}`}
+ aria-hidden="true"
+ >
+ <path d={vol().area} fill="currentColor" class="opacity-[0.08]" />
+ <path
+ d={vol().line}
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1"
+ vector-effect="non-scaling-stroke"
+ class="opacity-25"
+ />
+ </svg>
+ )}
+ </Show>
+
+ {/* Hover preview line + date label */}
+ <Show when={hoverPx() !== null && drag() === null}>
+ <div
+ class="pointer-events-none absolute inset-y-0 z-10 w-px bg-accent/30"
+ style={{ left: `${hoverPx() ?? 0}px` }}
+ />
+ <span
+ ref={hoverLabelRef}
+ class="pointer-events-none absolute top-full z-10 -translate-x-1/2 whitespace-nowrap rounded bg-surface px-1 text-[10px] text-ink"
+ style={{
+ left: `${Math.max((hoverLabelRef?.offsetWidth ?? 0) / 2, Math.min(hoverPx()!, width() - (hoverLabelRef?.offsetWidth ?? 0) / 2))}px`,
+ }}
+ >
+ {formatTimestamp(
+ new Date(containerPositionToTimestamp(hoverPx()!))
+ )}
+ </span>
+ </Show>
+
+ {/* Rail */}
+ <div class="relative h-12 overflow-hidden">
+ <div class="absolute inset-x-0 top-1/2 h-0.5 -translate-y-1/2 rounded bg-edge" />
+ <For each={gapMarkers()}>
+ {(marker) => (
+ <div
+ class="absolute inset-y-0 flex items-center justify-center overflow-hidden whitespace-nowrap text-[10px] text-ink-muted"
+ style={{ left: `${marker.left}px`, width: `${marker.width}px` }}
+ >
+ {`·· ${marker.label} ··`}
+ </div>
+ )}
+ </For>
+ {/* Marquee zoom selection */}
+ <Show when={marquee()}>
+ {(activeMarquee) => (
+ <div
+ class="absolute inset-y-0 z-10 border-accent border-x bg-accent/20"
+ style={{
+ left: `${Math.min(activeMarquee().startPx, activeMarquee().curPx)}px`,
+ width: `${Math.abs(activeMarquee().curPx - activeMarquee().startPx)}px`,
+ }}
+ />
+ )}
+ </Show>
+ {/* Diamond thumb */}
+ <Show when={thumbPx() !== null}>
+ <div
+ class="pointer-events-none absolute top-1/2 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center"
+ style={{ left: `${thumbPx()!}px` }}
+ >
+ <div class="size-3.5 rotate-45 bg-accent shadow" />
+ </div>
+ </Show>
+ </div>
+
+ {/* Per-user session lanes */}
+ <div class="flex flex-col gap-0.5">
+ <For each={lanes()}>
+ {(lane) => (
+ <div class="relative h-1 overflow-hidden rounded-full">
+ <div class="absolute inset-x-0 top-1/2 h-px -translate-y-1/2 bg-edge/60" />
+ <For each={lane.sessions}>
+ {(session) => {
+ const left = () =>
+ timestampToContainerPosition(session.startMs);
+ const right = () =>
+ timestampToContainerPosition(session.endMs);
+ return (
+ <div
+ class="absolute inset-y-0 cursor-pointer rounded-full"
+ // Stop the rail's scrub/marquee drag from starting so a
+ // bar click cleanly opens that session's diff.
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={() => {
+ if (
+ history.diff.session()?.startMs === session.startMs
+ ) {
+ history.diff.clear();
+ } else {
+ history.diff.view(session);
+ }
+ }}
+ onPointerEnter={(e) =>
+ setHoverUser({
+ user: lane.user,
+ x: localPx(e.clientX),
+ y: localY(e.clientY),
+ })
+ }
+ onPointerMove={(e) =>
+ setHoverUser({
+ user: lane.user,
+ x: localPx(e.clientX),
+ y: localY(e.clientY),
+ })
+ }
+ onPointerLeave={() => setHoverUser(null)}
+ style={{
+ left: `${left()}px`,
+ width: `${Math.max(3, right() - left())}px`,
+ background: lane.user.color,
+ }}
+ />
+ );
+ }}
+ </For>
+ </div>
+ )}
+ </For>
+ </div>
+
+ <Show when={hoverUser()}>
+ {(hover) => (
+ <UserHoverTag
+ label={hover().user.displayName()}
+ color={hover().user.color}
+ left={Math.max(0, Math.min(width() - 160, hover().x + 10))}
+ top={Math.max(0, hover().y - 30)}
+ />
+ )}
+ </Show>
+
+ {/* Edge time labels */}
+ <span class="absolute top-full left-0 text-[10px] text-ink-muted">
+ {formatTimestamp(
+ new Date(warpedPositionToTimestamp(visibleWindow().start))
+ )}
+ </span>
+ <span class="absolute top-full right-0 text-[10px] text-ink-muted">
+ {formatTimestamp(
+ new Date(warpedPositionToTimestamp(visibleWindow().end))
+ )}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/block-md/history/HistorySessionList.tsx b/js/app/packages/block-md/history/HistorySessionList.tsx
new file mode 100644
index 0000000000..2192478ac8
--- /dev/null
+++ b/js/app/packages/block-md/history/HistorySessionList.tsx
@@ -0,0 +1,108 @@
+import { tryMacroId, useDisplayNameParts } from '@core/user';
+import type { HistorySession } from '@service-sync/client';
+import { cn } from '@ui';
+import { type Accessor, createMemo, For, Show } from 'solid-js';
+import { buildActivityRows } from './activityRows';
+import { userColor } from './utils';
+
+type HistorySessionListProps = {
+ sessions: readonly HistorySession[];
+ selectedAt: Accessor<Date | null>;
+ onSelect: (at?: Date) => void;
+ onViewSessionDiff?: (session: HistorySession) => void;
+};
+
+function UserName(props: { userId: string }) {
+ const { firstName } = useDisplayNameParts(tryMacroId(props.userId));
+ return <>{firstName()}</>;
+}
+
+const MAX_NAMED = 3;
+
+function UserList(props: { userIds: readonly string[] }) {
+ const visible = () => props.userIds.slice(0, MAX_NAMED);
+ const overflow = () => props.userIds.length - MAX_NAMED;
+ return (
+ <>
+ <For each={visible()}>
+ {(userId, index) => (
+ <>
+ <Show when={index() > 0}>
+ {index() === visible().length - 1 && overflow() <= 0
+ ? ' and '
+ : ', '}
+ </Show>
+ <UserName userId={userId} />
+ </>
+ )}
+ </For>
+ <Show when={overflow() > 0}>
+ {` and ${overflow()} ${overflow() === 1 ? 'other' : 'others'}`}
+ </Show>
+ </>
+ );
+}
+
+export function HistorySessionList(props: HistorySessionListProps) {
+ const rows = createMemo(() => buildActivityRows(props.sessions));
+
+ const selectedMs = () => props.selectedAt()?.getTime() ?? null;
+
+ return (
+ <Show when={rows().length > 0}>
+ <div class="mt-2 min-w-0">
+ <div class="min-h-0 space-y-1 pr-1">
+ <For each={rows()}>
+ {(row) => {
+ const isSelected = () => selectedMs() === row.endMs;
+ const edits = () =>
+ `${row.count} ${row.count === 1 ? 'edit' : 'edits'}`;
+ return (
+ <button
+ type="button"
+ class={cn(
+ 'flex w-full min-w-0 items-start gap-2 rounded-md px-2 py-1.5 text-left hover:bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40',
+ isSelected() && 'bg-active text-ink'
+ )}
+ onClick={() => {
+ if (props.onViewSessionDiff) {
+ // A row aggregates a burst of activity; diff its whole
+ // time range, tinted by its lead editor.
+ props.onViewSessionDiff({
+ userId: row.userIds[0] ?? 'unknown',
+ startMs: row.startMs,
+ endMs: row.endMs,
+ count: row.count,
+ });
+ } else {
+ props.onSelect(new Date(row.endMs));
+ }
+ }}
+ >
+ <span class="flex w-4 shrink-0 items-center -space-x-1 mt-[3px]">
+ <For each={row.userIds.slice(0, MAX_NAMED)}>
+ {(userId) => (
+ <span
+ class="size-2 rounded-full ring-1 ring-surface"
+ style={{ 'background-color': userColor(userId) }}
+ />
+ )}
+ </For>
+ </span>
+ <span class="min-w-0 flex-1">
+ <span class="block text-ink text-xs">
+ <UserList userIds={row.userIds} /> edited {row.label}
+ </span>
+ <span class="block text-ink-muted text-[11px]">
+ {edits()}
+ </span>
+ </span>
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ </Show>
+ );
+}
diff --git a/js/app/packages/block-md/history/OldOverlay.tsx b/js/app/packages/block-md/history/OldOverlay.tsx
new file mode 100644
index 0000000000..a359b77aa4
--- /dev/null
+++ b/js/app/packages/block-md/history/OldOverlay.tsx
@@ -0,0 +1,73 @@
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import { useBlockId } from '@core/block';
+import { toast } from '@core/component/Toast/Toast';
+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
+import GitFork from '@phosphor-icons/core/regular/git-fork.svg?component-solid';
+import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
+import { storageServiceClient } from '@service-storage/client';
+import { Button, Hotkey } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { useHistory } from './HistoryContext';
+
+const nameForkedDocument = (name: string) => `${name} (forked)`;
+
+export function OldOverlay() {
+ const history = useHistory();
+ const blockId = useBlockId();
+ const documentName = useBlockDocumentName();
+ const { insertSplit } = useSplitLayout();
+ const [forking, setForking] = createSignal(false);
+
+ const handleFork = async () => {
+ if (forking()) return;
+ const ms = history.selectedAt()?.getTime();
+ const vid = history.isLive()
+ ? undefined
+ : ms
+ ? (history.versionIdAt(ms) ?? undefined)
+ : undefined;
+ if (!history.isLive() && !vid) return;
+ setForking(true);
+ const res = await storageServiceClient.copyDocument({
+ documentId: blockId,
+ documentName: nameForkedDocument(documentName() ?? ''),
+ syncServiceVersion: vid,
+ });
+ setForking(false);
+ if (res.isErr()) {
+ toast.failure('Failed to fork document');
+ return;
+ }
+ insertSplit({ type: 'md', id: res.value.documentId }, 'fork');
+ history.exit();
+ };
+
+ return (
+ <Show when={history.isOpen()}>
+ <div class="flex w-full items-center gap-2 bg-alert-bg px-3 py-2 text-xs text-alert-ink">
+ <span class="flex items-center gap-1 flex-1">
+ You are viewing history. Press{' '}
+ <Hotkey shortcut="escape" theme="current" /> to exit.
+ </span>
+ <Button variant="base" size="sm" onClick={history.exit}>
+ <XIcon />
+ Exit
+ </Button>
+ <Button
+ variant="active"
+ size="sm"
+ onClick={handleFork}
+ disabled={
+ forking() ||
+ (!history.isLive() &&
+ (history.loading.doc() ||
+ !history.versionIdAt(history.selectedAt()?.getTime() ?? 0)))
+ }
+ >
+ <GitFork class="size-3.5 shrink-0" />
+ {forking() ? 'Forking…' : 'Fork'}
+ </Button>
+ </div>
+ </Show>
+ );
+}
diff --git a/js/app/packages/block-md/history/UserHoverTag.tsx b/js/app/packages/block-md/history/UserHoverTag.tsx
new file mode 100644
index 0000000000..bcec38a1cf
--- /dev/null
+++ b/js/app/packages/block-md/history/UserHoverTag.tsx
@@ -0,0 +1,23 @@
+// A small floating tag: a user's accent dot + a label. Shared by the timeline
+// scrubber (hovering a session lane) and the diff overlay (hovering changed text),
+// so both surfaces show identical "who" affordances. Positioned absolutely within
+// the caller's relatively-positioned container.
+export function UserHoverTag(props: {
+ label: string;
+ color: string;
+ left: number;
+ top: number;
+}) {
+ return (
+ <div
+ class="pointer-events-none absolute z-30 flex items-center gap-1.5 rounded-md bg-surface px-2 py-1 text-ink text-xs shadow-lg ring-1 ring-edge-muted"
+ style={{ left: `${props.left}px`, top: `${props.top}px` }}
+ >
+ <span
+ class="size-2 shrink-0 rounded-full"
+ style={{ background: props.color }}
+ />
+ <span class="max-w-40 truncate">{props.label}</span>
+ </div>
+ );
+}
diff --git a/js/app/packages/block-md/history/activityRows.test.ts b/js/app/packages/block-md/history/activityRows.test.ts
new file mode 100644
index 0000000000..106e32d8c5
--- /dev/null
+++ b/js/app/packages/block-md/history/activityRows.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+import { type ActivitySession, buildActivityRows } from './activityRows';
+
+const MINUTE = 60 * 1000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+const _WEEK = 7 * DAY;
+const NOW = new Date('2026-06-25T12:00:00Z').getTime();
+
+function session(
+ userId: string,
+ endAgoMs: number,
+ durationMs = MINUTE,
+ count = 1
+): ActivitySession {
+ const endMs = NOW - endAgoMs;
+ return { userId, startMs: endMs - durationMs, endMs, count };
+}
+
+describe('buildActivityRows', () => {
+ it('groups recent edits from multiple users into the same progressive tier', () => {
+ const rows = buildActivityRows(
+ [session('wolf', 2 * MINUTE), session('bob', 6 * MINUTE)],
+ NOW
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].userIds).toEqual(['wolf', 'bob']);
+ expect(rows[0].label).toBe('2 minutes ago');
+ });
+
+ it('skips empty tiers and groups older users by their broader tier', () => {
+ const rows = buildActivityRows(
+ [
+ session('bob', 2 * DAY),
+ session('sarah', 2 * DAY + HOUR),
+ session('joseph', 2 * DAY + 2 * HOUR),
+ ],
+ NOW
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].userIds).toEqual(['bob', 'sarah', 'joseph']);
+ expect(rows[0].label).toBe('2 days ago');
+ });
+
+ it('splits rows when active span exceeds the tier max span', () => {
+ const rows = buildActivityRows(
+ [session('wolf', 12 * MINUTE), session('bob', 55 * MINUTE, 20 * MINUTE)],
+ NOW
+ );
+
+ expect(rows).toHaveLength(2);
+ expect(rows[0].userIds).toEqual(['wolf']);
+ expect(rows[1].userIds).toEqual(['bob']);
+ });
+});
diff --git a/js/app/packages/block-md/history/activityRows.ts b/js/app/packages/block-md/history/activityRows.ts
new file mode 100644
index 0000000000..cf02bcec1a
--- /dev/null
+++ b/js/app/packages/block-md/history/activityRows.ts
@@ -0,0 +1,163 @@
+export type ActivitySession = {
+ userId: string;
+ startMs: number;
+ endMs: number;
+ count: number;
+};
+
+export type ActivityRow = {
+ userIds: string[];
+ startMs: number;
+ endMs: number;
+ count: number;
+ label: string;
+};
+
+// Algorithm for bucketing:
+//
+// 1. Sort sessions newest-first (by endMs, then startMs).
+// 2. Bucket each session into an age tier by how long ago its endMs was.
+// Tiers widen as they get older (last 10 min, last hour, last day, ...).
+// Great, we have a bunch of bucketed sessions now. Let's cluster within
+// sessions.
+// 3. Within each tier, walk newest->oldest and accumulate sessions into a
+// group while the group's total span (newest end − oldest start) stays
+// under that tier's maxActiveSpanMs. When adding one would exceed it,
+// emit the group as a row and start a new group. Coarser tiers tolerate
+// wider spans, so old activity is grouped more loosely than recent.
+// 4. Sessions older than the last tier collapse into a single trailing row.
+// 5. Emit each group as a summarized row with a relative label.
+
+const MINUTE_MS = 60 * 1000;
+const HOUR_MS = 60 * MINUTE_MS;
+const DAY_MS = 24 * HOUR_MS;
+const WEEK_MS = 7 * DAY_MS;
+const MONTH_MS = 30 * DAY_MS;
+const YEAR_MS = 365 * DAY_MS;
+
+// these "feel right" but we can change it
+const ACTIVITY_TIERS = [
+ { boundaryMs: 10 * MINUTE_MS, maxActiveSpanMs: 10 * MINUTE_MS },
+ { boundaryMs: HOUR_MS, maxActiveSpanMs: HOUR_MS },
+ { boundaryMs: DAY_MS, maxActiveSpanMs: 4 * HOUR_MS },
+ { boundaryMs: 3 * DAY_MS, maxActiveSpanMs: 8 * HOUR_MS },
+ { boundaryMs: WEEK_MS, maxActiveSpanMs: DAY_MS },
+ { boundaryMs: 2 * WEEK_MS, maxActiveSpanMs: 2 * DAY_MS },
+ { boundaryMs: MONTH_MS, maxActiveSpanMs: 3 * DAY_MS },
+ { boundaryMs: 6 * MONTH_MS, maxActiveSpanMs: WEEK_MS },
+ { boundaryMs: 2 * YEAR_MS, maxActiveSpanMs: MONTH_MS },
+] as const;
+
+function activityLabel(endMs: number, nowMs: number) {
+ const ageMs = Math.max(0, nowMs - endMs);
+ if (ageMs < MINUTE_MS) return 'just now';
+ if (ageMs < HOUR_MS) {
+ const minutes = Math.max(1, Math.floor(ageMs / MINUTE_MS));
+ return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'} ago`;
+ }
+ if (ageMs < DAY_MS) {
+ const hours = Math.max(1, Math.floor(ageMs / HOUR_MS));
+ return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
+ }
+ if (ageMs < WEEK_MS) {
+ const days = Math.max(1, Math.floor(ageMs / DAY_MS));
+ return days === 1 ? 'yesterday' : `${days} days ago`;
+ }
+ const weeks = Math.max(1, Math.floor(ageMs / WEEK_MS));
+ if (ageMs < 8 * WEEK_MS) {
+ return weeks === 1 ? 'last week' : `${weeks} weeks ago`;
+ }
+
+ const date = new Date(endMs);
+ return date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ });
+}
+
+function createRow(
+ sessions: readonly ActivitySession[],
+ nowMs: number
+): ActivityRow {
+ const userIds: string[] = [];
+ let startMs = Number.POSITIVE_INFINITY;
+ let endMs = 0;
+ let count = 0;
+
+ for (const session of sessions) {
+ if (!userIds.includes(session.userId)) userIds.push(session.userId);
+ startMs = Math.min(startMs, session.startMs);
+ endMs = Math.max(endMs, session.endMs);
+ count += session.count;
+ }
+
+ return {
+ userIds,
+ startMs,
+ endMs,
+ count,
+ label: activityLabel(endMs, nowMs),
+ };
+}
+
+export function buildActivityRows(
+ sessions: readonly ActivitySession[],
+ nowMs: number = Date.now()
+): ActivityRow[] {
+ const sorted = [...sessions].sort(
+ (a, b) => b.endMs - a.endMs || b.startMs - a.startMs
+ );
+ const rows: ActivityRow[] = [];
+ let cursor = 0;
+ let previousBoundaryMs = nowMs;
+
+ for (const tier of ACTIVITY_TIERS) {
+ const tierBoundaryMs = nowMs - tier.boundaryMs;
+ const tierSessions: ActivitySession[] = [];
+
+ while (cursor < sorted.length) {
+ const session = sorted[cursor];
+ if (session.endMs > previousBoundaryMs) {
+ cursor++;
+ continue;
+ }
+ if (session.endMs <= tierBoundaryMs) break;
+ tierSessions.push(session);
+ cursor++;
+ }
+
+ let group: ActivitySession[] = [];
+ for (const session of tierSessions) {
+ if (group.length === 0) {
+ group = [session];
+ continue;
+ }
+
+ const groupEndMs = Math.max(...group.map((item) => item.endMs));
+ const nextStartMs = Math.min(
+ session.startMs,
+ ...group.map((item) => item.startMs)
+ );
+ if (groupEndMs - nextStartMs > tier.maxActiveSpanMs) {
+ rows.push(createRow(group, nowMs));
+ group = [session];
+ } else {
+ group.push(session);
+ }
+ }
+
+ if (group.length > 0) {
+ rows.push(createRow(group, nowMs));
+ }
+
+ previousBoundaryMs = tierBoundaryMs;
+ }
+
+ if (cursor < sorted.length) {
+ const remaining = sorted.slice(cursor);
+ rows.push(createRow(remaining, nowMs));
+ }
+
+ return rows;
+}
diff --git a/js/app/packages/block-md/history/createTimelineScales.ts b/js/app/packages/block-md/history/createTimelineScales.ts
new file mode 100644
index 0000000000..303d81007c
--- /dev/null
+++ b/js/app/packages/block-md/history/createTimelineScales.ts
@@ -0,0 +1,129 @@
+import { type ScaleLinear, scaleLinear } from 'd3-scale';
+import { createMemo } from 'solid-js';
+import {
+ buildCompressedTimeline,
+ type CompressedTimeline,
+ warpedIntervalEnd,
+} from './timeline';
+import { humanizeDuration } from './utils';
+
+export type WindowRange = { start: number; end: number };
+export type GapMarker = { left: number; width: number; label: string };
+
+// Custom hook that owns all the coordinate math for the timeline scrubber.
+// Accepts reactive inputs and returns stable function references backed by memos.
+//
+// Coordinate pipeline:
+// real timestamp (ms)
+// -> warped position [warpScale: compresses gap dead time logarithmically]
+// -> container position [containerXScale: maps the visible window onto [0, width]]
+export function createTimelineScales(
+ sessions: () => readonly { startMs: number; endMs: number }[],
+ width: () => number,
+ view: () => WindowRange | null,
+ gapMarkerMinPx = 36
+) {
+ const compressedTimeline = createMemo<CompressedTimeline>(() =>
+ buildCompressedTimeline(sessions())
+ );
+
+ // Maps real timestamps to warped coordinates. We feed d3 the start and end of
+ // each activity block as alternating domain/range pairs, d3 handles the rest
+ // by interpolating linearly within each block (given a real timestamp, it
+ // will put it into this new scale at a corresponding position). The gaps
+ // between blocks simply don't appear in the domain, so they get compressed
+ // away. .clamp(true) snaps any timestamp that falls in a gap to the nearest
+ // block edge.
+ const warpScale = createMemo<ScaleLinear<number, number>>(() => {
+ const { intervals } = compressedTimeline();
+ if (intervals.length === 0)
+ return scaleLinear().domain([0, 1]).range([0, 0]);
+ return scaleLinear()
+ .domain(
+ intervals.flatMap((interval) => [interval.startMs, interval.endMs])
+ )
+ .range(
+ intervals.flatMap((interval) => [
+ interval.warpStart,
+ warpedIntervalEnd(interval),
+ ])
+ )
+ .clamp(true);
+ });
+
+ const timestampToWarpedPosition = (ms: number): number => warpScale()(ms);
+ const warpedPositionToTimestamp = (warped: number): number => {
+ const ms = warpScale().invert(warped);
+ return Number.isNaN(ms) ? 0 : ms;
+ };
+
+ const defaultWindow = createMemo<WindowRange>(() => {
+ const { total } = compressedTimeline();
+ return { start: 0, end: Math.max(1, total) };
+ });
+
+ const visibleWindow = createMemo<WindowRange>(
+ () => view() ?? defaultWindow()
+ );
+
+ const containerXScale = createMemo<ScaleLinear<number, number>>(() =>
+ scaleLinear()
+ .domain([visibleWindow().start, visibleWindow().end])
+ .range([0, Math.max(1, width())])
+ );
+
+ const warpedPositionToContainerPosition = (warped: number) =>
+ containerXScale()(warped);
+ const containerPositionToWarpedPosition = (px: number) =>
+ containerXScale().invert(px);
+
+ // Full pipeline: timestamp → warped position → container position.
+ const timestampToContainerPosition = (ms: number) =>
+ warpedPositionToContainerPosition(timestampToWarpedPosition(ms));
+ // Full pipeline: container position → warped position → timestamp.
+ const containerPositionToTimestamp = (px: number) =>
+ warpedPositionToTimestamp(containerPositionToWarpedPosition(px));
+
+ const gapMarkers = createMemo<GapMarker[]>(() => {
+ const totalWidth = width();
+ const { intervals } = compressedTimeline();
+ const out: GapMarker[] = [];
+ for (let i = 1; i < intervals.length; i++) {
+ const prev = intervals[i - 1];
+ const cur = intervals[i];
+ const left = warpedPositionToContainerPosition(warpedIntervalEnd(prev));
+ const right = warpedPositionToContainerPosition(cur.warpStart);
+ if (right < 0 || left > totalWidth) continue;
+ const markerWidth = right - left;
+ if (markerWidth < gapMarkerMinPx) continue;
+ out.push({
+ left,
+ width: markerWidth,
+ label: humanizeDuration(cur.startMs - prev.endMs),
+ });
+ }
+ return out;
+ });
+
+ return {
+ /** Merged + warped session intervals. Source of truth for all coordinate math. */
+ compressedTimeline,
+ /** The slice of the timeline currently on screen, in warped coordinates. Defaults to
+ * the last DEFAULT_SESSIONS blocks; updated when the user pans or zooms. */
+ visibleWindow,
+ /** Gap labels between activity blocks, pre-filtered to those wide enough to display. */
+ gapMarkers,
+ /** Real timestamp (ms) → warped position. */
+ timestampToWarpedPosition,
+ /** Warped position → real timestamp (ms). Inverse of the warp compression. */
+ warpedPositionToTimestamp,
+ /** Warped position → screen pixel within the container. */
+ warpedPositionToContainerPosition,
+ /** Screen pixel → warped position. */
+ containerPositionToWarpedPosition,
+ /** Real timestamp (ms) → screen pixel. Full two-step pipeline. */
+ timestampToContainerPosition,
+ /** Screen pixel → real timestamp (ms). Full two-step pipeline. */
+ containerPositionToTimestamp,
+ };
+}
diff --git a/js/app/packages/block-md/history/sessionize.test.ts b/js/app/packages/block-md/history/sessionize.test.ts
new file mode 100644
index 0000000000..94537cfed4
--- /dev/null
+++ b/js/app/packages/block-md/history/sessionize.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import {
+ BOGUS_BLANK_MARKDOWN_GOLDEN_SNAPSHOT_HISTORY_MS as GOLDEN_MS,
+ sessionize,
+} from './sessionize';
+
+const GAP = 100;
+const ev = (userId: string, tMs: number) => ({ userId, tMs });
+
+describe('sessionize', () => {
+ it('empty', () => {
+ expect(sessionize([], GAP)).toEqual([]);
+ });
+
+ it('single event', () => {
+ expect(sessionize([ev('a', 1000)], GAP)).toEqual([
+ { userId: 'a', startMs: 1000, endMs: 1000, count: 1 },
+ ]);
+ });
+
+ it('two within gap merge into one session', () => {
+ const sessions = sessionize([ev('a', 1000), ev('a', 1050)], GAP);
+ expect(sessions).toHaveLength(1);
+ expect(sessions[0]).toMatchObject({ startMs: 1000, endMs: 1050, count: 2 });
+ });
+
+ it('two beyond gap split, most recent first', () => {
+ const sessions = sessionize([ev('a', 1000), ev('a', 1200)], GAP);
+ expect(sessions).toHaveLength(2);
+ expect(sessions[0]).toMatchObject({ startMs: 1200, count: 1 });
+ expect(sessions[1]).toMatchObject({ startMs: 1000, count: 1 });
+ });
+
+ it('unsorted input grouped correctly', () => {
+ const sessions = sessionize(
+ [ev('a', 1050), ev('a', 1000), ev('a', 1025)],
+ GAP
+ );
+ expect(sessions).toHaveLength(1);
+ expect(sessions[0]).toMatchObject({ startMs: 1000, endMs: 1050, count: 3 });
+ });
+
+ it('multiple users', () => {
+ const sessions = sessionize(
+ [
+ ev('a', 9000),
+ ev('b', 5000),
+ ev('a', 1050),
+ ev('b', 1010),
+ ev('a', 1000),
+ ],
+ GAP
+ );
+ expect(sessions).toHaveLength(4);
+ expect(sessions[0]).toMatchObject({ endMs: 9000, userId: 'a' });
+ expect(sessions[1]).toMatchObject({ endMs: 5000, userId: 'b' });
+ const aOld = sessions.find((s) => s.userId === 'a' && s.startMs === 1000);
+ expect(aOld).toMatchObject({ endMs: 1050, count: 2 });
+ });
+
+ it('filters the lone bogus golden-snapshot session', () => {
+ const sessions = sessionize([ev('a', GOLDEN_MS)], GAP);
+ expect(sessions).toEqual([]);
+ });
+});
diff --git a/js/app/packages/block-md/history/sessionize.ts b/js/app/packages/block-md/history/sessionize.ts
new file mode 100644
index 0000000000..37aaec129b
--- /dev/null
+++ b/js/app/packages/block-md/history/sessionize.ts
@@ -0,0 +1,67 @@
+import type { HistorySession } from '@service-sync/client';
+
+/** Largest gap in ms between consecutive edits that still counts as one session. */
+export const SESSION_GAP_MS = 10 * 60 * 1000;
+
+/**
+ * The blank-markdown golden snapshot seeds every fresh document with one bogus
+ * change at this fixed timestamp (ms). Filtered out so it never shows as a real
+ * editing session.
+ */
+export const BOGUS_BLANK_MARKDOWN_GOLDEN_SNAPSHOT_HISTORY_MS = 1780516229000;
+
+type EditEvent = { userId: string; tMs: number };
+
+/**
+ * Group `(userId, timestampMs)` events into per-user sessions. Within a user,
+ * consecutive edits more than `gapMs` apart start a new session. Returns all
+ * sessions sorted most-recent first (`endMs` desc).
+ * Sessions may overlap across users editing at the same time.
+ */
+export function sessionize(
+ events: readonly EditEvent[],
+ gapMs: number = SESSION_GAP_MS
+): HistorySession[] {
+ const byUser = new Map<string, number[]>();
+ for (const { userId, tMs } of events) {
+ const list = byUser.get(userId);
+ if (list) list.push(tMs);
+ else byUser.set(userId, [tMs]);
+ }
+
+ const sessions: HistorySession[] = [];
+ for (const [userId, editTimes] of byUser) {
+ editTimes.sort((a, b) => a - b); // oldest to newest
+ let start = editTimes[0];
+ let end = editTimes[0];
+ let count = 1;
+ for (let i = 1; i < editTimes.length; i++) {
+ const t = editTimes[i];
+ if (t - end > gapMs) {
+ sessions.push({ userId, startMs: start, endMs: end, count });
+ start = t;
+ count = 0;
+ }
+ end = t;
+ count += 1;
+ }
+ sessions.push({ userId, startMs: start, endMs: end, count });
+ }
+
+ sessions.sort(
+ (a, b) =>
+ b.endMs - a.endMs ||
+ b.startMs - a.startMs ||
+ (a.userId < b.userId ? -1 : a.userId > b.userId ? 1 : 0)
+ );
+
+ // Hide the known blank golden-snapshot session while preserving real sessions.
+ return sessions.filter(
+ (s) =>
+ !(
+ s.startMs === BOGUS_BLANK_MARKDOWN_GOLDEN_SNAPSHOT_HISTORY_MS &&
+ s.endMs === BOGUS_BLANK_MARKDOWN_GOLDEN_SNAPSHOT_HISTORY_MS &&
+ s.count === 1
+ )
+ );
+}
diff --git a/js/app/packages/block-md/history/timeline.test.ts b/js/app/packages/block-md/history/timeline.test.ts
new file mode 100644
index 0000000000..677bab8a8a
--- /dev/null
+++ b/js/app/packages/block-md/history/timeline.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+import {
+ ACTIVE_TIME_MULTIPLIER,
+ buildCompressedTimeline,
+ SESSION_GAP_MS,
+ warpedIntervalEnd,
+} from './timeline';
+
+const GAP = SESSION_GAP_MS;
+
+describe('buildCompressedTimeline', () => {
+ it('returns total 0 for empty input', () => {
+ const result = buildCompressedTimeline([]);
+ expect(result.intervals).toHaveLength(0);
+ expect(result.total).toBe(0);
+ });
+
+ it('single session produces one interval at offset 0', () => {
+ const result = buildCompressedTimeline([{ startMs: 1000, endMs: 5000 }]);
+ expect(result.intervals).toHaveLength(1);
+ expect(result.intervals[0]).toMatchObject({
+ startMs: 1000,
+ endMs: 5000,
+ warpStart: 0,
+ });
+ // Active editing time is stretched by ACTIVE_TIME_MULTIPLIER in warped space.
+ expect(result.total).toBe(4000 * ACTIVE_TIME_MULTIPLIER);
+ });
+
+ it('floors zero-duration sessions to 1ms so intervals are non-empty', () => {
+ const result = buildCompressedTimeline([{ startMs: 1000, endMs: 1000 }]);
+ expect(result.intervals[0].endMs).toBe(1001);
+ expect(result.total).toBe(1 * ACTIVE_TIME_MULTIPLIER);
+ });
+
+ it('merges sessions within the gap threshold into one interval', () => {
+ const a = { startMs: 0, endMs: 1000 };
+ const b = { startMs: 1000 + GAP, endMs: 2000 + GAP };
+ const result = buildCompressedTimeline([a, b]);
+ expect(result.intervals).toHaveLength(1);
+ });
+
+ it('keeps sessions beyond the gap as separate intervals', () => {
+ const a = { startMs: 0, endMs: 1000 };
+ const b = { startMs: 1000 + GAP + 1, endMs: 2000 + GAP + 1 };
+ const result = buildCompressedTimeline([a, b]);
+ expect(result.intervals).toHaveLength(2);
+ });
+
+ it('second interval warpStart is less than the real gap (compression)', () => {
+ const a = { startMs: 0, endMs: 1000 };
+ const bigGap = GAP * 100;
+ const b = { startMs: 1000 + bigGap, endMs: 2000 + bigGap };
+ const result = buildCompressedTimeline([a, b]);
+ expect(result.intervals).toHaveLength(2);
+ const realGap = b.startMs - a.endMs;
+ const warpedGap =
+ result.intervals[1].warpStart - warpedIntervalEnd(result.intervals[0]);
+ expect(warpedGap).toBeLessThan(realGap);
+ });
+
+ it('larger real gaps produce larger warped gaps (compression is monotonic)', () => {
+ const base = { startMs: 0, endMs: 1000 };
+ const withSmall = buildCompressedTimeline([
+ base,
+ { startMs: 1000 + GAP * 2, endMs: 2000 + GAP * 2 },
+ ]);
+ const withLarge = buildCompressedTimeline([
+ base,
+ { startMs: 1000 + GAP * 100, endMs: 2000 + GAP * 100 },
+ ]);
+ const warpedSmall =
+ withSmall.intervals[1].warpStart -
+ warpedIntervalEnd(withSmall.intervals[0]);
+ const warpedLarge =
+ withLarge.intervals[1].warpStart -
+ warpedIntervalEnd(withLarge.intervals[0]);
+ expect(warpedLarge).toBeGreaterThan(warpedSmall);
+ });
+
+ it('sorts input before processing', () => {
+ const a = { startMs: 0, endMs: 1000 };
+ const b = { startMs: 1000 + GAP * 2, endMs: 2000 + GAP * 2 };
+ const result = buildCompressedTimeline([b, a]); // b first, out of order
+ expect(result.intervals[0].startMs).toBe(0);
+ expect(result.intervals[1].startMs).toBe(b.startMs);
+ });
+
+ it('overlapping sessions are merged', () => {
+ const a = { startMs: 0, endMs: 5000 };
+ const b = { startMs: 3000, endMs: 8000 };
+ const result = buildCompressedTimeline([a, b]);
+ expect(result.intervals).toHaveLength(1);
+ expect(result.intervals[0].endMs).toBe(8000);
+ });
+
+ it('warpedIntervalEnd equals warpStart + stretched duration', () => {
+ const result = buildCompressedTimeline([
+ { startMs: 0, endMs: 1000 },
+ { startMs: 1000 + GAP * 10, endMs: 2000 + GAP * 10 },
+ ]);
+ for (const iv of result.intervals) {
+ expect(warpedIntervalEnd(iv)).toBe(
+ iv.warpStart + (iv.endMs - iv.startMs) * ACTIVE_TIME_MULTIPLIER
+ );
+ }
+ });
+});
diff --git a/js/app/packages/block-md/history/timeline.ts b/js/app/packages/block-md/history/timeline.ts
new file mode 100644
index 0000000000..429b24d6aa
--- /dev/null
+++ b/js/app/packages/block-md/history/timeline.ts
@@ -0,0 +1,125 @@
+import { blur, max } from 'd3-array';
+import { area, curveBasis } from 'd3-shape';
+
+// the "activity" meter is mostly vibe and not really designed to be super
+// useful right now :/
+
+export const SESSION_GAP_MS = 10 * 60 * 1000;
+const GAP_COMPRESSION_MULTIPLIER = 0.25;
+export const ACTIVE_TIME_MULTIPLIER = 8;
+
+export type Interval = { startMs: number; endMs: number; warpStart: number };
+
+// where it's supposed to look like it's starting, plus the real duration
+// we only fake the start position
+export const warpedIntervalEnd = (iv: Interval) =>
+ iv.warpStart + (iv.endMs - iv.startMs) * ACTIVE_TIME_MULTIPLIER;
+
+export type CompressedTimeline = { intervals: Interval[]; total: number };
+
+// Merges overlapping/adjacent sessions into contiguous blocks, then assigns
+// each block a warped start offset where gaps are logarithmically compressed.
+// Dead time between sessions takes up far less space than real editing time.
+// The idea is that we find all the overlapping sections where at least one person is editing, then find the gap between each of the merged sections, and assign real start, real end, and how much "virtual padding" to add after each section.
+export function buildCompressedTimeline(
+ sessions: readonly { startMs: number; endMs: number }[],
+ gapMs: number = SESSION_GAP_MS
+): CompressedTimeline {
+ if (sessions.length === 0) return { intervals: [], total: 0 };
+
+ const spans = [...sessions].sort((a, b) => a.startMs - b.startMs);
+ const merged: { startMs: number; endMs: number }[] = [];
+ for (const span of spans) {
+ const last = merged[merged.length - 1];
+ if (last && span.startMs - last.endMs <= gapMs) {
+ last.endMs = Math.max(last.endMs, span.endMs);
+ } else {
+ merged.push({ ...span });
+ }
+ }
+
+ const intervals: Interval[] = [];
+ let offset = 0;
+ for (let i = 0; i < merged.length; i++) {
+ if (i > 0) {
+ const gap = merged[i].startMs - merged[i - 1].endMs;
+ offset +=
+ gapMs *
+ GAP_COMPRESSION_MULTIPLIER *
+ (1 + Math.log(1 + (gap - gapMs) / gapMs));
+ }
+ const span = merged[i];
+ const endMs = Math.max(span.endMs, span.startMs + 1);
+ intervals.push({ startMs: span.startMs, endMs, warpStart: offset });
+ offset += (endMs - span.startMs) * ACTIVE_TIME_MULTIPLIER;
+ }
+
+ return { intervals, total: offset };
+}
+
+export type VolumeShape = { area: string; line: string };
+
+// Height in pixels of the volume band SVG. Exported so the caller can size the viewBox to match.
+export const VOLUME_BAND_H = 32;
+
+const VOLUME_BUCKETS = 160;
+
+// Histogram of edit intensity across the timeline. Each session contributes
+// edits/minute to the buckets it spans (in pixel space), normalized to the
+// peak so the shape is always full-height regardless of absolute volume.
+export function buildVolumeShape(
+ sessions: readonly { startMs: number; endMs: number; count: number }[],
+ toXPosition: (ms: number) => number,
+ width: number,
+ bandH: number = VOLUME_BAND_H
+): VolumeShape | null {
+ if (width <= 0 || sessions.length === 0) return null;
+
+ const bucketWidth = width / VOLUME_BUCKETS;
+ const buckets = new Array<number>(VOLUME_BUCKETS).fill(0);
+
+ for (const session of sessions) {
+ // Rate in edits/min; floor duration at 1 min so short bursts don't spike to infinity.
+ const durMin = Math.max(1, (session.endMs - session.startMs) / 60_000);
+ const rate = session.count / durMin;
+ const leftPx = Math.max(0, toXPosition(session.startMs));
+ const rightPx = Math.min(width, toXPosition(session.endMs));
+ if (rightPx < 0 || leftPx > width || rightPx < leftPx) continue;
+ const clampBucket = (px: number) =>
+ Math.max(0, Math.min(VOLUME_BUCKETS - 1, Math.floor(px / bucketWidth)));
+ const firstBucket = clampBucket(leftPx);
+ // Subtract epsilon so a session ending exactly on a bucket boundary doesn't bleed into the next.
+ const lastBucket = Math.max(firstBucket, clampBucket(rightPx - 1e-6));
+ for (let i = firstBucket; i <= lastBucket; i++) buckets[i] += rate;
+ }
+
+ // More sessions in view -> lower blur radius.
+ // this lets us see more detail when the detail has meaning. if we show deep
+ // detail (low smoothing) when there are just a few sessions then we will just
+ // see spikes for those specific sessions, which isn't super useful.
+ const visibleCount = sessions.filter((s) => {
+ const leftPos = toXPosition(s.startMs);
+ const rightPos = toXPosition(s.endMs);
+ // "is it in view at all?"
+ return rightPos >= 0 && leftPos <= width;
+ }).length;
+
+ // the actual amount of blur radius proportional to the number of visible
+ // sessions is log-based.
+ const blurRadius = Math.max(1, Math.floor(8 / Math.log2(2 + visibleCount)));
+ const roundedBuckets = Array.from(blur([...buckets], blurRadius));
+ const peak = max(roundedBuckets) ?? 0;
+ if (peak <= 0) return null;
+
+ // y1 leaves 2px headroom at the top so the line is always visible at peak.
+ const areaGenerator = area<number>()
+ .x((_, i) => (i / (VOLUME_BUCKETS - 1)) * width)
+ .y0(bandH)
+ .y1((value) => bandH - (value / peak) * (bandH - 2))
+ .curve(curveBasis);
+
+ return {
+ area: areaGenerator(roundedBuckets) ?? '',
+ line: areaGenerator.lineY1()(roundedBuckets) ?? '',
+ };
+}
diff --git a/js/app/packages/block-md/history/timestampIndex.ts b/js/app/packages/block-md/history/timestampIndex.ts
new file mode 100644
index 0000000000..430dd3aef0
--- /dev/null
+++ b/js/app/packages/block-md/history/timestampIndex.ts
@@ -0,0 +1,45 @@
+import type { HistoryVersionId } from '@service-sync/client';
+import type { SerializedEditorState } from 'lexical';
+import type { Change, LoroDoc } from 'loro-crdt';
+
+function frontiersAt(changes: Change[], targetMs: number) {
+ // Maintain a proper frontier antichain: when a change's deps cover a peer already
+ // in the frontier, that peer is now in the causal past and must be pruned. Without
+ // this, we'd pass non-antichain frontiers to checkout() which Loro rejects.
+ const frontier = new Map<Change['peer'], number>();
+ for (const { peer, counter, length, timestamp, deps } of changes) {
+ if (timestamp * 1000 > targetMs) break;
+ const endCounter = counter + length - 1;
+ for (const dep of deps) {
+ const cur = frontier.get(dep.peer);
+ if (cur !== undefined && cur <= dep.counter) frontier.delete(dep.peer);
+ }
+ if (endCounter > (frontier.get(peer) ?? -1)) frontier.set(peer, endCounter);
+ }
+ return [...frontier.entries()].map(([peer, counter]) => ({ peer, counter }));
+}
+
+export function buildTimestampIndex(doc: LoroDoc) {
+ const changes = [...doc.getAllChanges().values()]
+ .flat()
+ .sort((a, b) => a.timestamp - b.timestamp || a.counter - b.counter);
+
+ return {
+ checkoutAt(targetMs: number): SerializedEditorState | null {
+ const frontiers = frontiersAt(changes, targetMs);
+ if (frontiers.length === 0) return null;
+ doc.checkoutToLatest();
+ doc.checkout(frontiers);
+ const state = doc.toJSON();
+ if (!state.root?.type) return null;
+ return state;
+ },
+
+ versionIdAt(targetMs: number): HistoryVersionId | null {
+ const frontiers = frontiersAt(changes, targetMs);
+ if (frontiers.length === 0) return null;
+ const f = frontiers[frontiers.length - 1];
+ return { peer: String(f.peer), counter: f.counter };
+ },
+ };
+}
diff --git a/js/app/packages/block-md/history/utils.ts b/js/app/packages/block-md/history/utils.ts
new file mode 100644
index 0000000000..f70d2eb3b2
--- /dev/null
+++ b/js/app/packages/block-md/history/utils.ts
@@ -0,0 +1,34 @@
+import { macroIdToEmail, tryMacroId } from '@core/user';
+
+export { diffAuthorColor as userColor } from '@lexical-core';
+
+export function userLabel(userId: string): string {
+ if (userId === 'unknown') return 'Unknown';
+ const id = tryMacroId(userId);
+ return id ? macroIdToEmail(id) : userId;
+}
+
+export function formatTimestamp(at: Date): string {
+ return at.toLocaleString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ });
+}
+
+export function humanizeDuration(ms: number): string {
+ const d = ms / 86_400_000;
+ if (d >= 1) return `${Math.round(d)}d`;
+ const h = ms / 3_600_000;
+ if (h >= 1) return `${Math.round(h)}h`;
+ return `${Math.max(1, Math.round(ms / 60_000))}m`;
+}
+
+export {
+ buildCompressedTimeline,
+ type CompressedTimeline,
+ type Interval,
+ warpedIntervalEnd,
+} from './timeline';
diff --git a/js/app/packages/block-md/package.json b/js/app/packages/block-md/package.json
index 41e222010e..e85858704b 100644
--- a/js/app/packages/block-md/package.json
+++ b/js/app/packages/block-md/package.json
@@ -2,5 +2,14 @@
"name": "block-markdown",
"private": true,
"scripts": {},
- "dependencies": {}
+ "dependencies": {
+ "d3-array": "^3.2.4",
+ "d3-scale": "^4.0.2",
+ "d3-shape": "^3.2.0"
+ },
+ "devDependencies": {
+ "@types/d3-array": "^3.2.2",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.1.8"
+ }
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/styles.css b/js/app/packages/core/component/LexicalMarkdown/styles.css
index 5d0693ca88..039cacfb5d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/styles.css
+++ b/js/app/packages/core/component/LexicalMarkdown/styles.css
@@ -610,3 +610,18 @@ mark {
opacity: 0.25;
text-decoration: line-through;
}
+
+.diff-insert {
+ background: color-mix(
+ in srgb,
+ var(--diff-author, hsl(145, 63%, 42%)) 24%,
+ transparent
+ );
+ border-radius: 2px;
+}
+
+.diff-delete {
+ text-decoration: line-through;
+ text-decoration-color: var(--diff-author, hsl(0, 65%, 55%));
+ opacity: 0.6;
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/utils.ts b/js/app/packages/core/component/LexicalMarkdown/utils.ts
index fa1610abf4..92888d4b44 100644
--- a/js/app/packages/core/component/LexicalMarkdown/utils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/utils.ts
@@ -170,7 +170,7 @@ export function initializeEditorWithState(
state?: SerializedEditorState,
peerId?: () => string | undefined
) {
- if (!state || state.root.children.length === 0) return;
+ if (!state || state.root.children?.length === 0) return;
try {
const parsed = editor.parseEditorState(state);
editor.setEditorState(parsed);
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index d70d3db86c..ff2298ade7 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -150,11 +150,10 @@ export const ENABLE_MARKDOWN_DIFF = resolveFeatureFlag(
true
);
-// TODO (seamus): markdown history is causing a quiet crash on some documents.
-// once I have a document that can consistently repro, i can debug and fix.
+// Toggle the new experimental history viewer — on in dev/preview, off in prod.
export const ENABLE_HISTORY_COMPONENT = resolveFeatureFlag(
'ENABLE_HISTORY_COMPONENT',
- false
+ DEV_MODE_ENV
);
export const ENABLE_BEARER_TOKEN_AUTH = resolveFeatureFlag(
diff --git a/js/app/packages/queries/sync/document-peers.ts b/js/app/packages/queries/sync/document-peers.ts
new file mode 100644
index 0000000000..e45b75f87d
--- /dev/null
+++ b/js/app/packages/queries/sync/document-peers.ts
@@ -0,0 +1,22 @@
+import { syncServiceClient } from '@service-sync/client';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { syncKeys } from './keys';
+
+async function fetchDocumentPeers(
+ documentId: string
+): Promise<Map<string, string>> {
+ const result = await syncServiceClient.getDocumentMetadata({ documentId });
+ if (result.isErr()) throw new Error(String(result.error));
+ return new Map(result.value.peers.map((p) => [String(p.peer_id), p.user_id]));
+}
+
+export function useDocumentPeersQuery(documentId: Accessor<string>) {
+ return useQuery(() => ({
+ queryKey: syncKeys.documentPeers(documentId()).queryKey,
+ queryFn: () => fetchDocumentPeers(documentId()),
+ staleTime: 60 * 1000,
+ gcTime: 10 * 60 * 1000,
+ enabled: !!documentId(),
+ }));
+}
diff --git a/js/app/packages/queries/sync/keys.ts b/js/app/packages/queries/sync/keys.ts
new file mode 100644
index 0000000000..c8a806c2cb
--- /dev/null
+++ b/js/app/packages/queries/sync/keys.ts
@@ -0,0 +1,5 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const syncKeys = createQueryKeys('sync', {
+ documentPeers: (documentId: string) => ({ queryKey: [documentId] }),
+});
diff --git a/js/app/packages/service-clients/service-sync/client.ts b/js/app/packages/service-clients/service-sync/client.ts
index 5e81971bf1..d6c3290666 100644
--- a/js/app/packages/service-clients/service-sync/client.ts
+++ b/js/app/packages/service-clients/service-sync/client.ts
@@ -69,6 +69,20 @@ type MetadataResponse = {
}>;
};
+export type HistorySession = {
+ userId: string;
+ startMs: number;
+ endMs: number;
+ count: number;
+};
+
+/** A single frontier op-id — structurally a `SyncServiceVersionID`, so it can
+ * be passed straight to the copy/fork path. */
+export type HistoryVersionId = {
+ peer: string;
+ counter: number;
+};
+
export const syncServiceClient = {
async wakeup(args: { documentId: string }) {
await syncFetch(`/document/${args.documentId}/wakeup`, {
diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.ts
index 05ba15cd3a..236c73b65e 100644
--- a/js/app/vitest.config.ts
+++ b/js/app/vitest.config.ts
@@ -82,6 +82,13 @@ export default defineConfig({
name: 'block-pr',
},
},
+ {
+ extends: './packages/core/vitest.config.ts',
+ test: {
+ include: ['packages/block-md/**/*.{test,spec}.{ts,tsx}'],
+ name: 'block-md',
+ },
+ },
{
extends: './packages/core/vitest.config.ts',
test: {
diff --git a/js/bun.lock b/js/bun.lock
index 60583bebf8..b5a6e13587 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -215,6 +215,16 @@
},
"app/packages/block-md": {
"name": "block-markdown",
+ "dependencies": {
+ "d3-array": "^3.2.4",
+ "d3-scale": "^4.0.2",
+ "d3-shape": "^3.2.0",
+ },
+ "devDependencies": {
+ "@types/d3-array": "^3.2.2",
+ "@types/d3-scale": "^4.0.9",
+ "@types/d3-shape": "^3.1.8",
+ },
},
"app/packages/block-pdf": {
"name": "block-pdf",
@@ -1663,6 +1673,16 @@
"@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
+ "@types/d3-array": ["@types/[email protected]", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
+
+ "@types/d3-path": ["@types/[email protected]", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
+
+ "@types/d3-scale": ["@types/[email protected]", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],
+
+ "@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w=="],
+
+ "@types/d3-time": ["@types/[email protected]", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
+
"@types/datadog-metrics": ["@types/[email protected]", "", {}, "sha512-p6zVpfmNcXwtcXjgpz7do/fKyfndGhU5sGJVtb5Gn5PvLDiQUAgD0mI/itf/99sBi9DRxeyhFQ9dQF6OxxQNbA=="],
"@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
@@ -2035,6 +2055,24 @@
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+ "d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
+
+ "d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
+
+ "d3-format": ["[email protected]", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="],
+
+ "d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
+
+ "d3-path": ["[email protected]", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
+
+ "d3-scale": ["[email protected]", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
+
+ "d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
+
+ "d3-time": ["[email protected]", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
+
+ "d3-time-format": ["[email protected]", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
+
"dashdash": ["[email protected]", "", { "dependencies": { "assert-plus": "^1.0.0" } }, "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g=="],
"data-uri-to-buffer": ["[email protected]", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="],
@@ -2441,6 +2479,8 @@
"internal-slot": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
+ "internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
+
"invariant": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="],
"ip-address": ["[email protected]", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
diff --git a/js/lexical-core/index.ts b/js/lexical-core/index.ts
index 6bbc4569b4..5c13500857 100644
--- a/js/lexical-core/index.ts
+++ b/js/lexical-core/index.ts
@@ -13,6 +13,7 @@ export * from './nodes/DecoratorBlockNode';
export * from './nodes/DiffDeleteNode';
export * from './nodes/DiffInsertNode';
export * from './nodes/DiffNode';
+export * from './nodes/DiffTextNode';
export * from './nodes/DocumentCardNode';
export * from './nodes/DocumentMentionNode';
export * from './nodes/EquationNode';
@@ -37,5 +38,10 @@ export * from './plugins/peerIdPlugin';
export * from './transformers';
export { toXml } from './transformers/xml';
+export * from './utils/applyDiffs';
+export * from './utils/buildDiffState';
+export * from './utils/buildWhoMap';
+export * from './utils/diffStates';
+export * from './utils/diffTypes';
export * from './utils/markdown-state';
export * from './utils/mentions';
diff --git a/js/lexical-core/node-list.ts b/js/lexical-core/node-list.ts
index 162a3262bb..fac029f737 100644
--- a/js/lexical-core/node-list.ts
+++ b/js/lexical-core/node-list.ts
@@ -23,6 +23,7 @@ import { DateMentionNode } from './nodes/DateMentionNode';
import { DiffDeleteNode } from './nodes/DiffDeleteNode';
import { DiffInsertNode } from './nodes/DiffInsertNode';
import { DiffNode } from './nodes/DiffNode';
+import { DiffTextNode } from './nodes/DiffTextNode';
import { DocumentCardNode } from './nodes/DocumentCardNode';
import { DocumentMentionNode } from './nodes/DocumentMentionNode';
import { EquationNode } from './nodes/EquationNode';
@@ -97,6 +98,7 @@ export const SupportedNodeTypes = [
DiffNode,
DiffInsertNode,
DiffDeleteNode,
+ DiffTextNode,
HtmlRenderNode,
ClassedBlockNode,
WatermarkNode,
diff --git a/js/lexical-core/nodes/DiffTextNode.ts b/js/lexical-core/nodes/DiffTextNode.ts
new file mode 100644
index 0000000000..8a9992b45f
--- /dev/null
+++ b/js/lexical-core/nodes/DiffTextNode.ts
@@ -0,0 +1,113 @@
+import {
+ type EditorConfig,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedTextNode,
+ type Spread,
+ TextNode,
+} from 'lexical';
+
+export type DiffStatus = 'insert' | 'delete';
+
+export type SerializedDiffTextNode = Spread<
+ { diffStatus: DiffStatus; author: string },
+ SerializedTextNode
+>;
+
+const LANE_HUES = [30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330];
+
+export function diffAuthorColor(author: string): string {
+ // claude hashing magic
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < author.length; i++) {
+ hash ^= author.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return `var(--color-accent-${LANE_HUES[(hash >>> 0) % LANE_HUES.length]})`;
+}
+
+// Inline diff marker: a TextNode that renders highlighted (insert) or struck
+// (delete), tinted by its author's color via a per-node `--diff-author`
+export class DiffTextNode extends TextNode {
+ __diffStatus: DiffStatus;
+ __author: string;
+
+ static getType() {
+ return 'diff-text';
+ }
+
+ static clone(node: DiffTextNode) {
+ return new DiffTextNode(
+ node.__text,
+ node.__diffStatus,
+ node.__author,
+ node.__key
+ );
+ }
+
+ constructor(text: string, status: DiffStatus, author: string, key?: NodeKey) {
+ super(text, key);
+ this.__diffStatus = status;
+ this.__author = author;
+ }
+
+ createDOM(config: EditorConfig) {
+ const dom = super.createDOM(config);
+ dom.classList.add(`diff-${this.__diffStatus}`);
+ // Expose status + author on the element so a single delegated hover handler
+ // (see HistoryOverlay) can show a "who changed this" tag, matching the
+ // timeline scrubber. The author is a user id, resolved to a label at hover.
+ dom.dataset.diffStatus = this.__diffStatus;
+ if (this.__author) {
+ dom.dataset.diffAuthor = this.__author;
+ // Tint this run by its own editor, overriding the container default.
+ dom.style.setProperty('--diff-author', diffAuthorColor(this.__author));
+ }
+ return dom;
+ }
+
+ updateDOM(prev: DiffTextNode, dom: HTMLElement, config: EditorConfig) {
+ const updated = super.updateDOM(prev as this, dom, config);
+ return (
+ updated ||
+ prev.__diffStatus !== this.__diffStatus ||
+ prev.__author !== this.__author
+ );
+ }
+
+ static importJSON(serialized: SerializedDiffTextNode): DiffTextNode {
+ const node = new DiffTextNode(
+ serialized.text,
+ serialized.diffStatus,
+ serialized.author
+ );
+ node.setFormat(serialized.format);
+ node.setDetail(serialized.detail);
+ node.setMode(serialized.mode);
+ node.setStyle(serialized.style);
+ return node;
+ }
+
+ exportJSON(): SerializedDiffTextNode {
+ return {
+ ...super.exportJSON(),
+ type: DiffTextNode.getType(),
+ diffStatus: this.__diffStatus,
+ author: this.__author,
+ };
+ }
+}
+
+export function $createDiffTextNode(
+ text: string,
+ status: DiffStatus,
+ author: string
+): DiffTextNode {
+ return new DiffTextNode(text, status, author);
+}
+
+export function $isDiffTextNode(
+ node: LexicalNode | null
+): node is DiffTextNode {
+ return node instanceof DiffTextNode;
+}
diff --git a/js/lexical-core/utils/applyDiffs.ts b/js/lexical-core/utils/applyDiffs.ts
new file mode 100644
index 0000000000..eea4236d73
--- /dev/null
+++ b/js/lexical-core/utils/applyDiffs.ts
@@ -0,0 +1,145 @@
+import {
+ $createLineBreakNode,
+ $createTextNode,
+ $getRoot,
+ $isElementNode,
+ $isTextNode,
+ $parseSerializedNode,
+ type ElementNode,
+ type LexicalEditor,
+ type LexicalNode,
+} from 'lexical';
+import { match, P } from 'ts-pattern';
+import { $getNodeById, type NodeIdMappings } from '../plugins/nodeIdPlugin';
+import { $createDiffTextNode, type DiffStatus } from '../nodes/DiffTextNode';
+import {
+ type DeleteDiff,
+ type Diff,
+ type InsertDiff,
+ type ModifyDiff,
+ NEWLINE,
+ type WordRun,
+} from './diffTypes';
+
+// Recursively retag every text leaf of a node as a diff run (whole-block
+// insert/delete). An empty block (a blank paragraph from pressing Enter) has no
+// text to mark, so it gets a ¶ marker — otherwise an added/removed blank line is
+// invisible.
+function markAllText(node: LexicalNode, status: DiffStatus, author: string) {
+ if ($isTextNode(node)) {
+ node.replace($createDiffTextNode(node.getTextContent(), status, author));
+ return;
+ }
+ if ($isElementNode(node)) {
+ const children = node.getChildren();
+ for (const child of children) markAllText(child, status, author);
+ if (children.length === 0 && !node.isInline()) {
+ node.append($createDiffTextNode('¶', status, author));
+ }
+ }
+}
+
+function applyInsert(
+ editor: LexicalEditor,
+ diff: InsertDiff,
+ mappings: NodeIdMappings
+) {
+ const newNode = $parseSerializedNode(diff.node);
+ markAllText(newNode, 'insert', diff.author ?? '');
+ const anchor = diff.node_id
+ ? $getNodeById(editor, mappings.idToNodeKeyMap, diff.node_id)
+ : null;
+ if (anchor) {
+ if (diff.operation === 'INSERT_BEFORE') anchor.insertBefore(newNode);
+ else anchor.insertAfter(newNode);
+ } else {
+ // no anchor (insert at the very start) — prepend to root
+ const first = $getRoot().getFirstChild();
+ if (first) first.insertBefore(newNode);
+ else $getRoot().append(newNode);
+ }
+}
+
+function applyDelete(
+ editor: LexicalEditor,
+ diff: DeleteDiff,
+ mappings: NodeIdMappings
+) {
+ const node = $getNodeById(editor, mappings.idToNodeKeyMap, diff.node_id);
+ if (node) markAllText(node, 'delete', diff.author ?? '');
+}
+
+function applyModify(
+ editor: LexicalEditor,
+ diff: ModifyDiff,
+ mappings: NodeIdMappings
+) {
+ const node = $getNodeById(editor, mappings.idToNodeKeyMap, diff.node_id);
+ if (!node || !$isElementNode(node)) return;
+ // Tier 1 rebuilds a block's inline content from text runs. A structured block
+ // (table, list, …) has block-level element children — rebuilding it as text
+ // would corrupt it, so skip. Per-cell/item diffing is the nested follow-up.
+ if (node.getChildren().some((c) => $isElementNode(c) && !c.isInline()))
+ return;
+ const author = diff.author ?? '';
+ node.clear();
+ for (const run of diff.runs) appendRun(node, run, author);
+}
+
+// Append a run's content, turning the linebreak sentinel back into real breaks.
+// A genuine inserted/deleted break shows a ¶ marker in the author's color; kept
+// breaks render as plain line breaks (layout only, no marker).
+function appendRun(block: ElementNode, run: WordRun, author: string) {
+ const segments = run.text.split(NEWLINE);
+ segments.forEach((segment, index) => {
+ if (segment) {
+ block.append(
+ run.op === 'keep'
+ ? $createTextNode(segment)
+ : $createDiffTextNode(segment, run.op, author)
+ );
+ }
+ // a genuine line break sat between this segment and the next
+ if (index < segments.length - 1) {
+ match(run.op)
+ .with('keep', () => {
+ block.append($createLineBreakNode());
+ })
+ .with('insert', () => {
+ block.append($createDiffTextNode('¶', 'insert', author));
+ block.append($createLineBreakNode());
+ })
+ .with('delete', () => {
+ block.append($createDiffTextNode('¶', 'delete', author));
+ })
+ .exhaustive();
+ }
+ });
+}
+
+// Render a diff into an editor loaded with the BEFORE state. Everything renders
+// inline via DiffTextNode on the document's normal blocks — no wrapper nodes.
+export function applyDiffs(
+ editor: LexicalEditor,
+ diffs: readonly Diff[],
+ mappings: NodeIdMappings
+): void {
+ editor.update(
+ () => {
+ for (const diff of diffs) {
+ match(diff)
+ .with({ operation: P.union('INSERT_AFTER', 'INSERT_BEFORE') }, (d) =>
+ applyInsert(editor, d, mappings)
+ )
+ .with({ operation: 'DELETE' }, (d) =>
+ applyDelete(editor, d, mappings)
+ )
+ .with({ operation: 'MODIFY' }, (d) =>
+ applyModify(editor, d, mappings)
+ )
+ .exhaustive();
+ }
+ },
+ { discrete: true }
+ );
+}
diff --git a/js/lexical-core/utils/buildDiffState.ts b/js/lexical-core/utils/buildDiffState.ts
new file mode 100644
index 0000000000..219b6a3ba6
--- /dev/null
+++ b/js/lexical-core/utils/buildDiffState.ts
@@ -0,0 +1,44 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import type { SerializedEditorState } from 'lexical';
+import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import { DiffTextNode } from '../nodes/DiffTextNode';
+import {
+ $updateAllNodeIds,
+ type NodeIdMappings,
+} from '../plugins/nodeIdPlugin';
+import { applyDiffs } from './applyDiffs';
+import type { Diff } from './diffTypes';
+
+/**
+ * Build the serialized state that renders a diff: load the BEFORE state into a
+ * throwaway headless editor, rebuild the id -> nodeKey map from the serialized
+ * `$.id` node-state, apply the diffs (inline DiffTextNodes), and serialize back
+ * out. Feed the result to any editor that registers DiffTextNode (e.g. the
+ * history overlay's MarkdownShell) as `initialState` to display it.
+ *
+ * We rebuild ids with `$updateAllNodeIds` directly rather than registering the
+ * full `nodeIdPlugin`: headless editors reject `registerMutationListener`, and
+ * we only need id resolution for `$getNodeById`, not live-editing id assignment.
+ */
+export function buildDiffState(
+ before: SerializedEditorState,
+ diffs: readonly Diff[]
+): SerializedEditorState {
+ const editor = createHeadlessEditor({
+ namespace: 'diff-view',
+ nodes: [...SupportedNodeTypes, DiffTextNode, ...NodeReplacements],
+ onError: (error) => {
+ throw error;
+ },
+ });
+
+ const mappings: NodeIdMappings = {
+ idToNodeKeyMap: new Map(),
+ nodeKeyToIdMap: new Map(),
+ };
+
+ editor.setEditorState(editor.parseEditorState(before));
+ editor.update(() => $updateAllNodeIds(mappings), { discrete: true });
+ applyDiffs(editor, diffs, mappings);
+ return editor.getEditorState().toJSON();
+}
diff --git a/js/lexical-core/utils/buildWhoMap.ts b/js/lexical-core/utils/buildWhoMap.ts
new file mode 100644
index 0000000000..e1857f413f
--- /dev/null
+++ b/js/lexical-core/utils/buildWhoMap.ts
@@ -0,0 +1,78 @@
+import type { Change, ContainerID, LoroDoc } from 'loro-crdt';
+import { LoroMap } from 'loro-crdt';
+
+// Read a node-map's `$.id`, if this container is a LoroMap with that structure.
+function dollarId(c: ReturnType<LoroDoc['getContainerById']>): string | null {
+ if (!(c instanceof LoroMap)) return null;
+ const dollar = c.get('$');
+ if (!(dollar instanceof LoroMap)) return null;
+ const id = dollar.get('id');
+ return typeof id === 'string' ? id : null;
+}
+
+// Read a node-map's lexical `type` field (paragraph/table/tablecell/…).
+function nodeType(c: ReturnType<LoroDoc['getContainerById']>): string | null {
+ if (!(c instanceof LoroMap)) return null;
+ const t = c.get('type');
+ return typeof t === 'string' ? t : null;
+}
+
+// Structural units whose id is stable across edits; diffStates pairs cell content
+// on these (the inner paragraph's id can churn when an empty cell is first typed).
+const STABLE_CONTAINERS = new Set(['tablecell', 'listitem']);
+
+// The id diffStates keys an edit on — so attribution lines up with the diff:
+// - text inside a table cell / list item -> the innermost cell/item id (stable)
+// - text anywhere else -> the block directly wrapping it
+// The climb yields node-maps [textNode, contentBlock, …ancestors…] (list
+// containers between carry no `$.id`). chain[0] is the text node; chain[1] is its
+// block. Climbing all the way to the top-level block instead would collapse every
+// cell of a table onto the single `table` id (all edits look like one author).
+function blockIdOfContainer(doc: LoroDoc, cid: ContainerID): string | null {
+ const chain: Array<{ type: string | null; id: string }> = [];
+ let cur = doc.getContainerById(cid)?.parent();
+ while (cur) {
+ const id = dollarId(cur);
+ if (id) chain.push({ type: nodeType(cur), id });
+ cur = cur.parent();
+ }
+ const cell = chain.find((n) => n.type && STABLE_CONTAINERS.has(n.type));
+ return cell?.id ?? chain[1]?.id ?? chain[0]?.id ?? null;
+}
+
+/**
+ * Map each node `$.id` to the user who last edited it, by walking the doc's op
+ * history (oldest -> newest, last write wins).
+ */
+export function buildWhoMap(
+ doc: LoroDoc,
+ peerToUser: (peer: string) => string = (peer) => peer
+): Map<string, string> {
+ const whoMap = new Map<string, string>();
+
+ const flat: Change[] = [];
+ for (const changes of doc.getAllChanges().values()) {
+ flat.push(...changes);
+ }
+ // Order by lamport (global causal clock) so "last write wins" is correct across
+ // peers — timestamps can tie/skew and counter is per-peer. Tie-break by peer for
+ // determinism.
+ flat.sort(
+ (a, b) =>
+ a.lamport - b.lamport || (a.peer < b.peer ? -1 : a.peer > b.peer ? 1 : 0)
+ );
+
+ for (const change of flat) {
+ // Change satisfies IdSpan structurally; exportJsonInIdSpan gives us properly
+ // typed JsonOp[] with container as ContainerID, unlike getOpsInChange (any[]).
+ for (const jsonChange of doc.exportJsonInIdSpan(change)) {
+ for (const op of jsonChange.ops) {
+ if (!op.container.endsWith(':Text')) continue;
+ const blockId = blockIdOfContainer(doc, op.container);
+ if (blockId) whoMap.set(blockId, peerToUser(change.peer));
+ }
+ }
+ }
+
+ return whoMap;
+}
diff --git a/js/lexical-core/utils/diffStates.ts b/js/lexical-core/utils/diffStates.ts
new file mode 100644
index 0000000000..8c4f444eed
--- /dev/null
+++ b/js/lexical-core/utils/diffStates.ts
@@ -0,0 +1,134 @@
+import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';
+import { type Diff, NEWLINE } from './diffTypes';
+import { diffChars } from 'diff';
+import { match } from 'ts-pattern';
+import type { WordRun } from './diffTypes';
+
+
+type SerNode = {
+ type: string;
+ text?: string;
+ $?: { id?: string };
+ children?: SerNode[];
+ [key: string]: unknown;
+};
+
+const idOf = (node: SerNode): string | undefined => node.$?.id;
+
+// Leaf block types: flatten their inline children to text and diff as a unit.
+// Everything else (tables, lists, custom containers, unknown future types) is
+// treated as a structural container — recurse through to find content blocks.
+const LEAF_TYPES = new Set(['paragraph', 'heading', 'code', 'quote']);
+
+/** Flatten a block's text content (concatenation of descendant text nodes).
+ * Genuine linebreak nodes become a sentinel so the diff sees them. */
+function flattenText(node: SerNode): string {
+ if (node.type === 'text' && typeof node.text === 'string') return node.text;
+ if (node.type === 'linebreak') return NEWLINE;
+ return (node.children ?? []).map(flattenText).join('');
+}
+
+/**
+ * Full character-level diff (jsdiff `diffChars`). Pure insertions/deletions —
+ * e.g. typing "OOO" into a word — show just the changed characters. Substitutions
+ * (brown -> red) are character-minimal, so they can fragment a little (jsdiff has
+ * no semantic-cleanup pass).
+ */
+export function wordDiff(before: string, after: string): WordRun[] {
+ return diffChars(before, after).map((part) => ({
+ op: match(part)
+ .with({ added: true }, () => 'insert' as const)
+ .with({ removed: true }, () => 'delete' as const)
+ .otherwise(() => 'keep' as const),
+ text: part.value,
+ }));
+}
+
+// Collect all content blocks (paragraphs, headings, …) from the entire tree,
+// keyed by their stable $.id. Recurses through containers transparently.
+function collectContentBlocks(root: SerNode): Map<string, SerNode> {
+ const out = new Map<string, SerNode>();
+ const recurse = (node: SerNode) => {
+ if (!LEAF_TYPES.has(node.type)) {
+ for (const child of node.children ?? []) recurse(child);
+ } else {
+ const id = idOf(node);
+ if (id) out.set(id, node);
+ }
+ };
+ recurse(root);
+ return out;
+}
+
+/**
+ * Compute a diff between two document versions, paired by `$.id`.
+ *
+ * - Top-level blocks: INSERT / DELETE (structural changes)
+ * - All content blocks (including inside tables/lists): MODIFY when text changes
+ *
+ * `authorOf` maps a block's `$.id` to the user who changed it.
+ */
+export function diffStates(
+ before: SerializedEditorState,
+ after: SerializedEditorState,
+ authorOf: (id: string) => string | undefined = () => undefined
+): Diff[] {
+ const beforeRoot = before.root as unknown as SerNode;
+ const afterRoot = after.root as unknown as SerNode;
+
+ const beforeKids = beforeRoot.children ?? [];
+ const afterKids = afterRoot.children ?? [];
+
+ const beforeById = new Map<string, SerNode>();
+ for (const node of beforeKids) {
+ const id = idOf(node);
+ if (id) beforeById.set(id, node);
+ }
+ const afterIds = new Set(afterKids.map(idOf));
+
+ const diffs: Diff[] = [];
+
+ // Top-level deletions.
+ for (const node of beforeKids) {
+ const id = idOf(node);
+ if (id && !afterIds.has(id)) {
+ diffs.push({ operation: 'DELETE', node_id: id, author: authorOf(id) });
+ }
+ }
+
+ // Top-level insertions.
+ let prevKeptId: string | undefined;
+ for (const node of afterKids) {
+ const id = idOf(node);
+ if (!id) continue;
+ if (!beforeById.has(id)) {
+ diffs.push({
+ operation: 'INSERT_AFTER',
+ node_id: prevKeptId ?? '',
+ node: node as unknown as SerializedLexicalNode,
+ author: authorOf(id),
+ });
+ } else {
+ prevKeptId = id;
+ }
+ }
+
+ // MODIFY pass: all content blocks in the tree, including inside tables/lists.
+ const beforeBlocks = collectContentBlocks(beforeRoot);
+ for (const [id, afterNode] of collectContentBlocks(afterRoot)) {
+ const beforeNode = beforeBlocks.get(id);
+ if (!beforeNode) continue;
+ const beforeText = flattenText(beforeNode);
+ const afterText = flattenText(afterNode);
+ if (beforeText !== afterText) {
+ diffs.push({
+ operation: 'MODIFY',
+ node_id: id,
+ runs: wordDiff(beforeText, afterText),
+ author: authorOf(id),
+ });
+ }
+ }
+
+ return diffs;
+}
diff --git a/js/lexical-core/utils/diffTypes.ts b/js/lexical-core/utils/diffTypes.ts
new file mode 100644
index 0000000000..387971b790
--- /dev/null
+++ b/js/lexical-core/utils/diffTypes.ts
@@ -0,0 +1,40 @@
+import type { SerializedLexicalNode } from 'lexical';
+
+/** One inline run within a modified block (character-level). */
+export interface WordRun {
+ op: 'keep' | 'insert' | 'delete';
+ text: string;
+}
+
+// Stands in for a genuine `linebreak` node when a block is flattened to text for
+// diffing. Text content is passed through verbatim, so a literal "\n" a user
+// typed never collides with this — the ¶ marker only ever represents a real
+// linebreak node.
+export const NEWLINE = '\n';
+
+interface DiffBase {
+ /** The stable `$.id` of the node this diff is anchored to. */
+ node_id: string;
+ /** Who made this change (drives author coloring). */
+ author?: string;
+}
+
+/** A whole new block inserted relative to the anchor node. */
+export interface InsertDiff extends DiffBase {
+ operation: 'INSERT_BEFORE' | 'INSERT_AFTER';
+ /** The actual after-block node to insert. */
+ node: SerializedLexicalNode;
+}
+
+/** An edited block, rendered as character-level inline runs. */
+export interface ModifyDiff extends DiffBase {
+ operation: 'MODIFY';
+ runs: WordRun[];
+}
+
+/** A removed block. */
+export interface DeleteDiff extends DiffBase {
+ operation: 'DELETE';
+}
+
+export type Diff = InsertDiff | ModifyDiff | DeleteDiff;
diff --git a/js/lexical-core/utils/markdown-state.ts b/js/lexical-core/utils/markdown-state.ts
index 236fb01652..b259b2db3a 100644
--- a/js/lexical-core/utils/markdown-state.ts
+++ b/js/lexical-core/utils/markdown-state.ts
@@ -1,5 +1,8 @@
import { createHeadlessEditor } from '@lexical/headless';
-import { $convertFromMarkdownString } from '@lexical/markdown';
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+} from '@lexical/markdown';
import type { SerializedEditorState } from 'lexical';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
import {
@@ -44,3 +47,18 @@ export function markdownToSerializedEditorStateWithIds(
return editor.getEditorState().toJSON();
}
+
+/**
+ * Converts a serialized Lexical editor state back to a markdown string. Headless
+ * inverse of {@link markdownToSerializedEditorStateWithIds}; useful for comparing
+ * two document versions by their rendered markdown.
+ */
+export function serializedEditorStateToMarkdown(
+ state: SerializedEditorState
+): string {
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ const parsed = editor.parseEditorState(state);
+ return parsed.read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+}
diff --git a/js/scripts/grab-snapshot.ts b/js/scripts/grab-snapshot.ts
new file mode 100644
index 0000000000..cf897047aa
--- /dev/null
+++ b/js/scripts/grab-snapshot.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env bun
+// simple script to dump a document's loro state for a document that exists in dev or prod into your locally running instance. locally running instances have a feature flag that exposes an endpoint that makes this possible
+const argv = process.argv.slice(2);
+const useDev = argv.includes('--dev');
+const [token, srcDocId, targetDocId, targetUrlArg] = argv.filter((a) => !a.startsWith('--'));
+if (!token || !srcDocId || !targetDocId) {
+ console.error(
+ 'usage: bun run scripts/grab-snapshot.ts [--dev] <token> <source-document-id> <target-dev-document-id> [target-url]'
+ );
+ process.exit(1);
+}
+
+const SOURCE_URL =
+ process.env.SOURCE_URL ??
+ (useDev
+ ? 'https://sync-service-dev3.macroverse.workers.dev'
+ : 'https://sync-service-prod2.macroverse.workers.dev');
+const TARGET_URL = targetUrlArg ?? process.env.TARGET_URL ?? 'http://localhost:8787';
+const APP_URL = process.env.APP_URL ?? 'http://localhost:3000';
+
+const grab = await fetch(`${SOURCE_URL}/document/${srcDocId}/snapshot`, {
+ headers: { Authorization: `Bearer ${token}` },
+});
+if (!grab.ok) {
+ console.error(`snapshot grab failed: ${grab.status} ${grab.statusText}`);
+ process.exit(1);
+}
+const snapshot = new Uint8Array(await grab.arrayBuffer());
+
+let peers: Array<{ peer_id: string; user_id: string }> = [];
+const meta = await fetch(`${SOURCE_URL}/document/${srcDocId}/metadata`, {
+ headers: { Authorization: `Bearer ${token}` },
+});
+if (meta.ok) {
+ peers = ((await meta.json()) as { peers?: typeof peers }).peers ?? [];
+} else {
+ console.warn(`metadata fetch failed (${meta.status}); continuing without peer map`);
+}
+
+const set = await fetch(`${TARGET_URL}/document/${targetDocId}/set_memory_state`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ snapshot: Array.from(snapshot), peers }),
+});
+if (!set.ok) {
+ console.error(`set_memory_state failed: ${set.status} — ${await set.text()}`);
+ process.exit(1);
+}
+
+console.log(`grabbed ${snapshot.length} bytes + ${peers.length} peers from ${useDev ? 'dev' : 'prod'}`);
+console.log(`swapped onto dev doc ${targetDocId} (in-memory)`);
+console.log(` ${APP_URL}/app/md/${targetDocId}`);
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 6f71d01c6b..f7c4f309a3 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
"aarch64-darwin": "sha256-NixmiWMFLKhy6zarDYnmS4N7GYthokmpBL3lM64vZzk=",
- "x86_64-linux": "sha256-psPPOB4jSR61J5Tsuiqb1F5k2okJetKF4l72l0nuKa4="
+ "x86_64-linux": "sha256-MEXhYptL8QV7DwTmXJf9kNI753Tfn9rU5iFh3Hzmq/E="
}
-}
\ No newline at end of file
+}
diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nix
index 5746151a27..9475bfb434 100644
--- a/nix/tauri-desktop.nix
+++ b/nix/tauri-desktop.nix
@@ -306,7 +306,7 @@
tauriLinuxdeployAppimagePluginSource = pkgs.fetchurl {
# Do not use the mutable "continuous" release: tag-push builds must be reproducible.
url = "https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1/linuxdeploy-plugin-appimage-x86_64.AppImage";
- hash = "sha256-mS1QKiSOFKsYVEjd9vbn0lVYy4TUYjw1TDrzUMJfzLM=";
+ hash = "sha256-psPPOB4jSR61J5Tsuiqb1F5k2okJetKF4l72l0nuKa4=";
};
tauriLinuxdeployAppimagePluginExtracted = pkgs.appimageTools.extractType2 {
pname = "linuxdeploy-plugin-appimage";