Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): keep next and previous working after the open thread leaves (#8227)
teo798e7fde8013
diff --git a/apps/web/src/components/list/use-list-detail-navigation.ts b/apps/web/src/components/list/use-list-detail-navigation.tsindex 39e68a770e..03017ca5af 100644--- a/apps/web/src/components/list/use-list-detail-navigation.ts+++ b/apps/web/src/components/list/use-list-detail-navigation.ts@@ -1,5 +1,5 @@import { fireAndForget } from '@core/util/fireAndForget';-import { type Accessor, createSignal, onCleanup } from 'solid-js';+import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';import type { ListDataSource } from './list-data-source';export type ListDetailNavigationTarget = {@@ -57,15 +57,64 @@ export function useListDetailNavigation<.map(options.getEntity).find((entity) => entity?.id === options.currentId());+ // Where the open entity sat when it was opened. Next and previous step+ // from there even after it moves (a reply draft lifts a thread to the top+ // of Signal) or leaves the list (a reply marks it done, another device+ // archives it).+ const anchor = createMemo<+ { id: string; next: string[]; previous: string[] } | undefined+ >((previous) => {+ const id = options.currentId();+ if (previous?.id === id) return previous;+ const ids = options.source.items().flatMap((item) => {+ const entity = options.getEntity(item);+ return entity ? [entity.id] : [];+ });+ const index = ids.indexOf(id);+ if (index === -1) return undefined;+ return {+ id,+ next: ids.slice(index + 1),+ previous: ids.slice(0, index).reverse(),+ };+ });++ const startIndex = (items: readonly TItem[], direction: -1 | 1) => {+ const indexById = new Map<string, number>();+ items.forEach((item, index) => {+ const entity = options.getEntity(item);+ if (entity) indexById.set(entity.id, index);+ });+ const id = options.currentId();+ const position = anchor();+ if (position?.id !== id) {+ const current = indexById.get(id);+ return current === undefined ? undefined : current + direction;+ }+ // The entity sat just after its nearest surviving earlier neighbour, so+ // stepping forward starts there, through any load-more row in between.+ for (const neighbour of position.previous) {+ const index = indexById.get(neighbour);+ if (index !== undefined) return direction === 1 ? index + 1 : index;+ }+ // Otherwise the nearest surviving later neighbour took its place.+ for (const neighbour of position.next) {+ const index = indexById.get(neighbour);+ if (index !== undefined) return direction === 1 ? index : index - 1;+ }+ // No neighbour it was opened beside remains (it was the only row loaded):+ // step from where it is now.+ const current = indexById.get(id);+ return current === undefined ? undefined : current + direction;+ };+const target = (direction: -1 | 1): NavigationStep<TEntity> | undefined => {const items = options.source.items();- const currentIndex = items.findIndex(- (item) => options.getEntity(item)?.id === options.currentId()- );- if (currentIndex === -1) return;+ const start = startIndex(items, direction);+ if (start === undefined) return;for (- let index = currentIndex + direction;+ let index = start;index >= 0 && index < items.length;index += direction) {@@ -73,6 +122,8 @@ export function useListDetailNavigation<if (!item) continue;const entity = options.getEntity(item);+ // The open entity itself may have moved into the path.+ if (entity?.id === options.currentId()) continue;if (entity) return { kind: 'entity', entity };const load =diff --git a/apps/web/src/features/block-email/use-email-list-navigation.test.ts b/apps/web/src/features/block-email/use-email-list-navigation.test.tsindex e971cbd7f4..ad0e07fd3c 100644--- a/apps/web/src/features/block-email/use-email-list-navigation.test.ts+++ b/apps/web/src/features/block-email/use-email-list-navigation.test.ts@@ -2,7 +2,7 @@ import type { ArchiveThreadOptions } from '@app/features/email-thread/context/emimport { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';import type { SplitId } from '@components/app/split-layout/layoutManager';import type { EntityData } from '@entity';-import { createRoot } from 'solid-js';+import { createRoot, createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useEmailListNavigation } from './use-email-list-navigation';@@ -338,3 +338,84 @@ describe('email list navigation adapter', () => {dispose();});});++describe('after the open thread leaves the list', () => {+ function reactiveSource(initial: string[]) {+ const [rows, setRows] = createSignal(initial);+ disposeSource();+ disposeSource = createRoot((dispose) => {+ registerListNavigationSource(+ {+ id: 'email-split' as SplitId,+ content: () => ({ type: 'component', id: 'mail' }),+ registerEntryStateCaptor: () => () => {},+ },+ {+ viewId: 'mail',+ entities: () =>+ rows().map((id) => ({ id, type: 'email' }) as EntityData),+ hasMore: () => mocks.hasMore,+ loadMore: mocks.loadMore,+ }+ );+ return dispose;+ });+ return setRows;+ }++ it('keeps next and previous on its former neighbours', async () => {+ const setRows = reactiveSource(['a', 'b', 'c']);+ const [nav, dispose] = createRoot(+ (dispose) => [createNavigation(() => 'b'), dispose] as const+ );+ setRows(['a', 'c']);+ expect(nav.canNext()).toBe(true);+ expect(nav.canPrevious()).toBe(true);+ nav.next();+ await vi.waitFor(() =>+ expect(mocks.open).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: 'c' }),+ expect.anything()+ )+ );+ dispose();+ });++ it('pages on after a surviving earlier neighbour when it was last', async () => {+ mocks.hasMore = true;+ const setRows = reactiveSource(['a', 'b']);+ mocks.loadMore.mockImplementation(async () => {+ setRows(['a', 'c']);+ mocks.hasMore = false;+ });+ const [nav, dispose] = createRoot(+ (dispose) => [createNavigation(() => 'b'), dispose] as const+ );+ setRows(['a']);+ nav.next();+ await vi.waitFor(() =>+ expect(mocks.open).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: 'c' }),+ expect.anything()+ )+ );+ expect(mocks.loadMore).toHaveBeenCalledOnce();+ dispose();+ });++ it('does not page through the mailbox when no former neighbour survives', async () => {+ mocks.hasMore = true;+ const setRows = reactiveSource(['a', 'b', 'c']);+ const [nav, dispose] = createRoot(+ (dispose) => [createNavigation(() => 'b'), dispose] as const+ );+ // Every loaded row was archived on another device.+ setRows([]);+ expect(nav.canNext()).toBe(false);+ nav.next();+ await Promise.resolve();+ expect(mocks.loadMore).not.toHaveBeenCalled();+ expect(mocks.open).not.toHaveBeenCalled();+ dispose();+ });+});diff --git a/apps/web/src/features/block-email/use-email-list-navigation.ts b/apps/web/src/features/block-email/use-email-list-navigation.tsindex f02a08e686..724c3061c6 100644--- a/apps/web/src/features/block-email/use-email-list-navigation.ts+++ b/apps/web/src/features/block-email/use-email-list-navigation.ts@@ -2,7 +2,11 @@ import type {EmailThreadCommands,EmailThreadListNavigation,} from '@app/features/email-thread/context/email-thread-context';-import { adjacentEmail } from '@app/features/email-thread/core/adjacent-email';+import {+ adjacentEmail,+ type EmailPosition,+ emailPosition,+} from '@app/features/email-thread/core/adjacent-email';import { useMaybeSoup } from '@app/features/next-soup/soup-context';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import {@@ -14,7 +18,7 @@ import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { toast } from '@core/component/Toast/Toast';import { fireAndForget } from '@core/util/fireAndForget';import type { EntityData } from '@entity';-import { type Accessor, createSignal, onCleanup } from 'solid-js';+import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';/** Keep thread controls tied to the list and filters the user opened it from. */export function useEmailListNavigation(@@ -41,13 +45,24 @@ export function useEmailListNavigation(if (from !== 'mail' && from !== 'home') return [];return soup?.rows().map((row) => row.original) ?? [];};+ // Where the open thread sat when it was opened: next and previous keep+ // stepping from there after it moves or leaves the list.+ const position = createMemo<EmailPosition | undefined>((previous) =>+ previous?.id === threadId()+ ? previous+ : emailPosition(entities(), threadId())+ );const target = (direction: -1 | 1) =>- adjacentEmail(entities(), threadId(), direction);- const canLoadNext = () =>- !!source()?.hasMore() &&- entities().some(- (entity) => entity.type === 'email' && entity.id === threadId()- );+ adjacentEmail(entities(), threadId(), direction, position());+ // More pages place a thread that left the list only after a surviving+ // earlier neighbour (their first row follows it). With none, paging could+ // never find a next email, so it would load the whole mailbox.+ const canLoadNext = () => {+ const at = position();+ if (!source()?.hasMore() || at?.id !== threadId()) return false;+ const listed = new Set(entities().map((entity) => entity.id));+ return listed.has(at.id) || at.previous.some((id) => listed.has(id));+ };const open = async (entity: EntityData,referredFrom = panel?.handle.referredFrom()diff --git a/apps/web/src/features/email-thread/core/adjacent-email.test.ts b/apps/web/src/features/email-thread/core/adjacent-email.test.tsindex a2f5f3c56b..200fb62f24 100644--- a/apps/web/src/features/email-thread/core/adjacent-email.test.ts+++ b/apps/web/src/features/email-thread/core/adjacent-email.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { adjacentEmail } from './adjacent-email';+import { adjacentEmail, emailPosition } from './adjacent-email';const rows = [{ id: 'a', type: 'email' },@@ -22,4 +22,32 @@ describe('adjacent email navigation', () => {expect(adjacentEmail(rows, 'missing', 1)).toBeUndefined();expect(adjacentEmail([], 'a', -1)).toBeUndefined();});+ it('steps from the former neighbours once the current thread leaves', () => {+ const former = emailPosition(rows, 'b');+ const remaining = rows.filter((row) => row.id !== 'b');+ expect(adjacentEmail(remaining, 'b', 1, former)?.id).toBe('c');+ expect(adjacentEmail(remaining, 'b', -1, former)?.id).toBe('a');+ });+ it('keeps its opened neighbours after the thread moves to the top', () => {+ const former = emailPosition(rows, 'b');+ // A reply draft lifts b above a.+ const moved = [rows[2], rows[0], rows[1], rows[4]];+ expect(adjacentEmail(moved, 'b', 1, former)?.id).toBe('c');+ expect(adjacentEmail(moved, 'b', -1, former)?.id).toBe('a');+ });+ it('skips former neighbours that left with it', () => {+ const list = ['a', 'b', 'c', 'd'].map((id) => ({ id, type: 'email' }));+ const former = emailPosition(list, 'b');+ const remaining = list.filter((row) => row.id === 'a' || row.id === 'd');+ expect(adjacentEmail(remaining, 'b', 1, former)?.id).toBe('d');+ expect(adjacentEmail(remaining, 'b', -1, former)?.id).toBe('a');+ });+ it('steps into rows loaded after a removed last thread', () => {+ const former = emailPosition(rows, 'c');+ const loaded = [+ ...rows.filter((row) => row.id !== 'c'),+ { id: 'd', type: 'email' },+ ];+ expect(adjacentEmail(loaded, 'c', 1, former)?.id).toBe('d');+ });});diff --git a/apps/web/src/features/email-thread/core/adjacent-email.ts b/apps/web/src/features/email-thread/core/adjacent-email.tsindex bf10e72480..36090c8676 100644--- a/apps/web/src/features/email-thread/core/adjacent-email.ts+++ b/apps/web/src/features/email-thread/core/adjacent-email.ts@@ -1,15 +1,63 @@-/** Find a neighboring thread in list order, skipping non-email rows and duplicates. */-export function adjacentEmail<T extends { id: string; type: string }>(- entities: readonly T[],- currentId: string,- direction: -1 | 1-): T | undefined {+/** Where an email sat among the list's emails, nearest neighbours first. */+export type EmailPosition = {+ id: string;+ next: string[];+ previous: string[];+};++function uniqueEmails<T extends { id: string; type: string }>(+ entities: readonly T[]+): T[] {const seen = new Set<string>();- const emails = entities.filter((entity) => {+ return entities.filter((entity) => {if (entity.type !== 'email' || seen.has(entity.id)) return false;seen.add(entity.id);return true;});- const index = emails.findIndex((entity) => entity.id === currentId);- return index < 0 ? undefined : emails[index + direction];+}++/** The email's current position, or undefined when it is not in the list. */+export function emailPosition<T extends { id: string; type: string }>(+ entities: readonly T[],+ currentId: string+): EmailPosition | undefined {+ const ids = uniqueEmails(entities).map((entity) => entity.id);+ const index = ids.indexOf(currentId);+ if (index < 0) return undefined;+ return {+ id: currentId,+ next: ids.slice(index + 1),+ previous: ids.slice(0, index).reverse(),+ };+}++/**+ * Find a neighboring thread in list order, skipping non-email rows and+ * duplicates. `former`, where the thread sat when it was opened, places it+ * between its surviving former neighbours even after it moved (a reply draft+ * lifts it to the top of Signal) or left the list (a reply marked it done).+ */+export function adjacentEmail<T extends { id: string; type: string }>(+ entities: readonly T[],+ currentId: string,+ direction: -1 | 1,+ former?: EmailPosition+): T | undefined {+ const all = uniqueEmails(entities);+ if (former?.id !== currentId) {+ const index = all.findIndex((entity) => entity.id === currentId);+ return index >= 0 ? all[index + direction] : undefined;+ }+ const emails = all.filter((entity) => entity.id !== currentId);+ const indexById = new Map(emails.map((entity, i) => [entity.id, i]));+ const survivor = (ids: string[]) =>+ ids.map((id) => indexById.get(id)).find((i) => i !== undefined);+ const before = survivor(former.previous);+ if (before !== undefined)+ return emails[direction === 1 ? before + 1 : before];+ const after = survivor(former.next);+ if (after !== undefined) return emails[direction === 1 ? after : after - 1];+ // No neighbour it was opened beside remains: step from where it is now.+ const index = all.findIndex((entity) => entity.id === currentId);+ return index >= 0 ? all[index + direction] : undefined;}diff --git a/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts b/apps/web/src/features/email-view/use-email-detail-list-navigation.test.tsindex 795f72d8ba..721a79162c 100644--- a/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts+++ b/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts@@ -35,11 +35,15 @@ function setup(mocks.view.mockReturnValue({source: {items: () =>- rows().map((id) => ({- kind: 'entity',- id: `row:${id}`,- entity: { type: 'email', id, name: id } as EmailEntity,- })),+ rows().map((id) =>+ id === 'more'+ ? { kind: 'load-more' }+ : {+ kind: 'entity',+ id: `row:${id}`,+ entity: { type: 'email', id, name: id } as EmailEntity,+ }+ ),hasMore,loadMore: mocks.loadMore,error: () => undefined,@@ -68,6 +72,42 @@ function setup(});return { navigation, setRows, setHasMore, setThreadId };}+describe('thread navigation after the open thread leaves the list', () => {+ it('keeps next and previous on its former neighbours', async () => {+ const { navigation, setRows } = setup(['a', 'b', 'c']);+ // Replying in Signal marks the thread done, which removes its row.+ setRows(['a', 'c']);+ expect(navigation.canNext()).toBe(true);+ expect(navigation.canPrevious()).toBe(true);+ await navigation.navigate(1);+ expect(mocks.open).toHaveBeenLastCalledWith({ id: 'c', fallbackName: 'c' });+ await navigation.navigate(-1);+ expect(mocks.open).toHaveBeenLastCalledWith({ id: 'a', fallbackName: 'a' });+ });+ it('steps into a load-more row that followed the removed thread', async () => {+ const { navigation, setRows } = setup(['a', 'b', 'more', 'c']);+ setRows(['a', 'more', 'c']);+ mocks.loadMore.mockImplementation(async () => setRows(['a', 'x', 'c']));+ await navigation.navigate(1);+ expect(mocks.loadMore).toHaveBeenCalledOnce();+ expect(mocks.open).toHaveBeenLastCalledWith({ id: 'x', fallbackName: 'x' });+ });+ it('steps from where the thread was opened after it moves', async () => {+ const { navigation, setRows } = setup(['a', 'b', 'c', 'd']);+ // A reply draft lifts the open thread to the top of Signal.+ setRows(['b', 'a', 'c', 'd']);+ await navigation.navigate(1);+ expect(mocks.open).toHaveBeenLastCalledWith({ id: 'c', fallbackName: 'c' });+ await navigation.navigate(-1);+ expect(mocks.open).toHaveBeenLastCalledWith({ id: 'a', fallbackName: 'a' });+ });+ it('has no previous when the removed thread was first', () => {+ const { navigation, setRows } = setup(['a', 'b', 'c'], 'a');+ setRows(['b', 'c']);+ expect(navigation.canPrevious()).toBe(false);+ expect(navigation.canNext()).toBe(true);+ });+});describe('email reminder navigation', () => {it('advances after the server event removes the saved row', async () => {const { navigation, setRows } = setup(['a', 'b', 'c']);diff --git a/apps/web/src/features/email-view/use-email-detail-list-navigation.ts b/apps/web/src/features/email-view/use-email-detail-list-navigation.tsindex b07364683a..3d9dcab11f 100644--- a/apps/web/src/features/email-view/use-email-detail-list-navigation.ts+++ b/apps/web/src/features/email-view/use-email-detail-list-navigation.ts@@ -1,4 +1,7 @@-import { useListDetailNavigation } from '@app/components/list';+import {+ type ListDetailNavigation,+ useListDetailNavigation,+} from '@app/components/list';import type {EmailThreadCommands,EmailThreadListNavigation,@@ -6,7 +9,7 @@ import type {import { toast } from '@core/component/Toast/Toast';import { fireAndForget } from '@core/util/fireAndForget';import type { EntityData } from '@entity';-import { type Accessor, createMemo, onCleanup } from 'solid-js';+import type { Accessor } from 'solid-js';import { useEmailView } from './email-view-context';import type { EmailDataSourceItem } from './queries/use-email-query';import { useEmailReaderPane } from './reader-pane';@@ -14,44 +17,12 @@ import { useEmailReaderPane } from './reader-pane';/** Keeps thread triage inside the Email view's filtered navigation stack. */export function useEmailDetailListNavigation(threadId: Accessor<string>-): EmailThreadListNavigation {+): EmailThreadListNavigation &+ Pick<ListDetailNavigation<EntityData>, 'navigate'> {const { source, openThread, list } = useEmailView();// Beside the list, the reader steps like the list cursor: the cursor moves// with it and each step replaces history instead of adding an entry.const inPane = useEmailReaderPane() !== undefined;- const emails = () =>- source- .items()- .flatMap((row) =>- row.kind === 'entity' && row.entity.type === 'email' ? [row.entity] : []- );- // Label events can remove the saved thread before its HTTP response arrives.- // Retain its last position, but only navigate to candidates still in this view.- const reminderAnchor = createMemo<- | {- threadId: string;- next: string[];- previous: string[];- }- | undefined- >((previous) => {- const id = threadId();- const rows = emails();- const index = rows.findIndex((row) => row.id === id);- if (index < 0) return previous?.threadId === id ? previous : undefined;- return {- threadId: id,- next: rows.slice(index + 1).map((row) => row.id),- previous: rows- .slice(0, index)- .reverse()- .map((row) => row.id),- };- });- let disposed = false;- onCleanup(() => {- disposed = true;- });const navigation = useListDetailNavigation<EmailDataSourceItem, EntityData>({currentId: threadId,source,@@ -79,36 +50,8 @@ export function useEmailDetailListNavigation(return {...navigation,- afterReminderSaved: async () => {- const id = threadId();- if (emails().some((row) => row.id === id)) {- await navigation.navigate(1, { fallbackDirection: -1 });- return;- }- const anchor = reminderAnchor();- if (!anchor || disposed) return;- const surviving = (ids: string[]) => {- const live = new Map(emails().map((row) => [row.id, row]));- return ids.map((candidate) => live.get(candidate)).find(Boolean);- };- try {- let next = surviving(anchor.next);- while (!next && source.hasMore() && !disposed && threadId() === id) {- const before = new Set(emails().map((row) => row.id));- await source.loadMore();- if (source.error()) throw source.error();- next =- surviving(anchor.next) ??- emails().find((row) => !before.has(row.id));- }- if (disposed || threadId() !== id) return;- const target = next ?? surviving(anchor.previous);- if (target) navigation.open(target);- } catch {- if (!disposed && threadId() === id)- toast.failure('Unable to open the next or previous email');- }- },+ // A saved reminder hides the thread; navigation follows its old position.+ afterReminderSaved: () => navigation.navigate(1, { fallbackDirection: -1 }),markDone: (archiveThread: EmailThreadCommands['archiveThread']) => {fireAndForget(navigation.navigate(1, {diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex f76453ab7c..a79797f352 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -319,7 +319,9 @@ first); the list keeps the row you came from focused. The inline header uses theemail title menu: open the menu button beside the subject for **Ask AI**, **Create aTask**, 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+follow the current filtered list and disable at its ends. When the open thread+leaves the list while it stays open (a reply in Signal marks it done, or another+device archives it), they step from its former neighbours. Mark done advances inthat list. In a list, the Mark done, Mark as not done and Delete keys act once perpress: a held key auto-repeats, and those repeats are ignored. Mark as unread (inthe header or title menu) returns to the originating list with its tab, inbox, anddiff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.mdindex 049083918b..580a5b1bce 100644--- a/docs/agent-guide/notifications.md+++ b/docs/agent-guide/notifications.md@@ -66,6 +66,7 @@ The floating Ask AI input appears only on the AI/Agents view.On touch devices, an email thread's floating action bar has Previous email andNext email arrows beside the larger Mark done checkmark. The arrows follow thesource list's filtered order, skip non-email items, and disable at its ends.+They keep working from the thread's former neighbours after it leaves the list.`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 threadopened without a source list has disabled arrows.