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
feat(email): discard a row's draft from the list (#9395)
Jacob Beckerman4dcb8cd165d7
diff --git a/apps/web/src/features/email-view/components/EmailList.tsx b/apps/web/src/features/email-view/components/EmailList.tsxindex 2e5d017837..a1a625637c 100644--- a/apps/web/src/features/email-view/components/EmailList.tsx+++ b/apps/web/src/features/email-view/components/EmailList.tsx@@ -306,6 +306,7 @@ export function EmailList(props: EmailListProps) {const actionState = toEntityActionListState({controller: list,getEntity: (row) => (row.kind === 'entity' ? row.entity : undefined),+ positions: source.positions,collapse: {// Signal and Noise remove archived threads; finish the row animation first.enabled: () =>diff --git a/apps/web/src/features/email-view/queries/email-results.ts b/apps/web/src/features/email-view/queries/email-results.tsindex ffc1d5220b..1d51edb3a1 100644--- a/apps/web/src/features/email-view/queries/email-results.ts+++ b/apps/web/src/features/email-view/queries/email-results.ts@@ -4,33 +4,43 @@ import {groupSoupEntities,type SoupGroup,} from '@app/features/soup/collection';+import type { DateValue } from '@core/util/date';import type { EntityData, WithNotification } from '@entity';+/** A row held in place keeps the timestamp it was bucketed by. */+type HeldSortTimestamp = (entityId: string) => DateValue | undefined;+// Threads are listed by latest activity: `sortTs` is the server's stamp for// that order, and rows that arrived outside the page (websocket inserts,// search hits) fall back to the thread's own recency.-const emailSortTimestamp = (entity: EntityData) =>- entity.sortTs ?? entity.updatedAt ?? entity.createdAt;+const emailSortTimestamp = (entity: EntityData, held?: HeldSortTimestamp) =>+ held?.(entity.id) ?? entity.sortTs ?? entity.updatedAt ?? entity.createdAt;export function groupEmailEntitiesByDate(entities: WithNotification<EntityData>[],- now = new Date()+ now = new Date(),+ held?: HeldSortTimestamp): SoupGroup<WithNotification<EntityData>>[] {return groupSoupEntities(entities, {- getGroupId: (entity) => dateBucket(emailSortTimestamp(entity), now).key,+ getGroupId: (entity) =>+ dateBucket(emailSortTimestamp(entity, held), now).key,getGroupLabel: (_groupId, firstEntity) =>- dateBucket(emailSortTimestamp(firstEntity), now).label,+ dateBucket(emailSortTimestamp(firstEntity, held), now).label,});}/** Keep today's messages flush with the header; retain older date headings. */export function buildEmailDateRows(entities: WithNotification<EntityData>[],- now = new Date()+ now = new Date(),+ held?: HeldSortTimestamp) {- const rows = buildGroupedSoupRows(groupEmailEntitiesByDate(entities, now), {- keyByEntity: true,- });+ const rows = buildGroupedSoupRows(+ groupEmailEntitiesByDate(entities, now, held),+ {+ keyByEntity: true,+ }+ );if (rows[0]?.kind === 'group-header' && rows[0].groupId === 'today')rows.shift();return rows;diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.tsindex fcb846b71c..ab3b6fe39b 100644--- a/apps/web/src/features/email-view/queries/use-email-query.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.ts@@ -1,4 +1,5 @@import type { ListDataSource } from '@app/components/list';+import { createPositionHolds } from '@app/features/next-soup/position-holds';import type { EmailRowReminder } from '@app/features/reminders/core/email-row-reminder';import {buildFlatSoupRows,@@ -47,6 +48,8 @@ export type EmailDataSourceItem = SoupRow<WithNotification<EntityData>>;export type EmailDataSource = ListDataSource<EmailDataSourceItem> & {reminderForThread?: (threadId: string) => EmailRowReminder | undefined;+ /** Keeps rows in place while an action changes their sort. */+ positions?: { hold: (entityIds: readonly string[]) => void };};export type EmailDataSourceInput = Pick<@@ -494,11 +497,15 @@ export function useEmailDataSource(];};- const listEntities = createMemo((): WithNotification<EntityData>[] =>- entities().map((email) =>+ // Discarding a draft moves a thread back to its last received message;+ // the row stays where it was until the list's scope changes.+ const positions = createPositionHolds({ scope });+ const listEntities = createMemo((): WithNotification<EntityData>[] => {+ const rows = entities().map((email) =>withEntityNotifications(email, notificationSource)- )- );+ );+ return search.isSearching() ? rows : positions.apply(rows);+ });const usesServiceSearch = search.usesServiceSearch;const [refreshing, setRefreshing] = createSignal(false);@@ -542,7 +549,7 @@ export function useEmailDataSource(// bucketed by date.const result: EmailDataSourceItem[] = search.isSearching()? buildFlatSoupRows(listEntities())- : buildEmailDateRows(listEntities());+ : buildEmailDateRows(listEntities(), new Date(), positions.sortTs);if (hasMore()) {result.push(@@ -575,6 +582,9 @@ export function useEmailDataSource(};return {+ positions: {+ hold: (entityIds) => positions.hold(listEntities(), entityIds),+ },reminderForThread: (threadId) =>showsReminders() ? reminders.reminderForThread?.(threadId) : undefined,items: () =>diff --git a/apps/web/src/features/next-soup/actions/entity-action-context.ts b/apps/web/src/features/next-soup/actions/entity-action-context.tsindex 8682065782..b2a1c6762a 100644--- a/apps/web/src/features/next-soup/actions/entity-action-context.ts+++ b/apps/web/src/features/next-soup/actions/entity-action-context.ts@@ -37,6 +37,8 @@ export type EntityActionListState = {SoupState['collapseEntity'],'callback' | 'shouldCollapse'>;+ /** Lists that can keep rows in place while an action changes their sort. */+ positions?: Pick<SoupState['positions'], 'hold'>;};export type EntityActionListFocusTarget = {@@ -55,6 +57,7 @@ export type ToEntityActionListStateOptions<TItem, TMetadata> = {enabled: () => boolean;run: (entityId: string) => Promise<void>;};+ positions?: EntityActionListState['positions'];};type AdaptedRow = {@@ -262,6 +265,7 @@ export function toEntityActionListState<TItem, TMetadata>(callback: collapseCallback,shouldCollapse: () => options.collapse?.enabled() ?? false,},+ positions: options.positions,};}diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.tsindex 1f9875dc0f..3486290592 100644--- a/apps/web/src/features/next-soup/actions/index.ts+++ b/apps/web/src/features/next-soup/actions/index.ts@@ -26,6 +26,7 @@ export { makeCopyEntityIdAction } from './make-copy-entity-id-action';export { makeCopyLinkAction } from './make-copy-link-action';export { makeCreateReminderAction } from './make-create-reminder-action';export { makeDeleteAction } from './make-delete-action';+export { makeDiscardDraftAction } from './make-discard-draft-action';export { makeDownloadAction } from './make-download-action';export { makeFavoriteAction } from './make-favorite-action';export { makeGithubLinkAction } from './make-github-link-action';diff --git a/apps/web/src/features/next-soup/actions/make-discard-draft-action.test.ts b/apps/web/src/features/next-soup/actions/make-discard-draft-action.test.tsnew file mode 100644index 0000000000..7f1462ed80--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-discard-draft-action.test.ts@@ -0,0 +1,175 @@+import type { EntityData } from '@entity';+import { err, ok } from 'neverthrow';+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { EntityActionListState } from './entity-action-context';++const mocks = vi.hoisted(() => ({+ success: vi.fn(),+ failure: vi.fn(),+ readThreadDrafts: vi.fn(),+ queueActive: vi.fn(() => true),+ deleteQueued: vi.fn(),+ deleteRest: vi.fn(),+ markSaved: vi.fn(),+ publish: vi.fn(),+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: mocks.success, failure: mocks.failure },+}));+// The real barrel reaches the query clients, which open websockets under jsdom.+vi.mock('@entity', () => ({+ isEmailEntity: (entity: EntityData) => entity.type === 'email',+}));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: {+ error: vi.fn(),+ span: (_name: string, run: (span: object) => unknown) =>+ run({ setAttr: vi.fn(), error: vi.fn() }),+ },+}));+vi.mock('@queries/email/thread-drafts', () => ({+ readThreadDrafts: mocks.readThreadDrafts,+}));+vi.mock('@queries/email/draft-queue', () => ({+ draftQueueActive: mocks.queueActive,+ deleteEmailDraftQueued: mocks.deleteQueued,+}));+vi.mock('@queries/email/draft', () => ({+ useDeleteDraftMutation: () => ({ mutateAsync: mocks.deleteRest }),+}));+vi.mock('@queries/email/draft-cache', () => ({+ markThreadDraftSaved: mocks.markSaved,+}));+vi.mock('@queries/email/draft-lifecycle-events', () => ({+ publishDraftLifecycleChange: mocks.publish,+}));+vi.mock('@queries/email/link', () => ({+ useNonPrimaryEmailLinkIdHeader: () => (linkId?: string | null) =>+ linkId === 'primary' ? undefined : (linkId ?? undefined),+}));++import { makeDiscardDraftAction } from './make-discard-draft-action';++const email = (overrides: Record<string, unknown> = {}) =>+ ({+ type: 'email',+ id: 'thread-1',+ name: 'Partnerships',+ isDraft: true,+ ...overrides,+ }) as unknown as EntityData;++const draft = {+ draftId: 'draft-1',+ draftGeneration: 3,+ threadId: 'thread-1',+ inboxId: 'primary',+};++const listWithHold = (hold: (ids: readonly string[]) => void) =>+ ({ positions: { hold } }) as unknown as EntityActionListState;++const createAction = () =>+ createRoot((dispose) => ({ action: makeDiscardDraftAction(), dispose }));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.queueActive.mockReturnValue(true);+ mocks.readThreadDrafts.mockResolvedValue(ok([draft]));+ mocks.deleteQueued.mockResolvedValue({ kind: 'committed' });+ mocks.deleteRest.mockResolvedValue(undefined);+});++describe('makeDiscardDraftAction', () => {+ it('only applies to email threads with a draft', () => {+ const { action, dispose } = createAction();++ expect(action.canExecute(email())).toBe(true);+ expect(action.canExecute(email({ isDraft: false }))).toBe(false);+ expect(action.canExecute(email({ type: 'document' }))).toBe(false);+ dispose();+ });++ it('holds the row in place before deleting the draft through the queue', async () => {+ const { action, dispose } = createAction();+ const order: string[] = [];+ const hold = vi.fn(() => order.push('hold'));+ mocks.readThreadDrafts.mockImplementation(async () => {+ order.push('read');+ return ok([draft]);+ });++ await action.executeWithSoup([email()], listWithHold(hold));++ expect(hold).toHaveBeenCalledWith(['thread-1']);+ expect(order).toEqual(['hold', 'read']);+ expect(mocks.deleteQueued).toHaveBeenCalledWith({+ draftId: 'draft-1',+ draftGeneration: 3,+ threadId: 'thread-1',+ });+ expect(mocks.publish).toHaveBeenCalledWith('draft-1', 'primary');+ expect(mocks.success).toHaveBeenCalledOnce();+ dispose();+ });++ it('deletes through REST when the draft queue is off', async () => {+ mocks.queueActive.mockReturnValue(false);+ mocks.readThreadDrafts.mockResolvedValue(+ ok([{ ...draft, inboxId: 'work-inbox' }])+ );+ const { action, dispose } = createAction();++ await action.execute([email()]);++ expect(mocks.deleteRest).toHaveBeenCalledWith({+ draftId: 'draft-1',+ draftGeneration: 3,+ threadId: 'thread-1',+ linkId: 'work-inbox',+ });+ expect(mocks.markSaved).toHaveBeenCalledWith('thread-1');+ expect(mocks.deleteQueued).not.toHaveBeenCalled();+ dispose();+ });++ it('reports a failed delete once', async () => {+ mocks.deleteQueued.mockRejectedValue(new Error('offline'));+ const { action, dispose } = createAction();++ await action.execute([email()]);++ expect(mocks.failure).toHaveBeenCalledOnce();+ expect(mocks.success).not.toHaveBeenCalled();+ dispose();+ });++ it('reports a thread it cannot read', async () => {+ mocks.readThreadDrafts.mockResolvedValue(+ err({ kind: 'thread-unavailable', codes: ['NOT_FOUND'] })+ );+ const { action, dispose } = createAction();++ await action.execute([email()]);++ expect(mocks.deleteQueued).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledOnce();+ dispose();+ });++ it('leaves rejection notices to the draft queue', async () => {+ mocks.deleteQueued.mockResolvedValue({+ kind: 'rejected',+ code: 'DRAFT_ALREADY_SENT',+ });+ const { action, dispose } = createAction();++ await action.execute([email()]);++ expect(mocks.failure).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ dispose();+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-discard-draft-action.ts b/apps/web/src/features/next-soup/actions/make-discard-draft-action.tsnew file mode 100644index 0000000000..9b0544de81--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-discard-draft-action.ts@@ -0,0 +1,147 @@+import { t } from '@app/lib/i18n';+import { toast } from '@core/component/Toast/Toast';+import { type EmailEntity, type EntityData, isEmailEntity } from '@entity';+import { Telemetry } from '@macro-inc/observability';+import { useDeleteDraftMutation } from '@queries/email/draft';+import { markThreadDraftSaved } from '@queries/email/draft-cache';+import { publishDraftLifecycleChange } from '@queries/email/draft-lifecycle-events';+import {+ deleteEmailDraftQueued,+ draftQueueActive,+} from '@queries/email/draft-queue';+import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';+import {+ readThreadDrafts,+ type ThreadDraftHandle,+} from '@queries/email/thread-drafts';+import { err, ok, type Result, ResultAsync } from 'neverthrow';+import { match } from 'ts-pattern';+import type { EntityActionListState } from './entity-action-context';++type DiscardFailure =+ | { kind: 'thread-unavailable'; codes: string[] }+ /** The draft queue already showed its own notice for this rejection. */+ | { kind: 'rejected'; code: string }+ | { kind: 'delete-failed'; error: unknown };++const deleteFailed = (error: unknown): DiscardFailure => ({+ kind: 'delete-failed',+ error,+});++/**+ * Discards the drafts on email thread rows, as the composer's discard+ * shortcut does, without opening them. The thread keeps its row and its+ * place in the list; only the draft badge and preview fall back to the+ * thread's latest message.+ */+export const makeDiscardDraftAction = () => {+ const remove = useDeleteDraftMutation();+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();++ const canExecute = (entity: EntityData): entity is EmailEntity =>+ isEmailEntity(entity) && entity.isDraft;++ const deleteDraft = async (+ draft: ThreadDraftHandle+ ): Promise<Result<void, DiscardFailure>> => {+ const { threadId } = draft;+ if (draftQueueActive()) {+ const outcome = await ResultAsync.fromPromise(+ deleteEmailDraftQueued({+ draftId: draft.draftId,+ draftGeneration: draft.draftGeneration,+ threadId,+ }),+ deleteFailed+ );+ if (outcome.isErr()) return err(outcome.error);+ if (outcome.value.kind === 'rejected')+ return err({ kind: 'rejected', code: outcome.value.code });+ } else {+ const removed = await ResultAsync.fromPromise(+ remove.mutateAsync({+ draftId: draft.draftId,+ draftGeneration: draft.draftGeneration,+ threadId,+ linkId: toHeaderLinkId(draft.inboxId),+ }),+ deleteFailed+ );+ if (removed.isErr()) return err(removed.error);+ markThreadDraftSaved(threadId);+ }+ // An open composer on this draft rereads it and closes.+ publishDraftLifecycleChange(draft.draftId, draft.inboxId);+ return ok(undefined);+ };++ const discardThreadDrafts = (+ thread: EmailEntity+ ): Promise<Result<number, DiscardFailure>> =>+ Telemetry.span('email.draft_discard.list', async (span) => {+ span.setAttr('email.thread_id', thread.id);+ const drafts = await readThreadDrafts(thread.id);+ if (drafts.isErr()) {+ span.error('Thread drafts unavailable');+ return err(drafts.error);+ }+ span.setAttr('email.draft_discard.count', drafts.value.length);+ for (const draft of drafts.value) {+ const deleted = await deleteDraft(draft);+ if (deleted.isErr()) {+ span.error(`Draft discard ${deleted.error.kind}`);+ return err(deleted.error);+ }+ }+ return ok(drafts.value.length);+ });++ const reportFailure = (failure: DiscardFailure) =>+ match(failure)+ .with({ kind: 'thread-unavailable' }, ({ codes }) =>+ Telemetry.error(+ new Error(`Thread drafts unavailable: ${codes.join(', ')}`)+ )+ )+ .with({ kind: 'rejected' }, () => undefined)+ .with({ kind: 'delete-failed' }, ({ error }) => Telemetry.error(error))+ .exhaustive();++ const execute = async (entities: EntityData[]) => {+ const threads = entities.filter(canExecute);+ if (threads.length === 0) return;++ const results = await Promise.all(threads.map(discardThreadDrafts));+ const failures = results.flatMap((result) =>+ result.isErr() ? [result.error] : []+ );+ if (failures.length > 0) {+ failures.forEach(reportFailure);+ if (failures.some((failure) => failure.kind !== 'rejected'))+ toast.failure(t('entityActions.toastDiscardDraftFailed'));+ return;+ }+ const discarded = results.reduce(+ (sum, result) => sum + (result.isOk() ? result.value : 0),+ 0+ );+ if (discarded === 0) return;+ toast.success(+ t('entityActions.toastDiscardedDrafts', { count: discarded }),+ { duration: 3_000, stack: true, hideOnMobile: true }+ );+ };++ /** Rows stay where they are, even though the thread's sort time moves back+ * to its latest received message. */+ const executeWithSoup = async (+ entities: EntityData[],+ soup: EntityActionListState+ ) => {+ soup.positions?.hold(entities.filter(canExecute).map(({ id }) => id));+ await execute(entities);+ };++ return { canExecute, execute, executeWithSoup };+};diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.tsindex e4021e9ae7..73eb5224a2 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts@@ -5,13 +5,20 @@ import { createRoot } from 'solid-js';import { expect, it, vi } from 'vitest';import { useEntityActionHotkeys } from './use-entity-action-hotkeys';-const { action, markDone } = vi.hoisted(() => {+const { action, markDone, discardDraft } = vi.hoisted(() => {const action = () => ({canExecute: () => true,execute: vi.fn(),executeWithSoup: vi.fn(() => Promise.resolve()),});- return { action, markDone: action() };+ return {+ action,+ markDone: action(),+ discardDraft: {+ ...action(),+ canExecute: (entity: { isDraft?: boolean }) => entity.isDraft === true,+ },+ };});vi.mock('@service-storage/websocket', () => ({@@ -52,6 +59,7 @@ vi.mock('./index', () => ({makeCopyLinkAction: action,makeCreateReminderAction: action,makeDeleteAction: action,+ makeDiscardDraftAction: () => discardDraft,makeFavoriteAction: action,makeMarkDoneAction: () => markDone,makeMarkNotDoneAction: action,@@ -88,3 +96,36 @@ it('marks one selection per key press and ignores key auto-repeat', () => {dispose();});});++it('discards a row draft with the composer discard keys', () => {+ createRoot((dispose) => {+ let thread = { type: 'email', id: 'thread', isDraft: true } as EntityData;+ const list = {} as never;+ useEntityActionHotkeys({+ scopeId: 'list',+ list,+ selectedEntities: () => [],+ focusedEntity: () => thread,+ restoreFocus: () => undefined,+ viewContext: () => ({ supportsMarkDone: true }) as never,+ });+ const options = vi+ .mocked(registerHotkey)+ .mock.calls.find(+ ([options]) => options.hotkeyToken === TOKENS.email.discardDraft+ )![0];+ expect(options.hotkey).toEqual([+ 'shift+cmd+.',+ 'shift+cmd+,',+ 'shift+cmd+d',+ ]);+ expect(options.condition!()).toBe(true);+ expect(options.keyDownHandler!()).toBe(true);+ expect(discardDraft.executeWithSoup).toHaveBeenCalledWith([thread], list);++ thread = { type: 'email', id: 'thread', isDraft: false } as EntityData;+ expect(options.condition!()).toBe(false);+ expect(options.keyDownHandler!()).toBe(false);+ dispose();+ });+});diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.tsindex 0ece53d1c9..0e37302728 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts@@ -29,6 +29,7 @@ import {makeCopyLinkAction,makeCreateReminderAction,makeDeleteAction,+ makeDiscardDraftAction,makeFavoriteAction,makeMarkDoneAction,makeMarkNotDoneAction,@@ -103,6 +104,8 @@ export const useEntityActionHotkeys = (userId: () => userId(),});+ const discardDraftAction = makeDiscardDraftAction();+const renameAction = makeRenameAction({userId: () => userId(),});@@ -299,6 +302,39 @@ export const useEntityActionHotkeys = (tags: [HotkeyTags.SelectionModification],}).withGroup(group);+ // Discard draft - the composer's discard keys, on rows with a draft. The+ // thread keeps its row and place; only the draft goes.+ registerHotkey({+ hotkey: ['shift+cmd+.', 'shift+cmd+,', 'shift+cmd+d'],+ hotkeyToken: TOKENS.email.discardDraft,+ scopeId,+ description: () =>+ t('entityActions.discardDraftCommand', {+ count: getEntitiesForAction().length,+ }),+ keyDownHandler: (event) => {+ if (event?.repeat) return true;+ const entities = getEntitiesForAction();+ if (entities.length === 0) return false;+ if (!entities.every(discardDraftAction.canExecute)) return false;++ fireAndForget(+ discardDraftAction.executeWithSoup(entities, list),+ 'entity-actions'+ );+ return true;+ },+ condition: () => {+ if (condition && !condition()) return false;+ const entities = getEntitiesForAction();+ return (+ entities.length > 0 && entities.every(discardDraftAction.canExecute)+ );+ },+ displayPriority: 9,+ tags: [HotkeyTags.SelectionModification],+ }).withGroup(group);+if (options.enableDeleteHotkey !== false) {const deleteDescription = () => {const count = getEntitiesForAction().length;diff --git a/apps/web/src/features/next-soup/create-soup-state.ts b/apps/web/src/features/next-soup/create-soup-state.tsindex 8a9d3b66f6..754a5bbff4 100644--- a/apps/web/src/features/next-soup/create-soup-state.ts+++ b/apps/web/src/features/next-soup/create-soup-state.ts@@ -8,13 +8,21 @@ import {createPredicatesStore,type PredicateConfig,} from '@app/features/next-soup/filters/filter-store/predicates-store';+import { createPositionHolds } from '@app/features/next-soup/position-holds';import { createSelectionState } from '@app/features/next-soup/selection-state';import { SORT_CONFIGS } from '@app/features/next-soup/soup-view/sort-options';import { isModality } from '@core/mobile/inputModality';import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { EntityData, WithNotification, WithSearch } from '@entity';import type { SoupRowFamily } from '@entity/composed/list-entity/row-geometry';-import { batch, createMemo, createSignal, type JSX } from 'solid-js';+import {+ type Accessor,+ batch,+ createMemo,+ createSignal,+ type JSX,+ onCleanup,+} from 'solid-js';import { createStore, reconcile } from 'solid-js/store';/**@@ -115,6 +123,17 @@ export const createSoupState = (options: SoupContextOptions = {}) => {const sort = createSortState(SORT_CONFIGS, ['updated_at']);+ // The view adds what the client can't see, such as its server filters.+ const [viewScope, setViewScope] = createSignal<Accessor<unknown>>(() => null);+ const positions = createPositionHolds({+ scope: () =>+ JSON.stringify([+ predicates.activeIds(),+ sort.active().map(({ id, reversed }) => [id, reversed === true]),+ viewScope()(),+ ]),+ });+// Tracked by index (not id) so a row id duplicated across groups highlights// only one occurrence. The identity key follows that row across setRows.const [focusedIndex, setFocusedIndex] = createSignal(-1);@@ -419,6 +438,26 @@ export const createSoupState = (options: SoupContextOptions = {}) => {indexOf,},+ positions: {+ /** Keep these entities' rows where they are; see createPositionHolds. */+ hold: (entityIds: readonly string[]) =>+ positions.hold(+ rows()+ .filter((row) => !row.getIsGrouped() && !row.getIsLoadMore())+ .map((row) => row.original),+ entityIds+ ),+ apply: positions.apply,+ sortTs: positions.sortTs,+ /** Release holds when this view state changes too, until cleanup. */+ scopeTo: (scope: Accessor<unknown>) => {+ setViewScope(() => scope);+ onCleanup(() => {+ if (viewScope() === scope) setViewScope(() => () => null);+ });+ },+ },+collapseEntity: {callback: collapseEntityCallback,set: setCollapseEntityCallback,diff --git a/apps/web/src/features/next-soup/position-holds.test.ts b/apps/web/src/features/next-soup/position-holds.test.tsnew file mode 100644index 0000000000..dd486395c8--- /dev/null+++ b/apps/web/src/features/next-soup/position-holds.test.ts@@ -0,0 +1,77 @@+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it } from 'vitest';+import { createPositionHolds } from './position-holds';++type Row = { id: string; sortTs?: string };++const rows = (...ids: string[]): Row[] => ids.map((id) => ({ id }));+const ids = (list: Row[]) => list.map(({ id }) => id);++const withHolds = (+ test: (+ holds: ReturnType<typeof createPositionHolds>,+ setScope: (scope: string) => void+ ) => void+) =>+ createRoot((dispose) => {+ const [scope, setScope] = createSignal('all');+ test(createPositionHolds({ scope }), setScope);+ dispose();+ });++describe('createPositionHolds', () => {+ it('keeps a held row after its previous neighbour when its sort moves it', () =>+ withHolds((holds) => {+ holds.hold(rows('kyle', 'sam', 'teo-1', 'teo-2'), ['sam']);++ // The draft is gone; Sam's thread now sorts by an older message.+ expect(ids(holds.apply(rows('kyle', 'teo-1', 'teo-2', 'sam')))).toEqual([+ 'kyle',+ 'sam',+ 'teo-1',+ 'teo-2',+ ]);+ }));++ it('keeps the first row above its old successor as new rows arrive', () =>+ withHolds((holds) => {+ holds.hold(rows('sam', 'teo'), ['sam']);++ expect(ids(holds.apply(rows('new', 'teo', 'sam')))).toEqual([+ 'new',+ 'sam',+ 'teo',+ ]);+ }));++ it('falls back to the natural order once both neighbours are gone', () =>+ withHolds((holds) => {+ holds.hold(rows('kyle', 'sam', 'teo'), ['sam']);++ expect(ids(holds.apply(rows('a', 'b', 'sam')))).toEqual([+ 'a',+ 'b',+ 'sam',+ ]);+ }));++ it('releases holds when the list scope changes', () =>+ withHolds((holds, setScope) => {+ holds.hold(rows('kyle', 'sam', 'teo'), ['sam']);+ setScope('inbox');++ expect(ids(holds.apply(rows('kyle', 'teo', 'sam')))).toEqual([+ 'kyle',+ 'teo',+ 'sam',+ ]);+ expect(holds.sortTs('sam')).toBeUndefined();+ }));++ it('remembers the captured sort time for date grouping', () =>+ withHolds((holds) => {+ holds.hold([{ id: 'sam', sortTs: '2026-11-02T14:43:00Z' }], ['sam']);++ expect(holds.sortTs('sam')).toBe('2026-11-02T14:43:00Z');+ }));+});diff --git a/apps/web/src/features/next-soup/position-holds.ts b/apps/web/src/features/next-soup/position-holds.tsnew file mode 100644index 0000000000..29b49a96b2--- /dev/null+++ b/apps/web/src/features/next-soup/position-holds.ts@@ -0,0 +1,97 @@+import type { DateValue } from '@core/util/date';+import { type Accessor, createMemo, createSignal } from 'solid-js';++type PositionHold = {+ /** The list scope (filters and sort) the position was captured in. */+ scope: string;+ /** Entity rendered directly above the held one, if any. */+ afterId: string | undefined;+ /** Entity rendered directly below the held one, if any. */+ beforeId: string | undefined;+ /** Sort timestamp at capture, so client date groups keep the row too. */+ sortTs: DateValue | undefined;+};++type HoldableEntity = {+ id: string;+ sortTs?: DateValue | null;+ updatedAt?: DateValue | null;+ createdAt?: DateValue | null;+};++/**+ * Keeps rows where they were when an in-place action changed their sort key,+ * such as discarding a draft, which moves a thread back to its last received+ * message. A hold lasts while the list keeps the scope it was captured in;+ * changing filters or sort releases it.+ */+export function createPositionHolds(options: { scope: Accessor<string> }) {+ const [holds, setHolds] = createSignal<ReadonlyMap<string, PositionHold>>(+ new Map()+ );++ const active = createMemo(() => {+ const scope = options.scope();+ const all = holds();+ const result = new Map<string, PositionHold>();+ for (const [id, hold] of all)+ if (hold.scope === scope) result.set(id, hold);+ return result;+ });++ /** Capture the positions of `ids` in the rendered entity order. */+ const hold = (order: readonly HoldableEntity[], ids: readonly string[]) => {+ const scope = options.scope();+ const next = new Map<string, PositionHold>();+ for (const [id, existing] of holds())+ if (existing.scope === scope) next.set(id, existing);+ const wanted = new Set(ids);+ order.forEach((entity, index) => {+ if (!wanted.has(entity.id)) return;+ next.set(entity.id, {+ scope,+ afterId: order[index - 1]?.id,+ beforeId: order[index + 1]?.id,+ sortTs:+ entity.sortTs ?? entity.updatedAt ?? entity.createdAt ?? undefined,+ });+ });+ setHolds(next);+ };++ /** Move held entities back beside their captured neighbours. */+ const apply = <T extends { id: string }>(entities: T[]): T[] => {+ const current = active();+ if (current.size === 0) return entities;+ const result = [...entities];+ for (const [id, hold] of current) {+ const from = result.findIndex((entity) => entity.id === id);+ if (from < 0) continue;+ const [entity] = result.splice(from, 1);+ const after =+ hold.afterId === undefined+ ? -1+ : result.findIndex((other) => other.id === hold.afterId);+ if (after >= 0) {+ result.splice(after + 1, 0, entity);+ continue;+ }+ const before =+ hold.beforeId === undefined+ ? -1+ : result.findIndex((other) => other.id === hold.beforeId);+ if (before >= 0) {+ result.splice(before, 0, entity);+ continue;+ }+ // Both neighbours are gone; fall back to the natural position.+ result.splice(from, 0, entity);+ }+ return result;+ };++ const sortTs = (id: string): DateValue | undefined =>+ active().get(id)?.sortTs;++ return { hold, apply, sortTs };+}diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 3c3294adc2..6ffc7fab34 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -790,6 +790,9 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {const soupBody = createMemo(() =>compileToAst(applyViewFilters(queryFilters.state)));+ // Server-side filters change the result set without touching the client+ // predicates or sort, so they release held row positions too.+ soup.positions.scopeTo(soupBody);const [searchText, setSearchText] = useEntryState<string>('search.text', {default: props.initialSearchText ?? '',@@ -1116,7 +1119,8 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {});}- return transformed;+ if (search.isSearching()) return transformed;+ return soup.positions.apply(transformed);};const entities = () => {@@ -1327,6 +1331,7 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {for (const entity of all) {const ts =(bucketOnNotification ? entity.notifiedAt : undefined) ??+ soup.positions.sortTs(entity.id) ??entity.sortTs ??entity.updatedAt ??entity.createdAt;diff --git a/apps/web/src/lib/i18n/locales/en/entity-actions.ts b/apps/web/src/lib/i18n/locales/en/entity-actions.tsindex d2961c1462..75001d0769 100644--- a/apps/web/src/lib/i18n/locales/en/entity-actions.ts+++ b/apps/web/src/lib/i18n/locales/en/entity-actions.ts@@ -39,6 +39,10 @@ export default {markDoneCommand: 'Mark done',markReadCommand: 'Mark read',markUnreadCommand: 'Mark unread',+ discardDraftCommand: {+ one: 'Discard draft',+ other: 'Discard drafts',+ },copyLinkCommand: 'Copy link',copyBranchNameCommand: 'Copy branch name',copyId: 'Copy ID',@@ -101,6 +105,11 @@ export default {other: 'Deleted {{count}} items',},toastDeleteFailed: 'Failed to delete',+ toastDiscardedDrafts: {+ one: 'Draft discarded',+ other: '{{count}} drafts discarded',+ },+ toastDiscardDraftFailed: 'Failed to discard draft',toastAddedToFavorites: 'Added to favorites',toastAddedCountToFavorites: {one: 'Added {{count}} item to favorites',diff --git a/apps/web/src/lib/queries/email/local-draft-entities.ts b/apps/web/src/lib/queries/email/local-draft-entities.tsindex 395c432042..2f2dc0d8ba 100644--- a/apps/web/src/lib/queries/email/local-draft-entities.ts+++ b/apps/web/src/lib/queries/email/local-draft-entities.ts@@ -1,20 +1,29 @@import type { LocalDraft } from '@app/features/email-compose/core/local-draft';import type { EmailEntity } from '@entity';+/** Whether a local working copy still shows as its own draft row. */+export function isListedLocalDraft(draft: LocalDraft): boolean {+ return !(+ draft.status === 'synced' ||+ (draft.status === 'deleting' &&+ !!draft.queuedAttemptId &&+ draft.queuedAttemptId === draft.latestAttemptId)+ );+}++/** The conversation row a local working copy appears under. */+export function localDraftRowId(draft: LocalDraft): string {+ return draft.serverThreadId ?? draft.threadId ?? draft.key;+}+/** One conversation row, even when several local reply drafts share it. */export function localDraftEntities(drafts: readonly LocalDraft[]): EmailEntity[] {const rows = new Map<string, EmailEntity>();for (const draft of drafts) {- if (- draft.status === 'synced' ||- (draft.status === 'deleting' &&- draft.queuedAttemptId &&- draft.queuedAttemptId === draft.latestAttemptId)- )- continue;- const id = draft.serverThreadId ?? draft.threadId ?? draft.key;+ if (!isListedLocalDraft(draft)) continue;+ const id = localDraftRowId(draft);if (rows.has(id)) continue;rows.set(id, {type: 'email',diff --git a/apps/web/src/lib/queries/email/thread-drafts.test.ts b/apps/web/src/lib/queries/email/thread-drafts.test.tsnew file mode 100644index 0000000000..5b0c427c81--- /dev/null+++ b/apps/web/src/lib/queries/email/thread-drafts.test.ts@@ -0,0 +1,130 @@+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ fetchThread: vi.fn(),+ listLocal: vi.fn(),+ queueActive: vi.fn(() => true),+}));++vi.mock('./thread', () => ({ fetchAndCacheThread: mocks.fetchThread }));+vi.mock('./local-drafts', () => ({ listLocalDrafts: mocks.listLocal }));+vi.mock('./draft-queue', () => ({ draftQueueActive: mocks.queueActive }));++import { readThreadDrafts } from './thread-drafts';++const message = (overrides: Record<string, unknown>) => ({+ db_id: 'm1',+ is_draft: false,+ draft_generation: 0,+ link_id: 'inbox',+ scheduled_send_time: null,+ ...overrides,+});++const local = (overrides: Record<string, unknown>) => ({+ key: 'key-1',+ draftId: 'local-1',+ threadId: 'thread-1',+ status: 'unconfirmed',+ inboxId: 'inbox',+ content: { draft_generation: 2 },+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ mocks.queueActive.mockReturnValue(true);+ mocks.listLocal.mockResolvedValue([]);+});++describe('readThreadDrafts', () => {+ it("returns the thread's server drafts, skipping scheduled sends", async () => {+ mocks.fetchThread.mockResolvedValue(+ ok({+ thread: {+ messages: [+ message({ db_id: 'received' }),+ message({ db_id: 'draft', is_draft: true, draft_generation: 4 }),+ message({+ db_id: 'scheduled',+ is_draft: true,+ scheduled_send_time: '2026-11-03T09:00:00Z',+ }),+ ],+ },+ })+ );++ const result = await readThreadDrafts('thread-1');++ expect(result._unsafeUnwrap()).toEqual([+ {+ draftId: 'draft',+ draftGeneration: 4,+ threadId: 'thread-1',+ inboxId: 'inbox',+ },+ ]);+ });++ it('discards a working copy that exists only on this device', async () => {+ mocks.listLocal.mockResolvedValue([+ local({ threadId: undefined, key: 'row-key' }),+ local({ draftId: 'synced', status: 'synced', key: 'row-key' }),+ ]);+ mocks.fetchThread.mockResolvedValue(+ err([{ code: 'NOT_FOUND', message: 'Email thread not found' }])+ );++ const result = await readThreadDrafts('row-key');++ expect(result._unsafeUnwrap()).toEqual([+ {+ draftId: 'local-1',+ draftGeneration: 2,+ threadId: 'row-key',+ inboxId: 'inbox',+ },+ ]);+ });++ it('deletes a working copy once when the server also has it', async () => {+ mocks.listLocal.mockResolvedValue([local({ serverDraftId: 'server-1' })]);+ mocks.fetchThread.mockResolvedValue(+ ok({+ thread: {+ messages: [message({ db_id: 'server-1', is_draft: true })],+ },+ })+ );++ const result = await readThreadDrafts('thread-1');++ expect(result._unsafeUnwrap().map(({ draftId }) => draftId)).toEqual([+ 'local-1',+ ]);+ });++ it('reports a thread it cannot read and has no local copy of', async () => {+ mocks.fetchThread.mockResolvedValue(+ err([{ code: 'NOT_FOUND', message: 'Email thread not found' }])+ );++ const result = await readThreadDrafts('thread-1');++ expect(result._unsafeUnwrapErr()).toEqual({+ kind: 'thread-unavailable',+ codes: ['NOT_FOUND'],+ });+ });++ it('ignores local drafts when the draft queue is off', async () => {+ mocks.queueActive.mockReturnValue(false);+ mocks.fetchThread.mockResolvedValue(ok({ thread: { messages: [] } }));++ await readThreadDrafts('thread-1');++ expect(mocks.listLocal).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/email/thread-drafts.ts b/apps/web/src/lib/queries/email/thread-drafts.tsnew file mode 100644index 0000000000..4481c0af49--- /dev/null+++ b/apps/web/src/lib/queries/email/thread-drafts.ts@@ -0,0 +1,90 @@+import type { ApiMessage } from '@service-email/generated/schemas';+import { err, ok, type Result, ResultAsync } from 'neverthrow';+import { draftQueueActive } from './draft-queue';+import { isListedLocalDraft, localDraftRowId } from './local-draft-entities';+import { listLocalDrafts } from './local-drafts';+import { fetchAndCacheThread } from './thread';++/** A draft in a thread that can be discarded without opening its composer. */+export type ThreadDraftHandle = {+ draftId: string;+ draftGeneration: number;+ /** Thread the delete targets; a local-only draft may use a local handle. */+ threadId: string;+ inboxId: string;+};++export type ThreadDraftsError = {+ kind: 'thread-unavailable';+ codes: string[];+};++/** Scheduled drafts are pending sends; cancel the schedule before discarding. */+function isDiscardableDraft(message: ApiMessage): boolean {+ return message.is_draft && !message.scheduled_send_time;+}++/** Working copies on this device that show under the row; queue only. */+async function readLocalThreadDrafts(rowId: string) {+ const none = { handles: [] as ThreadDraftHandle[], ids: new Set<string>() };+ if (!draftQueueActive()) return none;+ // Storage can be unavailable (signed out, private mode); then there are none.+ const drafts = await ResultAsync.fromPromise(listLocalDrafts(), () => null);+ if (drafts.isErr()) return none;+ const listed = drafts.value.filter(+ (draft) => isListedLocalDraft(draft) && localDraftRowId(draft) === rowId+ );+ return {+ handles: listed.map(+ (draft): ThreadDraftHandle => ({+ draftId: draft.draftId,+ draftGeneration: draft.content.draft_generation ?? 0,+ threadId: draft.serverThreadId ?? draft.threadId ?? rowId,+ inboxId: draft.inboxId ?? '',+ })+ ),+ // The server knows a synced working copy by its server ID.+ ids: new Set(+ listed.flatMap((draft) =>+ draft.serverDraftId+ ? [draft.draftId, draft.serverDraftId]+ : [draft.draftId]+ )+ ),+ };+}++/**+ * Reads a row's discardable drafts: unsynced working copies on this device+ * and the thread's server drafts. The fetch also warms the thread cache,+ * which the queued draft delete rebases its optimistic thread onto. A row+ * that exists only on this device has no server thread to read.+ */+export async function readThreadDrafts(+ threadId: string+): Promise<Result<ThreadDraftHandle[], ThreadDraftsError>> {+ const [local, result] = await Promise.all([+ readLocalThreadDrafts(threadId),+ fetchAndCacheThread(threadId),+ ]);+ if (result.isErr()) {+ if (local.handles.length > 0) return ok(local.handles);+ return err({+ kind: 'thread-unavailable',+ codes: result.error.map((error) => error.code),+ });+ }+ const server = result.value.thread.messages+ .filter(+ (message) => isDiscardableDraft(message) && !local.ids.has(message.db_id)+ )+ .map(+ (message): ThreadDraftHandle => ({+ draftId: message.db_id,+ draftGeneration: message.draft_generation,+ threadId,+ inboxId: message.link_id,+ })+ );+ return ok([...local.handles, ...server]);+}diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 1e3f4a411a..93177274cf 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -70,7 +70,12 @@ In every composer `Cmd+Shift+.`, `Cmd+Shift+,` and `Cmd+Shift+D` discard thedraft exactly like its trash button, `Cmd+Shift+U` opens the attach picker, and`Cmd+Shift+X`, `7`, `8` and `9` apply strikethrough, numbered list, bulletedlist and quote. Check discard from both a reply (the reply closes) and-standalone compose (the view goes back), with focus in the body.+standalone compose (the view goes back), with focus in the body. The same+three keys discard the drafts on the focused or selected rows of a list (Email+or a soup view) that carry the Draft badge. The thread keeps its row and its+place, even though its sort time falls back to the last real message, until+the tab, filters, or sort change; only the badge and preview change back to+that message. Check it on a reply draft in All: the row must not move.Star and mute feedback reports what happened to the write. With GraphQL Soupenabled, a star queued while offline toasts that it is waiting to sync (for