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): stop offering mark-not-done on send-only threads (#5214)

Evan Hutniked3e6c2abec0
diff --git a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx b/apps/web/src/features/block-email/component/BottomReplyButtons.tsx
index 3309b32812..6efb143afd 100644
--- a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx
+++ b/apps/web/src/features/block-email/component/BottomReplyButtons.tsx
@@ -70,6 +70,10 @@ export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {
const isDone = () => ctx.isThreadDone();
+ // Matches TopBar: a send-only thread is permanently done, so the toggle
+ // would be a no-op in both directions.
+ const showMarkDoneToggle = () => !isDone() || ctx.canMarkThreadNotDone();
+
const toggleMarkDone = () => {
if (isDone()) {
ctx.markThreadNotDone();
@@ -115,18 +119,20 @@ export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {
/>
</div>
- <ReplyActionButton
- icon={(iconProps) => (
- <Show
- when={isDone()}
- fallback={<CheckIcon class={iconProps.class} />}
- >
- <CheckBoldIcon class={cn(iconProps.class, 'text-accent')} />
- </Show>
- )}
- ariaLabel={isDone() ? 'Mark as not done' : 'Mark done'}
- onClick={toggleMarkDone}
- />
+ <Show when={showMarkDoneToggle()}>
+ <ReplyActionButton
+ icon={(iconProps) => (
+ <Show
+ when={isDone()}
+ fallback={<CheckIcon class={iconProps.class} />}
+ >
+ <CheckBoldIcon class={cn(iconProps.class, 'text-accent')} />
+ </Show>
+ )}
+ ariaLabel={isDone() ? 'Mark as not done' : 'Mark done'}
+ onClick={toggleMarkDone}
+ />
+ </Show>
</div>
</div>
</FloatRegionOrInline>
diff --git a/apps/web/src/features/block-email/component/Email.tsx b/apps/web/src/features/block-email/component/Email.tsx
index e203399c14..28fe583b88 100644
--- a/apps/web/src/features/block-email/component/Email.tsx
+++ b/apps/web/src/features/block-email/component/Email.tsx
@@ -517,6 +517,7 @@ function EmailContent(props: EmailViewProps) {
markDone: context.archiveThread,
markNotDone: context.markThreadNotDone,
isThreadDone: context.isThreadDone,
+ canMarkNotDone: context.canMarkThreadNotDone,
markUnread: context.markThreadUnread,
markRead: context.markThreadRead,
isThreadMarkedUnread: context.isThreadMarkedUnread,
diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsx
index f1944b9908..a4d94bf389 100644
--- a/apps/web/src/features/block-email/component/EmailContext.tsx
+++ b/apps/web/src/features/block-email/component/EmailContext.tsx
@@ -155,6 +155,9 @@ type EmailContextValues = {
archiveThread: (opts?: ArchiveThreadOptions) => boolean;
/** True when the thread is archived, i.e. currently marked done. */
isThreadDone: Accessor<boolean>;
+ /** True when the done state can actually be reversed — see
+ * `markThreadNotDone`. */
+ canMarkThreadNotDone: Accessor<boolean>;
/** Unarchives a done thread and restores its notifications. */
markThreadNotDone: () => boolean;
/** True when the user marked the open thread unread. Resets to false per
@@ -487,6 +490,18 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
return thread ? !thread.inbox_visible : false;
};
+ // Doneness is derived, not stored: `inbox_visible` is recomputed from the
+ // thread's messages as "some message has INBOX and not SENT", and the inbox
+ // view additionally requires an inbound message. A thread with only sent
+ // messages can satisfy neither, so it is permanently done — unarchiving it
+ // reverts on the next recompute and meanwhile labels its sent messages
+ // INBOX, in Gmail too. Only offer the reversal when it can hold.
+ const canMarkThreadNotDone = () => {
+ const thread = threadQuery.data;
+ if (!thread) return false;
+ return !thread.inbox_visible && thread.latest_inbound_message_ts != null;
+ };
+
// Resolve a thread's soup representation for the mark-done / mark-not-done
// paths: the live list row when it's rendered, else the normalized
// soup-cache entity. Shared by markThreadNotDone and archiveThread.
@@ -502,6 +517,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
if (thread.inbox_visible) return false;
+ if (!canMarkThreadNotDone()) return false;
+
// Mark-not-done issues the /archived request itself (plus notification
// and soup-cache restore), so the path below skips archiveMutation and
// only mirrors its thread-cache handling via trackExternalThreadArchive.
@@ -876,6 +893,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
onRecipientsChange,
archiveThread,
isThreadDone,
+ canMarkThreadNotDone,
markThreadNotDone,
isThreadMarkedUnread: threadMarkedUnread,
markThreadUnread,
diff --git a/apps/web/src/features/block-email/component/TopBar.tsx b/apps/web/src/features/block-email/component/TopBar.tsx
index 046dffb7b2..0a35e510cf 100644
--- a/apps/web/src/features/block-email/component/TopBar.tsx
+++ b/apps/web/src/features/block-email/component/TopBar.tsx
@@ -91,6 +91,10 @@ export function TopBar(props: {
const isDone = () => emailCtx.isThreadDone();
+ // 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();
@@ -289,7 +293,7 @@ export function TopBar(props: {
</Show>
</Button>
</Show>
- <Show when={isOwnThread()}>
+ <Show when={isOwnThread() && showMarkDoneToggle()}>
<Button
class="p-1 rounded-lg"
label={isDone() ? 'Mark as not done' : 'Mark done'}
diff --git a/apps/web/src/features/block-email/util/emailHotkeys.ts b/apps/web/src/features/block-email/util/emailHotkeys.ts
index baf814ea3c..8e46c020d2 100644
--- a/apps/web/src/features/block-email/util/emailHotkeys.ts
+++ b/apps/web/src/features/block-email/util/emailHotkeys.ts
@@ -10,6 +10,10 @@ interface EmailHotkeyHandlers {
markNotDone: () => boolean;
/** Gates which of Mark done / Mark as not done is active. */
isThreadDone: () => boolean;
+ /** Whether the done state can be reversed at all — false for threads that
+ * are structurally done (no inbound message), where Mark as not done is a
+ * no-op. */
+ canMarkNotDone: () => boolean;
markUnread: () => boolean;
markRead: () => boolean;
/** Gates which of Mark as unread / Mark as read is active. */
@@ -68,7 +72,7 @@ export function registerEmailHotkeys(
keyDownHandler: handlers.markNotDone,
hotkeyToken: TOKENS.entity.action.markNotDone,
displayPriority: 10,
- condition: () => handlers.isThreadDone(),
+ condition: () => handlers.isThreadDone() && handlers.canMarkNotDone(),
});
registerHotkey({
hotkey: 'u',
diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts
new file mode 100644
index 0000000000..b0f8d9f7f4
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.test.ts
@@ -0,0 +1,106 @@
+import type { EntityData } from '@entity';
+import type { NotificationSource } from '@notifications';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ threadCanBeMarkedNotDone: vi.fn(async (_id: string) => true),
+ executeMarkEntitiesUndone: vi.fn(async () => {}),
+ resolveMarkEntitiesDoneVariables: vi.fn(
+ ({ entities }: { entities: EntityData[] }) => ({
+ emailIds: entities.map((e) => e.id),
+ notificationIds: [],
+ })
+ ),
+ alert: vi.fn(),
+ success: vi.fn(),
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: {
+ alert: mocks.alert,
+ failure: vi.fn(),
+ success: mocks.success,
+ },
+}));
+
+vi.mock('@queries/email/thread', () => ({
+ threadCanBeMarkedNotDone: mocks.threadCanBeMarkedNotDone,
+}));
+
+vi.mock('@queries/notification/user-notifications', () => ({
+ fetchDoneNotificationIdsByEventItemIds: vi.fn(async () => []),
+}));
+
+vi.mock('@queries/soup/cache', () => ({
+ invalidateAllSoup: vi.fn(),
+ refetchSoupEntity: vi.fn(async () => {}),
+}));
+
+vi.mock('@app/features/next-soup/utils', () => ({
+ applyEntitiesNotDoneOptimistic: vi.fn(() => ({ rollback: vi.fn() })),
+ executeMarkEntitiesUndone: mocks.executeMarkEntitiesUndone,
+ resolveMarkEntitiesDoneVariables: mocks.resolveMarkEntitiesDoneVariables,
+}));
+
+import { makeMarkNotDoneAction } from './make-mark-not-done-action';
+
+const doneEmail = (id: string) =>
+ ({ type: 'email', id, done: true }) as EntityData;
+
+function createAction() {
+ return makeMarkNotDoneAction({
+ notificationSource: () => ({}) as NotificationSource,
+ });
+}
+
+describe('makeMarkNotDoneAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.threadCanBeMarkedNotDone.mockImplementation(async () => true);
+ });
+
+ it('unarchives a thread that has an inbound message', async () => {
+ await createAction().execute([doneEmail('inbound')]);
+
+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith(
+ expect.objectContaining({ emailIds: ['inbound'] })
+ );
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+
+ // A send-only thread is permanently done: unarchiving reverts on the next
+ // server-side recompute and meanwhile labels its sent messages INBOX.
+ it('skips a thread with no inbound message and explains why', async () => {
+ mocks.threadCanBeMarkedNotDone.mockImplementation(async () => false);
+
+ await createAction().execute([doneEmail('sent-only')]);
+
+ expect(mocks.executeMarkEntitiesUndone).not.toHaveBeenCalled();
+ expect(mocks.alert).toHaveBeenCalledOnce();
+ });
+
+ it('unarchives only the eligible threads in a mixed selection', async () => {
+ mocks.threadCanBeMarkedNotDone.mockImplementation(
+ async (id: string) => id === 'inbound'
+ );
+
+ await createAction().execute([
+ doneEmail('inbound'),
+ doneEmail('sent-only'),
+ ]);
+
+ expect(mocks.executeMarkEntitiesUndone).toHaveBeenCalledWith(
+ expect.objectContaining({ emailIds: ['inbound'] })
+ );
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+
+ it('does not resolve threads when nothing is done', async () => {
+ await createAction().execute([
+ { type: 'email', id: 'not-done', done: false } as EntityData,
+ ]);
+
+ expect(mocks.threadCanBeMarkedNotDone).not.toHaveBeenCalled();
+ expect(mocks.executeMarkEntitiesUndone).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
index 47382f103c..e24b3fa8d5 100644
--- a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts
@@ -6,6 +6,7 @@ import {
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
import type { NotificationSource } from '@notifications';
+import { threadCanBeMarkedNotDone } from '@queries/email/thread';
import { fetchDoneNotificationIdsByEventItemIds } from '@queries/notification/user-notifications';
import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';
import type { SoupState } from '../create-soup-state';
@@ -18,15 +19,35 @@ type MakeMarkNotDoneOptions = {
* Reverses a mark-done: unarchives email threads and restores their
* notifications. Only done emails qualify — other entity types' done state
* lives on their notifications, and their rows never render as done in the
- * mark-done-capable views.
+ * mark-done-capable views. Threads whose done state can't be reversed (no
+ * inbound message) are dropped at execute time; see
+ * `threadCanBeMarkedNotDone`.
*/
export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {
const canExecute = (entity: EntityData): boolean =>
entity.type === 'email' && entity.done === true;
const execute = async (entities: EntityData[]) => {
- const targets = entities.filter(canExecute);
- if (targets.length === 0) return;
+ const candidates = entities.filter(canExecute);
+ if (candidates.length === 0) return;
+
+ // `done` alone doesn't mean the state is reversible — a thread with only
+ // sent messages is permanently done. Soup rows can't tell, so resolve it
+ // from the thread itself (cached when the thread is open).
+ const eligibility = await Promise.all(
+ candidates.map((entity) => threadCanBeMarkedNotDone(entity.id))
+ );
+ const targets = candidates.filter((_, i) => eligibility[i]);
+
+ if (targets.length === 0) {
+ toast.alert(
+ candidates.length > 1
+ ? 'These threads have no received messages, so they stay done'
+ : 'This thread has no received messages, so it stays done',
+ { duration: 4_000 }
+ );
+ return;
+ }
const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({
entities: targets,
diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.ts
index d4c5c27462..061c02653d 100644
--- a/apps/web/src/lib/queries/email/thread.ts
+++ b/apps/web/src/lib/queries/email/thread.ts
@@ -115,6 +115,28 @@ export async function fetchAndCacheThread(
return ok({ thread: thread! });
}
+/**
+ * Whether a thread's done state can actually be reversed.
+ *
+ * Doneness is derived, not stored: `inbox_visible` is recomputed server-side
+ * as "some message has INBOX and not SENT", and the inbox view additionally
+ * requires an inbound message. A thread with only sent messages satisfies
+ * neither, so it is permanently done — unarchiving it reverts on the next
+ * recompute and meanwhile labels its own sent messages INBOX, in Gmail too.
+ *
+ * Soup rows carry no inbound-message field, so this resolves the thread
+ * (served from cache when it is already loaded). A failed lookup resolves to
+ * `true`: the unarchive that follows would fail the same way, and blocking on
+ * a transient error would misreport ordinary threads as unreversible.
+ */
+export async function threadCanBeMarkedNotDone(
+ threadId: string
+): Promise<boolean> {
+ const result = await fetchAndCacheThread(threadId);
+ if (result.isErr()) return true;
+ return result.value.thread.latest_inbound_message_ts != null;
+}
+
type ThreadQueryData = {
thread: Thread;
hasMore: boolean;