Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(email): restore topbar actions (#7018)

Peter Chinman88c03699d755
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index 998ff4500c..e12d2efa37 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -1,3 +1,4 @@
+import type { ListDetailNavigationTarget } from '@app/components/list';
import { ViewBreadcrumbs } from '@app/components/view-shell';
import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
@@ -338,30 +339,48 @@ function SoupNavigationButtons() {
return (
<Show when={shouldShow()}>
- <div class="flex items-center gap-0.5">
- <Button
- size="icon-md"
- label="Previous item"
- hotkey={TOKENS.entity.step.start}
- disabled={!canNavigateUp()}
- onClick={() => navigate(-1)}
- >
- <CaretUp class="size-4" />
- </Button>
- <Button
- size="icon-md"
- label="Next item"
- hotkey={TOKENS.entity.step.end}
- disabled={!canNavigateDown()}
- onClick={() => navigate(1)}
- >
- <CaretDown class="size-4" />
- </Button>
- </div>
+ <ListNavigationButtons
+ navigation={{
+ canPrevious: canNavigateUp,
+ canNext: canNavigateDown,
+ previous: () => navigate(-1),
+ next: () => navigate(1),
+ }}
+ />
</Show>
);
}
+/** Shared header controls; each host supplies its current list navigation. */
+export function ListNavigationButtons(props: {
+ navigation: ListDetailNavigationTarget;
+}) {
+ return (
+ <div class="flex items-center gap-0.5">
+ <Button
+ size="icon-md"
+ label="Previous item"
+ hotkey={TOKENS.entity.step.start}
+ disabled={!props.navigation.canPrevious()}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={props.navigation.previous}
+ >
+ <CaretUp class="size-4" />
+ </Button>
+ <Button
+ size="icon-md"
+ label="Next item"
+ hotkey={TOKENS.entity.step.end}
+ disabled={!props.navigation.canNext()}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={props.navigation.next}
+ >
+ <CaretDown class="size-4" />
+ </Button>
+ </div>
+ );
+}
+
function SplitHeaderContextMenu(props: ParentProps) {
const panel = useContext(SplitPanelContext);
const layout = useContext(SplitLayoutContext);
diff --git a/apps/web/src/components/entity-detail/use-list-navigation-hotkeys.ts b/apps/web/src/components/entity-detail/use-list-navigation-hotkeys.ts
index 2c8483355b..b5147d778c 100644
--- a/apps/web/src/components/entity-detail/use-list-navigation-hotkeys.ts
+++ b/apps/web/src/components/entity-detail/use-list-navigation-hotkeys.ts
@@ -7,11 +7,12 @@ export function useListNavigationHotkeys(options: {
scopeId: string;
enabled: Accessor<boolean>;
navigation: ListDetailNavigationTarget;
+ arrowKeys?: boolean;
}) {
const group = createHotkeyGroup();
registerHotkey({
- hotkey: 'j',
+ hotkey: options.arrowKeys ? ['j', 'arrowright'] : 'j',
hotkeyToken: TOKENS.entity.step.end,
scopeId: options.scopeId,
description: 'Next item',
@@ -24,7 +25,7 @@ export function useListNavigationHotkeys(options: {
}).withGroup(group);
registerHotkey({
- hotkey: 'k',
+ hotkey: options.arrowKeys ? ['k', 'arrowleft'] : 'k',
hotkeyToken: TOKENS.entity.step.start,
scopeId: options.scopeId,
description: 'Previous item',
diff --git a/apps/web/src/features/block-email/EmailThreadHostView.tsx b/apps/web/src/features/block-email/EmailThreadHostView.tsx
index c9403f8908..60fcba0963 100644
--- a/apps/web/src/features/block-email/EmailThreadHostView.tsx
+++ b/apps/web/src/features/block-email/EmailThreadHostView.tsx
@@ -27,6 +27,8 @@ export type EmailThreadHostViewProps = {
threadTransport: EmailThreadProps['threadTransport'];
host: EmailThreadHost;
topBar?: (context: EmailThreadHostViewContext) => JSX.Element;
+ /** Host chrome that stays mounted for both drafts and message threads. */
+ chrome?: (context: EmailThreadHostViewContext) => JSX.Element;
sidePanelHeaderToggle?: boolean;
};
@@ -65,16 +67,19 @@ export function EmailThreadHostView(props: EmailThreadHostViewProps) {
header={props.topBar?.({ createTask })}
actions={<ThreadActions title={props.title} onCreateTask={createTask} />}
frame={(content) => (
- <SidePanel.Layout
- defaultOpen={false}
- headerToggle={props.sidePanelHeaderToggle}
- >
- {content()}
- <EmailSidePanelSections
- threadId={props.threadId()}
- title={props.title}
- />
- </SidePanel.Layout>
+ <>
+ {props.chrome?.({ createTask })}
+ <SidePanel.Layout
+ defaultOpen={false}
+ headerToggle={props.sidePanelHeaderToggle}
+ >
+ {content()}
+ <EmailSidePanelSections
+ threadId={props.threadId()}
+ title={props.title}
+ />
+ </SidePanel.Layout>
+ </>
)}
/>
);
diff --git a/apps/web/src/features/block-email/component/EmailThreadControls.tsx b/apps/web/src/features/block-email/component/EmailThreadControls.tsx
new file mode 100644
index 0000000000..c1efd61957
--- /dev/null
+++ b/apps/web/src/features/block-email/component/EmailThreadControls.tsx
@@ -0,0 +1,65 @@
+import { TOKENS } from '@core/hotkey/tokens';
+import { isMobile } from '@core/mobile/isMobile';
+import CheckIcon from '@phosphor/check.svg';
+import EnvelopeSimpleIcon from '@phosphor/envelope-simple.svg';
+import EnvelopeSimpleOpenIcon from '@phosphor/envelope-simple-open.svg';
+import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export function EmailThreadControls(props: {
+ isOwnThread: boolean;
+ isDone: boolean;
+ isUnread: boolean;
+ canToggleDone: boolean;
+ onToggleDone: () => void;
+ onToggleUnread: () => void;
+}) {
+ return (
+ <Show when={!isMobile()}>
+ {/* Read-state toggle. Viewing the thread marks it read, so it
+ starts as Mark as unread; marking unread flips it to a bold
+ accent closed envelope that re-marks the thread read. */}
+ <Show when={props.isOwnThread}>
+ <Button
+ size="icon-md"
+ label={props.isUnread ? 'Mark as read' : 'Mark as unread'}
+ hotkey={
+ props.isUnread
+ ? TOKENS.entity.action.markRead
+ : TOKENS.entity.action.markUnread
+ }
+ onClick={props.onToggleUnread}
+ // Keep focus (and the hotkey scope cmd-K reads) in the thread
+ // content: focusing the header would hide its commands.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <Show
+ when={props.isUnread}
+ fallback={<EnvelopeSimpleOpenIcon class="size-4" />}
+ >
+ <EnvelopeSimpleIcon class="size-4 text-accent" />
+ </Show>
+ </Button>
+ </Show>
+ <Show when={props.isOwnThread && props.canToggleDone}>
+ <Button
+ size="icon-md"
+ label={props.isDone ? 'Mark as not done' : 'Mark done'}
+ hotkey={
+ props.isDone
+ ? TOKENS.entity.action.markNotDone
+ : TOKENS.entity.action.markDone
+ }
+ onClick={props.onToggleDone}
+ // Same focus-preservation as the read-state toggle above.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <Show when={props.isDone} fallback={<CheckIcon class="size-4" />}>
+ <CheckBoldIcon class="size-4 text-accent" />
+ </Show>
+ </Button>
+ </Show>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-email/component/TopBar.tsx b/apps/web/src/features/block-email/component/TopBar.tsx
index d8487f607b..c9769dba02 100644
--- a/apps/web/src/features/block-email/component/TopBar.tsx
+++ b/apps/web/src/features/block-email/component/TopBar.tsx
@@ -1,16 +1,3 @@
-import {
- ChatWithAgentButton,
- ChatWithAgentIcon,
- openChatWithAgent,
-} from '@app/features/chat/ChatWithAgentButton';
-import { useEmailThreadState } from '@app/features/email-thread/context/email-thread-state-context';
-import { makeMoveToProjectAction } from '@app/features/next-soup/actions';
-import { useMaybeSoup } from '@app/features/next-soup/soup-context';
-import {
- openEntityInSplitFromUnifiedList,
- trashEmails,
-} from '@app/features/next-soup/utils';
-import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
import { ResponsiveBlockToolbar } from '@components/app/ResponsiveBlockToolbar';
import {
SplitHeaderLeft,
@@ -20,273 +7,14 @@ import {
SplitHeaderBadge,
StaticSplitLabel,
} from '@components/app/split-layout/components/SplitLabel';
-import { getPermissions } from '@core/component/SharePermissions';
-import { toast } from '@core/component/Toast/Toast';
+import { EmailThreadControls } from './EmailThreadControls';
import {
- getShareDrawerRecipientInput,
- ShareTrigger,
-} from '@core/component/TopBar/ShareButton';
-import { useShareModal } from '@core/component/TopBar/shareModal';
-import { ENABLE_EMAIL_SHARING } from '@core/constant/featureFlags';
-import { TOKENS } from '@core/hotkey/tokens';
-import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
-import { isMobile } from '@core/mobile/isMobile';
-import { buildEntityData } from '@entity';
-import IconShared from '@icon/share.svg';
-import ArrowRightIcon from '@phosphor/arrow-right.svg';
-import CheckIcon from '@phosphor/check.svg';
-import EnvelopeSimpleIcon from '@phosphor/envelope-simple.svg';
-import EnvelopeSimpleOpenIcon from '@phosphor/envelope-simple-open.svg';
-import TaskIcon from '@phosphor/list-checks.svg';
-import ProhibitIcon from '@phosphor/prohibit.svg';
-import TrashIcon from '@phosphor/trash.svg';
-import NoiseIcon from '@phosphor/waveform.svg';
-import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
-import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
-import { useEmailLinksQuery } from '@queries/email/link';
-import { queryReadyGate } from '@queries/gate';
-import { Button } from '@ui';
-import { Show } from 'solid-js';
-
-export function TopBar(props: {
- id: string;
- title: string;
- isDraft?: boolean;
- onCreateTask?: () => void;
-}) {
- const emailCtx = useEmailThreadState();
- const openShare = useShareModal(() => {
- const thread = emailCtx.thread();
- if (!thread) return;
- return {
- id: props.id,
- blockAlias: 'email',
- itemType: 'email',
- name: props.title,
- userPermissions: getPermissions(thread.access_level),
- };
- });
- const soup = useMaybeSoup();
- const linksQuery = useEmailLinksQuery();
- const moveToProjectAction = makeMoveToProjectAction();
-
- const isInvite = () => {
- const row = soup?.items.get(props.id);
- const entity = row?.original;
- return entity?.type === 'email' && entity.hasIcsAttachment === true;
- };
-
- const isOwnThread = () => {
- const thread = emailCtx.thread();
- if (!thread || !queryReadyGate(linksQuery)) return false;
- return linksQuery.data.links.some((link) => link.id === thread.link_id);
- };
-
- const isDone = () => emailCtx.isThreadDone();
-
- const emailEntity = () => {
- const soupEntity = soup?.items.get(props.id)?.original;
- if (soupEntity?.type === 'email') return soupEntity;
-
- const thread = emailCtx.thread();
- return buildEntityData({
- id: props.id,
- name: props.title,
- blockName: 'email',
- projectId: thread?.project_id ?? undefined,
- isRead: thread?.is_read,
- isDraft: props.isDraft,
- done: thread ? !thread.inbox_visible : undefined,
- });
- };
-
- const moveToFolder = () => {
- const entity = emailEntity();
- if (!entity || !moveToProjectAction.canExecute(entity)) return;
- void moveToProjectAction.execute([entity]);
- };
-
- // A send-only thread is permanently done, so neither half of the toggle
- // does anything — hide it rather than offer a no-op.
- const showMarkDoneToggle = () => !isDone() || emailCtx.canMarkThreadNotDone();
-
- const toggleMarkDone = () => {
- if (isDone()) {
- emailCtx.markThreadNotDone();
- return;
- }
- // Prefer the active Mark done command so it drives soup navigation and
- // notifications; fall back to archiving the thread directly. A command
- // can be found but still decline (condition/handler returns false, e.g.
- // the triage registration when not opened from inbox/mail), so gate on
- // it actually capturing.
- const command = getActiveCommandByToken(TOKENS.entity.action.markDone);
- if (command && runCommand(command).commandCaptured) return;
- emailCtx.archiveThread();
- };
-
- const toggleMarkUnread = () => {
- if (emailCtx.isThreadMarkedUnread()) {
- emailCtx.markThreadRead();
- } else {
- emailCtx.markThreadUnread();
- }
- };
-
- const trashThread = () => {
- const thread = emailCtx.thread();
- if (!thread?.db_id) return;
-
- // Calculate next row before trashing so we can navigate to it
- const nextRow = (() => {
- if (!soup) return undefined;
- const currentIndex = soup.focus.index();
- return soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
- })();
-
- const handle = trashEmails([{ id: thread.db_id, linkId: thread.link_id }]);
-
- if (soup && nextRow) {
- soup.selection.clear();
- soup.focus.set(nextRow.id);
- openEntityInSplitFromUnifiedList(nextRow.original, {});
- }
-
- const toastId = toast.success('Moved to Trash', {
- actions: [
- {
- label: 'Undo',
- icon: ArrowCounterClockwise,
- onClick: () => {
- if (toastId != null) toast.dismiss(toastId);
- handle.undo().then(
- () => toast.success('Restored from Trash'),
- () => toast.failure('Failed to restore from Trash')
- );
- },
- },
- ],
- duration: 10_000,
- });
-
- handle.done.catch(() => {
- toast.failure('Failed to move to Trash');
- });
- };
-
- const shareTool: BlockTool = {
- group: 'sharing',
- label: 'Share',
- icon: IconShared,
- action: openShare,
- condition: () => ENABLE_EMAIL_SHARING,
- buttonComponent: () => (
- <ShareTrigger onClick={openShare} id={props.id} blockType="email" />
- ),
- focusTarget: getShareDrawerRecipientInput,
- };
-
- const emailActions: BlockTool[] = [
- {
- label: 'Mark done',
- icon: CheckIcon,
- action: toggleMarkDone,
- condition: () => isOwnThread() && !isDone(),
- hotkeyToken: TOKENS.entity.action.markDone,
- },
- {
- label: 'Mark as not done',
- icon: CheckBoldIcon,
- action: toggleMarkDone,
- condition: () =>
- isOwnThread() && isDone() && emailCtx.canMarkThreadNotDone(),
- hotkeyToken: TOKENS.entity.action.markNotDone,
- },
- {
- label: 'Mark unread',
- icon: EnvelopeSimpleOpenIcon,
- action: toggleMarkUnread,
- condition: () => isOwnThread() && !emailCtx.isThreadMarkedUnread(),
- hotkeyToken: TOKENS.entity.action.markUnread,
- },
- {
- label: 'Mark read',
- icon: EnvelopeSimpleIcon,
- action: toggleMarkUnread,
- condition: () => isOwnThread() && emailCtx.isThreadMarkedUnread(),
- hotkeyToken: TOKENS.entity.action.markRead,
- },
- {
- label: 'Ask Macro',
- icon: ChatWithAgentIcon,
- action: () => {
- const threadId = emailCtx.thread()?.db_id;
- if (!threadId) return;
- openChatWithAgent({ type: 'email', id: threadId, name: props.title });
- },
- condition: () => !!emailCtx.thread()?.db_id,
- },
- {
- label: 'Create task',
- icon: TaskIcon,
- action: () => props.onCreateTask?.(),
- condition: () => !!props.onCreateTask && !!emailCtx.thread()?.db_id,
- },
- shareTool,
- {
- group: 'file',
- label: 'Move to folder',
- icon: ArrowRightIcon,
- action: moveToFolder,
- condition: () => {
- const entity = emailEntity();
- return !!entity && moveToProjectAction.canExecute(entity);
- },
- },
- {
- group: 'delete',
- label: 'Delete',
- icon: TrashIcon,
- action: trashThread,
- condition: isOwnThread,
- },
- {
- group: 'sender',
- label: 'Sender → Noise',
- icon: NoiseIcon,
- action: () => emailCtx.markSenderNoise(),
- condition: isOwnThread,
- },
- {
- group: 'sender',
- label: 'Block Sender',
- icon: ProhibitIcon,
- action: () => emailCtx.blockSender(),
- condition: isOwnThread,
- },
- ];
+ type EmailThreadToolsOptions,
+ useEmailThreadTools,
+} from './useEmailThreadTools';
- const tools: BlockTool[] = [
- {
- label: 'Chat',
- icon: ChatWithAgentIcon,
- action: () => {
- const threadId = emailCtx.thread()?.db_id;
- if (!threadId) return;
- openChatWithAgent({ type: 'email', id: threadId, name: props.title });
- },
- condition: () => !!emailCtx.thread()?.db_id,
- buttonComponent: () => {
- const id = emailCtx.thread()?.db_id;
- return id ? (
- <ChatWithAgentButton
- entity={{ type: 'email', id, name: props.title }}
- />
- ) : null;
- },
- },
- shareTool,
- ];
+export function TopBar(props: EmailThreadToolsOptions) {
+ const { isInvite, tools, menuTools, controls } = useEmailThreadTools(props);
return (
<>
@@ -309,64 +37,13 @@ export function TopBar(props: {
/>
</SplitHeaderLeft>
- {/* Desktop-only Mark done button, sitting just left of the Previous item
- caret. On mobile this action lives in the bottom reply bar instead.
- A done thread shows a bold accent check and unarchives on click. */}
- <Show when={!isMobile()}>
- <SplitHeaderRight>
- {/* Read-state toggle. Viewing the thread marks it read, so it
- starts as Mark as unread; marking unread flips it to a bold
- accent closed envelope that re-marks the thread read. */}
- <Show when={isOwnThread()}>
- <Button
- size="icon-md"
- label={
- emailCtx.isThreadMarkedUnread()
- ? 'Mark as read'
- : 'Mark as unread'
- }
- hotkey={
- emailCtx.isThreadMarkedUnread()
- ? TOKENS.entity.action.markRead
- : TOKENS.entity.action.markUnread
- }
- onClick={toggleMarkUnread}
- // Keep focus (and the hotkey scope cmd-K reads) in the thread
- // content: focusing the header would hide its commands.
- onMouseDown={(e) => e.preventDefault()}
- >
- <Show
- when={emailCtx.isThreadMarkedUnread()}
- fallback={<EnvelopeSimpleOpenIcon class="size-4" />}
- >
- <EnvelopeSimpleIcon class="size-4 text-accent" />
- </Show>
- </Button>
- </Show>
- <Show when={isOwnThread() && showMarkDoneToggle()}>
- <Button
- size="icon-md"
- label={isDone() ? 'Mark as not done' : 'Mark done'}
- hotkey={
- isDone()
- ? TOKENS.entity.action.markNotDone
- : TOKENS.entity.action.markDone
- }
- onClick={toggleMarkDone}
- // Same focus-preservation as the read-state toggle above.
- onMouseDown={(e) => e.preventDefault()}
- >
- <Show when={isDone()} fallback={<CheckIcon class="size-4" />}>
- <CheckBoldIcon class="size-4 text-accent" />
- </Show>
- </Button>
- </Show>
- </SplitHeaderRight>
- </Show>
+ <SplitHeaderRight>
+ <EmailThreadControls {...controls} />
+ </SplitHeaderRight>
<ResponsiveBlockToolbar
tools={tools}
- menuTools={emailActions}
+ menuTools={menuTools}
ops={[]}
id={props.id}
itemType="email"
diff --git a/apps/web/src/features/block-email/component/useEmailThreadTools.tsx b/apps/web/src/features/block-email/component/useEmailThreadTools.tsx
new file mode 100644
index 0000000000..1b2b4f1a66
--- /dev/null
+++ b/apps/web/src/features/block-email/component/useEmailThreadTools.tsx
@@ -0,0 +1,314 @@
+import {
+ ChatWithAgentButton,
+ ChatWithAgentIcon,
+ openChatWithAgent,
+} from '@app/features/chat/ChatWithAgentButton';
+import type { EmailThreadListNavigation } from '@app/features/email-thread/context/email-thread-context';
+import { useEmailThreadState } from '@app/features/email-thread/context/email-thread-state-context';
+import { makeMoveToProjectAction } from '@app/features/next-soup/actions';
+import { useMaybeSoup } from '@app/features/next-soup/soup-context';
+import {
+ openEntityInSplitFromUnifiedList,
+ trashEmails,
+} from '@app/features/next-soup/utils';
+import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
+import { getPermissions } from '@core/component/SharePermissions';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ getShareDrawerRecipientInput,
+ ShareTrigger,
+} from '@core/component/TopBar/ShareButton';
+import { useShareModal } from '@core/component/TopBar/shareModal';
+import { ENABLE_EMAIL_SHARING } from '@core/constant/featureFlags';
+import { TOKENS } from '@core/hotkey/tokens';
+import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';
+import { buildEntityData } from '@entity';
+import IconShared from '@icon/share.svg';
+import ArrowRightIcon from '@phosphor/arrow-right.svg';
+import CheckIcon from '@phosphor/check.svg';
+import EnvelopeSimpleIcon from '@phosphor/envelope-simple.svg';
+import EnvelopeSimpleOpenIcon from '@phosphor/envelope-simple-open.svg';
+import TaskIcon from '@phosphor/list-checks.svg';
+import ProhibitIcon from '@phosphor/prohibit.svg';
+import TrashIcon from '@phosphor/trash.svg';
+import NoiseIcon from '@phosphor/waveform.svg';
+import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
+import { useEmailLinksQuery } from '@queries/email/link';
+import { queryReadyGate } from '@queries/gate';
+
+export type EmailThreadToolsOptions = {
+ id: string;
+ title: string;
+ isDraft?: boolean;
+ onCreateTask?: () => void;
+ onMarkedUnread?: () => void;
+ onDeleted?: () => void;
+ listNavigation?: EmailThreadListNavigation;
+};
+
+export function useEmailThreadTools(props: EmailThreadToolsOptions) {
+ const emailCtx = useEmailThreadState();
+ const openShare = useShareModal(() => {
+ const thread = emailCtx.thread();
+ if (!thread) return;
+ return {
+ id: props.id,
+ blockAlias: 'email',
+ itemType: 'email',
+ name: props.title,
+ userPermissions: getPermissions(thread.access_level),
+ };
+ });
+ const soup = useMaybeSoup();
+ const linksQuery = useEmailLinksQuery();
+ const moveToProjectAction = makeMoveToProjectAction();
+
+ const isInvite = () => {
+ const row = soup?.items.get(props.id);
+ const entity = row?.original;
+ return entity?.type === 'email' && entity.hasIcsAttachment === true;
+ };
+
+ const isOwnThread = () => {
+ const thread = emailCtx.thread();
+ if (!thread || !queryReadyGate(linksQuery)) return false;
+ return linksQuery.data.links.some((link) => link.id === thread.link_id);
+ };
+
+ const isDone = () => emailCtx.isThreadDone();
+
+ const emailEntity = () => {
+ const soupEntity = soup?.items.get(props.id)?.original;
+ if (soupEntity?.type === 'email') return soupEntity;
+
+ const thread = emailCtx.thread();
+ return buildEntityData({
+ id: props.id,
+ name: props.title,
+ blockName: 'email',
+ projectId: thread?.project_id ?? undefined,
+ isRead: thread?.is_read,
+ isDraft: props.isDraft,
+ done: thread ? !thread.inbox_visible : undefined,
+ });
+ };
+
+ const moveToFolder = () => {
+ const entity = emailEntity();
+ if (!entity || !moveToProjectAction.canExecute(entity)) return;
+ void moveToProjectAction.execute([entity]);
+ };
+
+ // A send-only thread is permanently done, so neither half of the toggle
+ // does anything — hide it rather than offer a no-op.
+ const showMarkDoneToggle = () => !isDone() || emailCtx.canMarkThreadNotDone();
+
+ const toggleMarkDone = () => {
+ if (isDone()) {
+ emailCtx.markThreadNotDone();
+ return;
+ }
+ if (props.listNavigation) {
+ props.listNavigation.markDone(emailCtx.archiveThread);
+ return;
+ }
+ // Prefer the active Mark done command so it drives soup navigation and
+ // notifications; fall back to archiving the thread directly. A command
+ // can be found but still decline (condition/handler returns false, e.g.
+ // the triage registration when not opened from inbox/mail), so gate on
+ // it actually capturing.
+ const command = getActiveCommandByToken(TOKENS.entity.action.markDone);
+ if (command && runCommand(command).commandCaptured) return;
+ emailCtx.archiveThread();
+ };
+
+ const toggleMarkUnread = () => {
+ if (emailCtx.isThreadMarkedUnread()) {
+ emailCtx.markThreadRead();
+ } else if (emailCtx.markThreadUnread()) {
+ props.onMarkedUnread?.();
+ }
+ };
+
+ const trashThread = () => {
+ const thread = emailCtx.thread();
+ if (!thread?.db_id) return;
+
+ // Calculate next row before trashing so we can navigate to it
+ const nextRow = (() => {
+ if (!soup) return undefined;
+ const currentIndex = soup.focus.index();
+ return soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
+ })();
+
+ const handle = trashEmails([{ id: thread.db_id, linkId: thread.link_id }]);
+
+ if (props.onDeleted) {
+ props.onDeleted();
+ } else if (soup && nextRow) {
+ soup.selection.clear();
+ soup.focus.set(nextRow.id);
+ openEntityInSplitFromUnifiedList(nextRow.original, {});
+ }
+
+ const toastId = toast.success('Moved to Trash', {
+ actions: [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ if (toastId != null) toast.dismiss(toastId);
+ handle.undo().then(
+ () => toast.success('Restored from Trash'),
+ () => toast.failure('Failed to restore from Trash')
+ );
+ },
+ },
+ ],
+ duration: 10_000,
+ });
+
+ handle.done.catch(() => {
+ toast.failure('Failed to move to Trash');
+ });
+ };
+
+ const shareTool: BlockTool = {
+ group: 'sharing',
+ label: 'Share',
+ icon: IconShared,
+ action: openShare,
+ condition: () => ENABLE_EMAIL_SHARING,
+ buttonComponent: () => (
+ <ShareTrigger onClick={openShare} id={props.id} blockType="email" />
+ ),
+ focusTarget: getShareDrawerRecipientInput,
+ };
+
+ const emailActions: BlockTool[] = [
+ {
+ label: 'Mark done',
+ icon: CheckIcon,
+ action: toggleMarkDone,
+ condition: () => isOwnThread() && !isDone(),
+ hotkeyToken: TOKENS.entity.action.markDone,
+ },
+ {
+ label: 'Mark as not done',
+ icon: CheckBoldIcon,
+ action: toggleMarkDone,
+ condition: () =>
+ isOwnThread() && isDone() && emailCtx.canMarkThreadNotDone(),
+ hotkeyToken: TOKENS.entity.action.markNotDone,
+ },
+ {
+ label: 'Mark unread',
+ icon: EnvelopeSimpleOpenIcon,
+ action: toggleMarkUnread,
+ condition: () => isOwnThread() && !emailCtx.isThreadMarkedUnread(),
+ hotkeyToken: TOKENS.entity.action.markUnread,
+ },
+ {
+ label: 'Mark read',
+ icon: EnvelopeSimpleIcon,
+ action: toggleMarkUnread,
+ condition: () => isOwnThread() && emailCtx.isThreadMarkedUnread(),
+ hotkeyToken: TOKENS.entity.action.markRead,
+ },
+ {
+ label: 'Ask Macro',
+ icon: ChatWithAgentIcon,
+ action: () => {
+ const threadId = emailCtx.thread()?.db_id;
+ if (!threadId) return;
+ openChatWithAgent({ type: 'email', id: threadId, name: props.title });
+ },
+ condition: () => !!emailCtx.thread()?.db_id,
+ },
+ {
+ label: 'Create task',
+ icon: TaskIcon,
+ action: () => props.onCreateTask?.(),
+ condition: () => !!props.onCreateTask && !!emailCtx.thread()?.db_id,
+ },
+ shareTool,
+ {
+ group: 'file',
+ label: 'Move to folder',
+ icon: ArrowRightIcon,
+ action: moveToFolder,
+ condition: () => {
+ const entity = emailEntity();
+ return !!entity && moveToProjectAction.canExecute(entity);
+ },
+ },
+ {
+ group: 'delete',
+ label: 'Delete',
+ icon: TrashIcon,
+ action: trashThread,
+ condition: isOwnThread,
+ },
+ {
+ group: 'sender',
+ label: 'Sender → Noise',
+ icon: NoiseIcon,
+ action: () => emailCtx.markSenderNoise(),
+ condition: isOwnThread,
+ },
+ {
+ group: 'sender',
+ label: 'Block Sender',
+ icon: ProhibitIcon,
+ action: () => emailCtx.blockSender(),
+ condition: isOwnThread,
+ },
+ ];
+
+ const tools: BlockTool[] = [
+ {
+ label: 'Chat',
+ icon: ChatWithAgentIcon,
+ action: () => {
+ const threadId = emailCtx.thread()?.db_id;
+ if (!threadId) return;
+ openChatWithAgent({ type: 'email', id: threadId, name: props.title });
+ },
+ condition: () => !!emailCtx.thread()?.db_id,
+ buttonComponent: () => {
+ const id = emailCtx.thread()?.db_id;
+ return id ? (
+ <ChatWithAgentButton
+ entity={{ type: 'email', id, name: props.title }}
+ />
+ ) : null;
+ },
+ },
+ shareTool,
+ ];
+
+ return {
+ isInvite,
+ emailEntity,
+ permissions: () => getPermissions(emailCtx.thread()?.access_level),
+ tools,
+ menuTools: emailActions,
+ controls: {
+ get isOwnThread() {
+ return isOwnThread();
+ },
+ get isDone() {
+ return isDone();
+ },
+ get isUnread() {
+ return emailCtx.isThreadMarkedUnread();
+ },
+ get canToggleDone() {
+ return showMarkDoneToggle();
+ },
+ onToggleDone: toggleMarkDone,
+ onToggleUnread: toggleMarkUnread,
+ },
+ };
+}
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index 70cb88e0ce..1c310829f2 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -1,3 +1,4 @@
+import { EntityDetailBreadcrumbSkeleton } from '@app/components/entity-detail/EntityDetailBreadcrumbSkeleton';
import { useListNavigationHotkeys } from '@app/components/entity-detail/use-list-navigation-hotkeys';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { displaySubject } from '@app/features/email-compose/core/subject-text';
@@ -5,15 +6,23 @@ import type { EmailThreadHost } from '@app/features/email-thread/context/email-t
import { createEmailThreadSource } from '@app/features/email-thread/queries/thread-source';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
import { createSearchParams, useRouteParams } from '@app/lib/split-router';
+import { EmailThreadControls } from '@block-email/component/EmailThreadControls';
import { EmailThreadLoadGate } from '@block-email/component/EmailThreadLoadGate';
+import {
+ type EmailThreadToolsOptions,
+ useEmailThreadTools,
+} from '@block-email/component/useEmailThreadTools';
import { EmailThreadHostView } from '@block-email/EmailThreadHostView';
import { registerEmailHotkeys } from '@block-email/util/emailHotkeys';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { SidePanel } from '@components/app/side-panel';
+import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';
+import { ListNavigationButtons } from '@components/app/split-layout/components/SplitHeader';
import {
useCanAutofocusSplitContent,
useSplitPanelOrThrow,
} from '@components/app/split-layout/layoutUtils';
+import { createSplitAutofocus } from '@components/app/split-layout/utils/createSplitAutofocus';
import { EntityIcon } from '@core/component/EntityIcon';
import { toEntityLoadError } from '@core/component/EntityLoadGate';
import { getPermissions } from '@core/component/SharePermissions';
@@ -26,39 +35,67 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { buildEntityData } from '@entity';
import { useThreadQuery } from '@queries/email/thread';
import { representativeThreadMessage } from '@queries/email/thread-subject';
-import { createEffect, createMemo, Show } from 'solid-js';
+import { createMemo, createSignal, Show } from 'solid-js';
+import { Portal } from 'solid-js/web';
import { emailDetailSearch } from '../email-route';
import { useEmailView } from '../email-view-context';
import { emailThreadRoute } from '../route';
import type { EmailThreadTarget } from '../types';
import { useEmailDetailListNavigation } from '../use-email-detail-list-navigation';
-function EmailThreadBreadcrumb(props: {
- value: string;
- title: string;
- threadId: string;
- focusThread: () => void;
-}) {
+function EmailDetailHeader(
+ props: EmailThreadToolsOptions & {
+ value: string;
+ focusThread: () => void;
+ controlsMount: HTMLDivElement | undefined;
+ }
+) {
+ const { emailEntity, permissions, menuTools, controls } =
+ useEmailThreadTools(props);
return (
- <ViewBreadcrumbs.Item
- value={props.value}
- metadata={{ type: 'email', id: props.threadId }}
- order={1}
- >
- {(item) => (
- <ViewBreadcrumbs.Button
- class="gap-1.5"
- isActive={item.isActive()}
- onClick={() => {
- item.onSelect();
- props.focusThread();
- }}
- >
- <EntityIcon targetType="email" size="xs" class="shrink-0" />
- <span class="truncate">{props.title}</span>
- </ViewBreadcrumbs.Button>
- )}
- </ViewBreadcrumbs.Item>
+ <>
+ <ViewBreadcrumbs.Item
+ value={props.value}
+ metadata={{ type: 'email', id: props.id }}
+ order={1}
+ >
+ {(item) => (
+ <div class="flex min-w-0 items-center gap-0.5">
+ <ViewBreadcrumbs.Button
+ class="gap-1.5"
+ isActive={item.isActive()}
+ onClick={() => {
+ item.onSelect();
+ props.focusThread();
+ }}
+ tooltip={props.title}
+ >
+ <EntityIcon targetType="email" size="xs" class="shrink-0" />
+ <span class="truncate">{props.title}</span>
+ </ViewBreadcrumbs.Button>
+ <div class="shrink-0">
+ <SplitFileMenu
+ id={props.id}
+ itemType="email"
+ entityKind="email"
+ name={props.title}
+ entity={emailEntity()}
+ permissions={permissions()}
+ ops={[]}
+ tools={menuTools}
+ />
+ </div>
+ </div>
+ )}
+ </ViewBreadcrumbs.Item>
+ <Show when={props.controlsMount}>
+ {(mount) => (
+ <Portal mount={mount()}>
+ <EmailThreadControls {...controls} />
+ </Portal>
+ )}
+ </Show>
+ </>
);
}
@@ -70,6 +107,7 @@ export function EmailDetailView(props: {
const panel = useSplitPanelOrThrow();
const notificationSource = useGlobalNotificationSource();
const canAutofocus = useCanAutofocusSplitContent();
+ const [controlsMount, setControlsMount] = createSignal<HTMLDivElement>();
const threadId = () => props.thread.id;
const threadQuery = useThreadQuery(threadId, () => ({
enabled: !!threadId(),
@@ -124,11 +162,9 @@ export function EmailDetailView(props: {
let container: HTMLDivElement | undefined;
const focusContainer = () => container?.focus({ preventScroll: true });
- let focused = false;
- createEffect(() => {
- if (focused || !canAutofocus || isTouchDevice() || !container) return;
- focusContainer();
- focused = true;
+ createSplitAutofocus({
+ element: () => container ?? null,
+ enabled: () => canAutofocus && panel.isPanelActive() && !isTouchDevice(),
});
const listNavigation = useEmailDetailListNavigation(threadId);
const hotkeyScope = () => panel.splitHotkeyScope;
@@ -161,6 +197,7 @@ export function EmailDetailView(props: {
enabled: () =>
panel.isPanelActive() && selectedThread()?.id === props.thread.id,
navigation: listNavigation,
+ arrowKeys: true,
});
const loadResult = {
data: threadData,
@@ -170,58 +207,68 @@ export function EmailDetailView(props: {
};
return (
- <>
- <EmailThreadBreadcrumb
- value={breadcrumbValue()}
- title={title()}
- threadId={props.thread.id}
- focusThread={focusContainer}
- />
- <SidePanel.Root defaultOpen={false}>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
- <ViewShell.TopBar class="touch:flex">
- <ViewBreadcrumbs.Outlet
- class="flex-1"
- aria-label="Email location"
- />
- <div class="ml-auto flex shrink-0 items-center gap-2">
- <Show when={ENABLE_EMAIL_SHARING}>
- <ShareTrigger
- onClick={openShare}
- id={props.thread.id}
- blockType="email"
- hotkeyScope={panel.splitHotkeyScope}
- />
- </Show>
- <SidePanel.Toggle />
+ <SidePanel.Root defaultOpen={false}>
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
+ <ViewShell.TopBar class="touch:flex">
+ <ViewBreadcrumbs.Outlet
+ class="flex-1"
+ aria-label="Email location"
+ fallback={<EntityDetailBreadcrumbSkeleton />}
+ />
+ <div class="ml-auto flex shrink-0 items-center gap-2">
+ <div ref={setControlsMount} class="flex items-center gap-0.5" />
+ <div class="touch:hidden">
+ <ListNavigationButtons navigation={listNavigation} />
</div>
- </ViewShell.TopBar>
- <div
- ref={container}
- class="relative min-h-0 min-w-0 flex-1"
- tabIndex={-1}
- >
- <EmailThreadLoadGate
- result={loadResult}
- notificationSource={notificationSource}
- threadId={props.thread.id}
- linkId={threadData()?.thread?.link_id}
- debounceTime={100}
- onRetry={() => void threadQuery.refetch()}
- >
- <EmailThreadHostView
- title={title()}
- threadId={threadId}
- source={source}
- threadTransport={() => threadQuery.transport}
- host={host}
- sidePanelHeaderToggle={false}
+ <Show when={ENABLE_EMAIL_SHARING}>
+ <ShareTrigger
+ onClick={openShare}
+ id={props.thread.id}
+ blockType="email"
+ hotkeyScope={panel.splitHotkeyScope}
/>
- </EmailThreadLoadGate>
+ </Show>
+ <SidePanel.Toggle />
</div>
+ </ViewShell.TopBar>
+ <div
+ ref={container}
+ class="relative min-h-0 min-w-0 flex-1"
+ tabIndex={-1}
+ >
+ <EmailThreadLoadGate
+ result={loadResult}
+ notificationSource={notificationSource}
+ threadId={props.thread.id}
+ linkId={threadData()?.thread?.link_id}
+ debounceTime={100}
+ onRetry={() => void threadQuery.refetch()}
+ >
+ <EmailThreadHostView
+ title={title()}
+ threadId={threadId}
+ source={source}
+ threadTransport={() => threadQuery.transport}
+ host={host}
+ chrome={({ createTask }) => (
+ <EmailDetailHeader
+ id={props.thread.id}
+ title={title()}
+ onCreateTask={createTask}
+ onMarkedUnread={closeThread}
+ onDeleted={closeThread}
+ listNavigation={listNavigation}
+ value={breadcrumbValue()}
+ focusThread={focusContainer}
+ controlsMount={controlsMount()}
+ />
+ )}
+ sidePanelHeaderToggle={false}
+ />
+ </EmailThreadLoadGate>
</div>
- </SidePanel.Root>
- </>
+ </div>
+ </SidePanel.Root>
);
}
diff --git a/apps/web/src/features/email-view/components/EmailHeader.tsx b/apps/web/src/features/email-view/components/EmailHeader.tsx
index d3817bd0a9..4ac368292f 100644
--- a/apps/web/src/features/email-view/components/EmailHeader.tsx
+++ b/apps/web/src/features/email-view/components/EmailHeader.tsx
@@ -32,6 +32,7 @@ export function EmailViewBreadcrumbItem() {
>
{(item) => (
<ViewBreadcrumbs.Button
+ class="shrink-0 rounded-md hover:bg-hover"
isActive={item.isActive()}
onClick={item.onSelect}
>
diff --git a/apps/web/src/lib/split-router/integrations/solid-router.ts b/apps/web/src/lib/split-router/integrations/solid-router.ts
index e754954bcb..b140a8f2ac 100644
--- a/apps/web/src/lib/split-router/integrations/solid-router.ts
+++ b/apps/web/src/lib/split-router/integrations/solid-router.ts
@@ -1,5 +1,12 @@
-import { type Accessor, createEffect, createRoot, on } from 'solid-js';
-import { browserEntryKeySignature } from '../entry-state';
+import {
+ type Accessor,
+ createEffect,
+ createRoot,
+ on,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import { externalLocationSignature } from '../location-sync';
import type {
SplitRouterExternalLocation,
SplitRouterExternalLocationValue,
@@ -24,6 +31,9 @@ export type SolidRouterLocationOptions = {
export function createSolidRouterLocation(
options: SolidRouterLocationOptions
): SplitRouterExternalLocation {
+ const pendingCommits = new Set<ReturnType<typeof setTimeout>>();
+ const dispatchedCommits: string[] = [];
+ let subscriptions = 0;
const read = (): SplitRouterExternalLocationValue => {
const location: SplitRouterExternalLocationValue = {
pathname: options.pathname(),
@@ -33,25 +43,47 @@ export function createSolidRouterLocation(
if (options.state) location.state = options.state();
return location;
};
+ let observedSignature = externalLocationSignature(untrack(read));
+ const cancelPendingCommits = () => {
+ for (const timer of pendingCommits) clearTimeout(timer);
+ pendingCommits.clear();
+ };
return {
read,
subscribe(listener) {
+ if (subscriptions === 0) {
+ // The location may have changed while no subscribers were observing it.
+ observedSignature = externalLocationSignature(untrack(read));
+ }
+ subscriptions += 1;
return createRoot((dispose) => {
+ onCleanup(() => {
+ subscriptions -= 1;
+ if (subscriptions > 0) return;
+ cancelPendingCommits();
+ dispatchedCommits.length = 0;
+ });
createEffect(
on(
- () => {
- const location = read();
-
- return JSON.stringify([
- location.pathname,
- location.search,
- location.hash,
- browserEntryKeySignature(location.state),
- ]);
+ () => externalLocationSignature(read()),
+ (signature) => {
+ // Process each change once even when several subscribers observe it.
+ if (signature !== observedSignature) {
+ observedSignature = signature;
+ const index = dispatchedCommits.lastIndexOf(signature);
+ if (index >= 0) {
+ // An echo of our own navigation must not cancel newer writes.
+ dispatchedCommits.splice(0, index + 1);
+ } else {
+ // Back/Forward or another navigator supersedes queued writes.
+ cancelPendingCommits();
+ dispatchedCommits.length = 0;
+ }
+ }
+ listener(read());
},
- () => listener(read()),
{ defer: true }
)
);
@@ -61,10 +93,20 @@ export function createSolidRouterLocation(
},
commit(location, commitOptions) {
- options.navigate(externalLocationToString(location), {
- replace: commitOptions.history === 'replace',
- state: location.state,
- });
+ // Zone.js, used for tracing, wraps focus event handlers and can run queued
+ // microtasks when those handlers finish. Navigating immediately can let
+ // Solid Router's transition start before the split finishes mounting,
+ // leaving onMount callbacks unrun and the preview blank. Defer navigation
+ // to the next event-loop task so the current mount can finish first.
+ const timer = setTimeout(() => {
+ pendingCommits.delete(timer);
+ dispatchedCommits.push(externalLocationSignature(location));
+ options.navigate(externalLocationToString(location), {
+ replace: commitOptions.history === 'replace',
+ state: location.state,
+ });
+ }, 0);
+ pendingCommits.add(timer);
},
};
}
diff --git a/apps/web/src/lib/split-router/location-sync.ts b/apps/web/src/lib/split-router/location-sync.ts
index fef20f593e..3965e5f0c0 100644
--- a/apps/web/src/lib/split-router/location-sync.ts
+++ b/apps/web/src/lib/split-router/location-sync.ts
@@ -8,7 +8,7 @@ import type {
} from './types';
import { encodeSplitRouterLocation } from './url';
-function externalLocationSignature(
+export function externalLocationSignature(
location: SplitRouterExternalLocationValue
): string {
const query = [...new URLSearchParams(location.search)].sort(
diff --git a/apps/web/src/lib/split-router/tests/solid-router-location.test.ts b/apps/web/src/lib/split-router/tests/solid-router-location.test.ts
new file mode 100644
index 0000000000..79cac88b2a
--- /dev/null
+++ b/apps/web/src/lib/split-router/tests/solid-router-location.test.ts
@@ -0,0 +1,205 @@
+import { createSignal, startTransition } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createSolidRouterLocation } from '../integrations/solid-router';
+import { createLocationSync } from '../location-sync';
+import { createRoutesManifest, decodeRoute } from '../routes';
+import type { SplitRouterExternalLocationValue } from '../types';
+import { parseExternalLocation } from '../url';
+
+const disposers: Array<() => void> = [];
+
+afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+ vi.useRealTimers();
+});
+
+function setup() {
+ vi.useFakeTimers();
+ const [external, setExternal] =
+ createSignal<SplitRouterExternalLocationValue>(
+ parseExternalLocation('/item/current')
+ );
+ const navigate = vi.fn((url: string, options: { state?: unknown }) => {
+ setExternal({ ...parseExternalLocation(url), state: options.state });
+ });
+ const location = createSolidRouterLocation({
+ pathname: () => external().pathname,
+ search: () => external().search,
+ hash: () => external().hash,
+ state: () => external().state,
+ navigate,
+ });
+ const listener = vi.fn();
+ const unsubscribe = location.subscribe(listener);
+ disposers.push(unsubscribe);
+ const commit = (url: string) =>
+ location.commit(parseExternalLocation(url), { history: 'push' });
+ return {
+ external,
+ setExternal,
+ navigate,
+ location,
+ listener,
+ commit,
+ unsubscribe,
+ };
+}
+
+describe('deferred Solid Router location commits', () => {
+ it('cancels pending commits on Back after reconnecting subscribers', async () => {
+ const { external, setExternal, navigate, location, commit, unsubscribe } =
+ setup();
+ const original = external();
+ unsubscribe();
+ setExternal(parseExternalLocation('/item/away'));
+ const listener = vi.fn();
+ disposers.push(location.subscribe(listener));
+
+ commit('/item/queued');
+ setExternal(original);
+ await vi.runAllTimersAsync();
+
+ expect(navigate).not.toHaveBeenCalled();
+ expect(external()).toEqual(original);
+ expect(listener).toHaveBeenLastCalledWith(original);
+ });
+
+ it.each([
+ parseExternalLocation('/item/back'),
+ parseExternalLocation('/item/current?filter=unread'),
+ parseExternalLocation('/item/current#message'),
+ {
+ ...parseExternalLocation('/item/current'),
+ state: { __macroSplitRouter: { entries: [{ key: 'older-entry' }] } },
+ },
+ ])(
+ 'cancels pending commits when external navigation changes to %j',
+ async (back) => {
+ const { external, setExternal, navigate, listener, commit } = setup();
+ commit('/item/first');
+ commit('/item/second');
+
+ setExternal(back);
+ await vi.runAllTimersAsync();
+
+ expect(navigate).not.toHaveBeenCalled();
+ expect(external()).toEqual(back);
+ expect(listener).toHaveBeenLastCalledWith(back);
+
+ commit('/item/fresh');
+ await vi.runAllTimersAsync();
+ expect(navigate).toHaveBeenCalledExactlyOnceWith('/item/fresh', {
+ replace: false,
+ state: undefined,
+ });
+ }
+ );
+
+ it.each(['synchronous', 'transition'])(
+ 'preserves newer queued commits when its own %s navigation is observed by multiple subscribers',
+ async (mode) => {
+ const { external, setExternal, navigate, location, commit } = setup();
+ if (mode === 'transition') {
+ navigate.mockImplementation((url, options) => {
+ void startTransition(() =>
+ setExternal({ ...parseExternalLocation(url), state: options.state })
+ );
+ });
+ }
+ const secondListener = vi.fn();
+ disposers.push(location.subscribe(secondListener));
+
+ commit('/item/first');
+ commit('/item/second');
+ await vi.runAllTimersAsync();
+
+ expect(navigate.mock.calls.map(([url]) => url)).toEqual([
+ '/item/first',
+ '/item/second',
+ ]);
+ expect(external().pathname).toBe('/item/second');
+ expect(secondListener).toHaveBeenCalledTimes(2);
+ }
+ );
+
+ it('expires coalesced echoes so Back to an older commit cancels a pending write', async () => {
+ const { external, setExternal, navigate, commit } = setup();
+ navigate.mockImplementation(() => {});
+ commit('/item/first');
+ commit('/item/second');
+ await vi.runAllTimersAsync();
+ setExternal(parseExternalLocation('/item/second'));
+ navigate.mockClear();
+
+ commit('/item/third');
+ setExternal(parseExternalLocation('/item/first'));
+ await vi.runAllTimersAsync();
+
+ expect(navigate).not.toHaveBeenCalled();
+ expect(external().pathname).toBe('/item/first');
+ });
+
+ it('lets Back supersede a queued commit after an earlier commit has been observed', async () => {
+ const { external, setExternal, navigate, commit } = setup();
+ navigate.mockImplementationOnce((url, options) => {
+ setExternal({ ...parseExternalLocation(url), state: options.state });
+ setExternal(parseExternalLocation('/item/back'));
+ });
+
+ commit('/item/first');
+ commit('/item/second');
+ await vi.runAllTimersAsync();
+
+ expect(navigate).toHaveBeenCalledTimes(1);
+ expect(external().pathname).toBe('/item/back');
+ });
+
+ it('keeps location-sync acknowledgements consistent when Back cancels a queued commit', async () => {
+ const { external, setExternal, navigate, location } = setup();
+ const routes = createRoutesManifest({
+ definitions: [{ id: 'item', path: 'item/:id' }],
+ });
+ const sync = createLocationSync({ routes, location });
+ const acknowledge = vi.fn((next: SplitRouterExternalLocationValue) =>
+ sync.acknowledge(next)
+ );
+ disposers.push(location.subscribe(acknowledge));
+ const commit = (id: string) =>
+ sync.commit([{ ...decodeRoute(routes, ['item', id])!, key: id }], {
+ history: 'push',
+ preserveHash: false,
+ });
+
+ commit('first');
+ await vi.runAllTimersAsync();
+ const first = external();
+ commit('second');
+ commit('third');
+ await vi.runAllTimersAsync();
+ expect(navigate.mock.calls.map(([url]) => url)).toEqual([
+ '/item/first',
+ '/item/second',
+ '/item/third',
+ ]);
+ expect(acknowledge.mock.results.map(({ value }) => value)).toEqual([
+ true,
+ true,
+ true,
+ ]);
+
+ navigate.mockClear();
+ commit('fourth');
+ setExternal(first);
+ await vi.runAllTimersAsync();
+ expect(acknowledge).toHaveLastReturnedWith(false);
+ expect(navigate).not.toHaveBeenCalled();
+ expect(external()).toEqual(first);
+
+ // A cancelled request must not prevent a later attempt at the same destination.
+ commit('fourth');
+ await vi.runAllTimersAsync();
+ expect(navigate).toHaveBeenCalledTimes(1);
+ expect(external().pathname).toBe('/item/fourth');
+ expect(acknowledge).toHaveLastReturnedWith(true);
+ });
+});
diff --git a/apps/web/src/lib/split-router/tests/solid.test.tsx b/apps/web/src/lib/split-router/tests/solid.test.tsx
index 06497bfa32..6012c7c945 100644
--- a/apps/web/src/lib/split-router/tests/solid.test.tsx
+++ b/apps/web/src/lib/split-router/tests/solid.test.tsx
@@ -1,5 +1,11 @@
import { cleanup, fireEvent, render } from '@solidjs/testing-library';
-import { type Accessor, onCleanup } from 'solid-js';
+import {
+ type Accessor,
+ createSignal,
+ onCleanup,
+ onMount,
+ startTransition,
+} from 'solid-js';
import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
import { z } from 'zod';
import {
@@ -7,6 +13,7 @@ import {
type SetSearchParams,
} from '../create-search-params';
import { createMemorySplitRouterLocation } from '../integrations/memory';
+import { createSolidRouterLocation } from '../integrations/solid-router';
import { defineRoute, defineRoutes } from '../routes';
import {
SplitRouter,
@@ -102,6 +109,7 @@ const schema = z.object({
afterEach(() => {
cleanup();
vi.restoreAllMocks();
+ vi.useRealTimers();
});
describe('Solid split router hooks', () => {
@@ -398,6 +406,84 @@ describe('Solid split router hooks', () => {
expect(disposals).toBe(1);
});
+ it('mounts keyed details before synchronizing their browser URLs', async () => {
+ vi.useFakeTimers();
+ const [external, setExternal] = createSignal({
+ pathname: '/detail/one',
+ state: undefined as unknown,
+ });
+ let mountedId: string | undefined;
+ let router!: ReturnType<typeof useSplitRouter<string>>;
+ const commits: Array<{ url: string; mountedId: string | undefined }> = [];
+ const location = createSolidRouterLocation({
+ pathname: () => external().pathname,
+ state: () => external().state,
+ navigate: (url, options) => {
+ commits.push({ url, mountedId });
+ return startTransition(() =>
+ setExternal({ pathname: url, state: options.state })
+ );
+ },
+ });
+ const View = () => {
+ router = useSplitRouter<string>();
+ const { id } = useParams<{ id: string }>();
+ onMount(() => {
+ mountedId = id;
+ });
+ onCleanup(() => {
+ mountedId = undefined;
+ });
+ return <article>{id}</article>;
+ };
+ const view = render(() => (
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={{
+ definitions: [
+ {
+ id: 'detail',
+ path: 'detail/:id',
+ component: View,
+ remountKey: (params) =>
+ typeof params.id === 'string' ? params.id : undefined,
+ },
+ ],
+ }}
+ location={location}
+ >
+ <SplitRouter.Outlet splitId="split" />
+ </SplitRouter.Root>
+ ));
+ await vi.runAllTimersAsync();
+ commits.length = 0;
+
+ for (const id of ['two', 'three', 'two', 'one']) {
+ router.navigate('split', `/detail/${id}`);
+ expect(view.getByRole('article').textContent).toBe(id);
+ await vi.runAllTimersAsync();
+ expect(commits.at(-1)).toEqual({ url: `/detail/${id}`, mountedId: id });
+ }
+ expect(commits).toHaveLength(4);
+ });
+
+ it('cancels pending browser URL updates when the router is disposed', async () => {
+ vi.useFakeTimers();
+ const navigate = vi.fn();
+ const location = createSolidRouterLocation({
+ pathname: () => '/drive',
+ navigate,
+ });
+ const unsubscribe = location.subscribe(() => {});
+ location.commit(
+ { pathname: '/drive/folder/one', search: '', hash: '' },
+ { history: 'push' }
+ );
+ unsubscribe();
+ await vi.runAllTimersAsync();
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
it.each(['invalid', 'updated_at'])(
'canonicalizes %s search with replacement rather than a new history entry',
async (sort) => {
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 45e0c7d27a..1d54f41be2 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -440,7 +440,24 @@ HTTP and WebSockets. iOS shares the native cache code but is not yet covered by
that driver.
In the new Email view, ordinary row activation opens the thread inside
-`/app/component/mail`; the Email breadcrumb returns to the filtered list.
+`/app/component/mail`; the view breadcrumb (for example Signal) has a hover
+background and returns to the filtered list. The inline header uses the existing
+email title menu: open the menu button beside the subject for **Ask AI**, **Create a
+Task**, and the other thread actions. On desktop, **Mark as unread**, **Mark done**,
+and **Previous item** / **Next item** sit at the right of that header. The arrows
+follow the current filtered list and disable at its ends. Mark done advances in
+that list. Mark as unread (in the header or title menu) returns to the originating
+list with its tab, inbox, and filters preserved. Mark as not done and Mark as read
+stay on the current thread.
+Opening a saved draft from **Drafts** keeps the subject breadcrumb, title menu,
+and applicable header controls visible above the composer. Verify these remain
+available when returning to Drafts and reopening the draft.
+**Delete** in the title menu moves the thread to Trash and returns to the same
+filtered list. Its toast offers **Undo** to restore the email.
+Verify that opening the title menu, returning to the list, and reopening a thread
+preserve working menu actions and header controls. Repeatedly navigate forward
+and backward, including after returning to the list: the subject and email body
+should remain visible without reloading.
Shift-click opens a standalone split at `/app/email/<thread-id>`, which remains
the destination for direct links and legacy surfaces. Click a message header to
expand or collapse it; `Show N hidden messages` reveals the collapsed middle of
@@ -1322,7 +1339,8 @@ without comment permission have no comment composer, so Ask AI remains visible.
On touch devices, an email thread's floating action bar has Previous email and
Next email arrows beside the larger Mark done checkmark. The arrows follow the
source list's filtered order, skip non-email items, and disable at its ends.
-`J` and `K` use that same order in the Email view. They do not wrap; a thread
+`J` / `ArrowRight` and `K` / `ArrowLeft` use that same order in the Email view.
+Arrow keys in a reply editor or other text input keep their normal editing behavior. They do not wrap; a thread
opened without a source list has disabled arrows.
Mark done archives the current thread and opens the next email in that same
filtered list, loading pages until another email is found or the list ends.