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(app/email): consolidate queries package + block-email using tanstack query (#480)
teo1006a3232efc
diff --git a/js/app/bun.lock b/js/app/bun.lockindex 136637ae92..f0a144d8e8 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -35,6 +35,7 @@"@lexical/selection": "^0.32.1","@lexical/table": "^0.32.1","@lexical/utils": "^0.32.1",+ "@lukemorales/query-key-factory": "^1.3.4","@macro-inc/document-processing-job-types": "^0.1.1","@panzoom/panzoom": "^4.6.0","@phosphor-icons/core": "^2.1.1",@@ -947,6 +948,8 @@"@lezer/rust": ["@lezer/[email protected]", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg=="],+ "@lukemorales/query-key-factory": ["@lukemorales/[email protected]", "", { "peerDependencies": { "@tanstack/query-core": ">= 4.0.0", "@tanstack/react-query": ">= 4.0.0" } }, "sha512-A3frRDdkmaNNQi6mxIshsDk4chRXWoXa05US8fBo4kci/H+lVmujS6QrwQLLGIkNIRFGjMqp2uKjC4XsLdydRw=="],+"@macro-inc/document-processing-job-types": ["@macro-inc/[email protected]", "https://npm.pkg.github.com/download/@macro-inc/document-processing-job-types/0.1.1/b1069c0d9531c77827d9f01ee3263dc37998cc96", { "dependencies": { "zod": "^3.23.4" } }, "sha512-MkkJTS9qstvVyxUJg4eLQSlpeuYVfpL59vtkIhsWP4JooEWBlte0hRo+MxO1XrBJ96TnNdGsh+iiCgjvcAsxfQ=="],"@macro-inc/lexical-core": ["@macro-inc/lexical-core@workspace:packages/lexical-core"],@@ -1313,6 +1316,8 @@"@tanstack/query-devtools": ["@tanstack/[email protected]", "", {}, "sha512-GtINOPjPUH0OegJExZ70UahT9ykmAhmtNVcmtdnOZbxLwT7R5OmRztR5Ahe3/Cu7LArEmR6/588tAycuaWb1xQ=="],+ "@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.12" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-graRZspg7EoEaw0a8faiUASCyJrqjKPdqJ9EwuDRUF9mEYJ1YPczI9H+/agJ0mOJkPCJDk0lsz5QTrLZ/jQ2rg=="],+"@tanstack/solid-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.2" }, "peerDependencies": { "solid-js": "^1.6.0" } }, "sha512-XEP+fzZYes+GLA4HSvmitj2NCC7o9iwMvwdkI5R7YSQD08jd1rA9p4KUYWvcu8VfMD+jodOCn/iMHmPz8zV3qw=="],"@tanstack/solid-query-devtools": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-devtools": "5.90.1" }, "peerDependencies": { "@tanstack/solid-query": "^5.90.3", "solid-js": "^1.6.0" } }, "sha512-UWb2/tHgHrMetOHrQFCzpivCJyttG7vb6axav/aiih9CN5PArxb6um1/7eOuWTb43vSRaMt2LP2Dj3fhixtDZA=="],@@ -4343,6 +4348,8 @@"@tailwindcss/oxide-wasm32-wasi/tslib": ["[email protected]", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+ "@tanstack/react-query/@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-T1/8t5DhV/SisWjDnaiU2drl6ySvsHj1bHBCWNXd+/T+Hh1cf6JodyEYMd5sgwm+b/mETT4EV3H+zCVczCU5hg=="],+"@testing-library/dom/aria-query": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A=="],"@testing-library/dom/dom-accessibility-api": ["[email protected]", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],diff --git a/js/app/package.json b/js/app/package.jsonindex 90b3f3d5fd..efeefd1cf9 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -71,6 +71,7 @@"@lexical/selection": "^0.32.1","@lexical/table": "^0.32.1","@lexical/utils": "^0.32.1",+ "@lukemorales/query-key-factory": "^1.3.4","@macro-inc/document-processing-job-types": "^0.1.1","@panzoom/panzoom": "^4.6.0","@phosphor-icons/core": "^2.1.1",diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex 4159eab3fb..10c31e6119 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -15,7 +15,7 @@ import { TOKENS } from '@core/hotkey/tokens';import { isMobileWidth } from '@core/mobile/mobileWidth';import { trackMention } from '@core/signal/mention';import { useDisplayName } from '@core/user';-import { isErr, isOk } from '@core/util/maybeResult';+import { isErr } from '@core/util/maybeResult';import Spinner from '@icon/bold/spinner-gap-bold.svg';import ReplyAll from '@icon/regular/arrow-bend-double-up-left.svg';import Reply from '@icon/regular/arrow-bend-up-left.svg';@@ -29,6 +29,7 @@ import Trash from '@icon/regular/trash.svg';import { DropdownMenu } from '@kobalte/core/dropdown-menu';import type { DocumentMentionInfo } from '@lexical-core';import { logger } from '@observability';+import { useSendMessageMutation } from '@queries/email/thread';import { emailClient } from '@service-email/client';import type {AttachmentMacro,@@ -153,7 +154,6 @@ export function BaseInput(props: {createSignal<boolean>(false);const [isDragging, setIsDragging] = createSignal<boolean>();const [isPendingUpload, setIsPendingUpload] = createSignal<boolean>(false);- const [isPendingSend, setIsPendingSend] = createSignal<boolean>(false);const [showFormatRibbon, setShowFormatRibbon] = createSignal<boolean>(props.newMessage ?? false);@@ -169,6 +169,30 @@ export function BaseInput(props: {MessageToSendDbId | undefined>(props.draft?.db_id ?? undefined);+ let pendingMentions: { documentId: string }[] = [];+ const [shouldMarkDoneOnSuccess, setShouldMarkDoneOnSuccess] =+ createSignal(false);++ const sendMutation = useSendMessageMutation({+ onSuccess: ({ message }) => {+ toast.success('Email sent');+ pendingMentions.forEach((mention) => {+ trackMention(blockId, 'document', mention.documentId);+ });+ pendingMentions = [];+ clearEmailBody(editor());+ resetState();+ props.sideEffectOnSend?.(message.db_id ?? null);+ if (shouldMarkDoneOnSuccess()) {+ props.onSendAndMarkDone?.();+ setShouldMarkDoneOnSuccess(false);+ }+ },+ onError: () => {+ toast.failure('Failed to send email');+ },+ });+// Attach side-effect handlers on mount; they replay against current stateonMount(() => {form().setOnDirty(() => {@@ -234,7 +258,7 @@ export function BaseInput(props: {}async function executeSaveDraft() {- if (isPendingSend()) {+ if (sendMutation.isPending) {return;}const draftToSave = collectDraft();@@ -354,17 +378,16 @@ export function BaseInput(props: {useHotkeyDOMScope('compose-message');let composeContainerRef: HTMLDivElement | undefined;- const sendEmail = async (): Promise<boolean> => {- if (isPendingSend() || isPendingUpload()) return false;- setIsPendingSend(true);+ const sendEmail = async (markDone = false) => {+ if (sendMutation.isPending || isPendingUpload()) return;+const to = form().recipients.to.map(convertEmailRecipientToContactInfo);const cc = form().recipients.cc.map(convertEmailRecipientToContactInfo);const bcc = form().recipients.bcc.map(convertEmailRecipientToContactInfo);if ((to?.length ?? 0) + (cc?.length ?? 0) + (bcc?.length ?? 0) === 0) {toast.failure('Email failed to send. No recipients provided');- setIsPendingSend(false);- return false;+ return;}const currentThread = ctx.threadData();@@ -373,15 +396,13 @@ export function BaseInput(props: {if (!currentThread && !newMessage) {logger.error(new Error("Can't send email, no email thread found"));toast.failure('Email failed to send');- setIsPendingSend(false);- return false;+ return;}if (newMessage && currentThread) {toast.failure('Email failed to send');logger.error('New message and thread cannot be provided together');- setIsPendingSend(false);- return false;+ return;}let linkId: string | undefined = currentThread?.link_id;@@ -390,8 +411,7 @@ export function BaseInput(props: {if (isErr(maybeFallbackLinks) || maybeFallbackLinks[1].links.length < 1) {toast.failure('Email failed to send');logger.error('No links found');- setIsPendingSend(false);- return false;+ return;}linkId = maybeFallbackLinks[1].links[0].id;}@@ -401,11 +421,13 @@ export function BaseInput(props: {replyingTo: props.replyingTo(),});if (!prepared) {- setIsPendingSend(false);- return false;+ return;}- const response = await emailClient.sendMessage({+ pendingMentions = prepared.mentions;+ setShouldMarkDoneOnSuccess(markDone);++ sendMutation.mutate({message: {bcc,body_html: prepared.bodyHtml,@@ -421,33 +443,6 @@ export function BaseInput(props: {link_id: linkId!,},});- if (isOk(response)) {- toast.success('Email sent');- const [, { message }] = response;- prepared.mentions.forEach((mention) => {- trackMention(blockId, 'document', mention.documentId);- });- clearEmailBody(editor());- resetState();- if (props.sideEffectOnSend) {- props.sideEffectOnSend(message.db_id ?? null);- }- setIsPendingSend(false);- return true;- } else {- toast.failure('Failed to send email');- setIsPendingSend(false);- return false;- }- };-- const sendEmailAndMarkDone = async () => {- if (isPendingSend() || isPendingUpload()) return;- const success = await sendEmail();- // Call onSendAndMarkDone after successful send- if (success && props.onSendAndMarkDone) {- props.onSendAndMarkDone();- }};const resetState = () => {@@ -539,7 +534,7 @@ export function BaseInput(props: {scopeId: composeHotkeyScope,description: 'Send and mark done',keyDownHandler: () => {- sendEmailAndMarkDone();+ sendEmail(true);return true;},runWithInputFocused: true,@@ -793,7 +788,7 @@ export function BaseInput(props: {form().setCapturedEditor(editor);}}class={`text-sm break-words text-ink ${isDragging() && 'blur'}`}- editable={() => !isPendingSend()}+ editable={() => !sendMutation.isPending}initialValue={props.preloadedBody}initialHtml={props.preloadedHtml}placeholder="Reply — @mention to share or cc people"@@ -864,9 +859,9 @@ export function BaseInput(props: {<div class="flex flex-row items-center"><TextButtontheme="base"- disabled={isPendingUpload() || isPendingSend()}+ disabled={isPendingUpload() || sendMutation.isPending}onClick={() => {- sendEmailAndMarkDone();+ sendEmail(true);}}tooltip={{label: 'Send and mark done',@@ -874,7 +869,7 @@ export function BaseInput(props: {}}><Show- when={!isPendingUpload() && !isPendingSend()}+ when={!isPendingUpload() && !sendMutation.isPending}fallback={<Spinner class="w-5 h-5 animate-spin cursor-disabled" />}diff --git a/js/app/packages/block-email/component/Block.tsx b/js/app/packages/block-email/component/Block.tsxindex 7890c1aceb..5cf66a4725 100644--- a/js/app/packages/block-email/component/Block.tsx+++ b/js/app/packages/block-email/component/Block.tsx@@ -2,10 +2,8 @@ import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import { withAnalytics } from '@coparse/analytics';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';import { EmailDebouncedReadMarker } from '@notifications';-import { createEffect, createMemo, onMount, Show } from 'solid-js';+import { createMemo, onMount, Show } from 'solid-js';import { blockDataSignal } from '../signal/emailBlockData';-import { createThreadMessagesResource } from '../signal/threadMessages';-import { markThreadAsSeen } from '../util/markThreadAsSeen';import { Email } from './Email';const { track, TrackingEvents } = withAnalytics();@@ -21,54 +19,27 @@ export default function BlockEmail() {return data.thread.messages[0].subject!;});- const threadMessagesResource = createMemo(() => {- const data = blockData();- const threadId = data?.thread?.db_id;- return threadId- ? createThreadMessagesResource(threadId, data.thread)- : null;- });-- const threadData = createMemo(() => {- const resource = threadMessagesResource();- const resourceData = resource?.resource();- return resourceData?.thread;- });+ const threadId = createMemo(() => blockData()?.thread?.db_id ?? '');onMount(() => {track(TrackingEvents.BLOCKEMAIL.OPEN);});- // Mark all messages as read- createEffect(() => {- const data = blockData();- if (!data) return;- let initialThreadLoad = data.thread;- if (!initialThreadLoad.db_id) return;-- markThreadAsSeen(initialThreadLoad.db_id);- });-return (<DocumentBlockContainer title={title() ?? 'Email'}><div class="size-full bracket-never" tabIndex={-1}><Show when={blockData()}>- <Show when={blockData()?.thread?.db_id}>- {(threadId) => {- return (+ <Show when={threadId()}>+ {(id) => (+ <><EmailDebouncedReadMarkernotificationSource={notificationSource}- threadId={threadId()}+ threadId={id()}/>- );- }}+ <Email title={title} threadId={id} />+ </>+ )}</Show>-- title={title}- threadMessagesResource={threadMessagesResource}- threadData={threadData}- /></Show></div></DocumentBlockContainer>diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex 647bc97b27..8cbd282e13 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -20,9 +20,8 @@ import {} from '@core/user';import { isErr } from '@core/util/maybeResult';import Caution from '@icon/regular/warning.svg';+import { useSendMessageMutation } from '@queries/email/thread';import { emailClient } from '@service-email/client';-import type { SendMessageResponse } from '@service-email/generated/schemas';-import { useMutation } from '@tanstack/solid-query';import {createMemo,createResource,@@ -38,11 +37,7 @@ type EmailComposeErrors =| 'no_recipient'| 'no_message'| 'no_subject'- | 'no_link'- | 'generic';-type EmailComposeVariables = {- body: { text: string; html: string; raw: string; attachments?: [] };-};+ | 'no_link';class EmailComposeError {constructor(@@ -125,87 +120,82 @@ export function EmailCompose() {const { replaceSplit } = useSplitLayout();- // TODO: We should handle these errors in a form not in the mutation- const sendEmailMutation = useMutation<- SendMessageResponse,- EmailComposeError | Error,- EmailComposeVariables- >(() => ({- async mutationFn(contents) {- const _link = link();-- if (!selectedRecipients().length) {- const e = 'Please select at least one recipient';- throw new EmailComposeError('no_recipient', e);- }-- if (!contents.body.raw.trim()) {- const e = 'Please enter a message';- throw new EmailComposeError('no_message', e);- }-- if (!subject()?.trim()) {- const e = 'Please enter a subject';- throw new EmailComposeError('no_subject', e);- }- if (!_link) {- const e = 'Unable to find linked email account';- throw new EmailComposeError('no_link', e);- }-- const result = await emailClient.sendMessage({- message: {- link_id: _link.id, // For new emails- to: convertToContactInfoArray(selectedRecipients()),- cc:- ccRecipients && ccRecipients.length > 0- ? convertToContactInfoArray(ccRecipients())- : [],- bcc:- bccRecipients && bccRecipients.length > 0- ? convertToContactInfoArray(bccRecipients())- : [],- subject: subject(),- body_text: contents.body.text,- body_html: contents.body.html,- body_macro: contents.body.raw,- attachments: [],- },- });-- if (isErr(result)) {- const e = 'Failed to send email';- throw new EmailComposeError('generic', e);- }+ const [validationError, setValidationError] =+ createSignal<EmailComposeError | null>(null);- return result[1];- },- mutationKey: ['compose-email'],- onError(error) {- if (error instanceof Error || error.type === 'generic') {- toast.failure(error instanceof Error ? error.message : error.message);- }- },- onSuccess(data) {+ const sendMutation = useSendMessageMutation({+ onSuccess: (data) => {toast.success('Email sent');if (data.message.thread_db_id) {replaceSplit({ type: 'email', id: data.message.thread_db_id }, true);}},- }));+ onError: () => {+ toast.failure('Failed to send email');+ },+ });const onSubmit = (data: ComposeInputData) => {- sendEmailMutation.mutate(data);- };+ setValidationError(null);- const withMutationError = (type: EmailComposeErrors) => {- const error = sendEmailMutation.error;+ const _link = link();- if (!error || error instanceof Error) return;+ if (!selectedRecipients().length) {+ setValidationError(+ new EmailComposeError(+ 'no_recipient',+ 'Please select at least one recipient'+ )+ );+ return;+ }- if (error.type !== type) return;+ if (!data.body.raw.trim()) {+ setValidationError(+ new EmailComposeError('no_message', 'Please enter a message')+ );+ return;+ }++ if (!subject()?.trim()) {+ setValidationError(+ new EmailComposeError('no_subject', 'Please enter a subject')+ );+ return;+ }++ if (!_link) {+ setValidationError(+ new EmailComposeError('no_link', 'Unable to find linked email account')+ );+ return;+ }++ sendMutation.mutate({+ message: {+ link_id: _link.id,+ to: convertToContactInfoArray(selectedRecipients()),+ cc:+ ccRecipients().length > 0+ ? convertToContactInfoArray(ccRecipients())+ : [],+ bcc:+ bccRecipients().length > 0+ ? convertToContactInfoArray(bccRecipients())+ : [],+ subject: subject(),+ body_text: data.body.text,+ body_html: data.body.html,+ body_macro: data.body.raw,+ attachments: [],+ },+ });+ };- return error;+ const withValidationError = (type: EmailComposeErrors) => {+ const error = validationError();+ if (error?.type === type) return error;+ return undefined;};return (@@ -330,7 +320,7 @@ export function EmailCompose() {disabled={hasLinkError()}/></div>- <Show when={withMutationError('no_recipient')}>+ <Show when={withValidationError('no_recipient')}>{(err) => (<div class="text-failure-ink text-sm mt-1">{err().message}@@ -397,7 +387,7 @@ export function EmailCompose() {/></div>- <Show when={withMutationError('no_subject')}>+ <Show when={withValidationError('no_subject')}>{(err) => (<div class="text-failure-ink text-sm mt-1">{err().message}@@ -416,10 +406,10 @@ export function EmailCompose() {><ComposeEmailInputonSubmit={onSubmit}- isSubmitting={sendEmailMutation.isPending}+ isSubmitting={sendMutation.isPending}disabled={hasLinkError()}/>- <Show when={withMutationError('no_message')}>+ <Show when={withValidationError('no_message')}>{(err) => (<div class="text-failure-ink text-sm mt-1">{err().message}diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsxindex 96f46a4107..58eccfe661 100644--- a/js/app/packages/block-email/component/Email.tsx+++ b/js/app/packages/block-email/component/Email.tsx@@ -1,5 +1,6 @@import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import { toast } from '@core/component/Toast/Toast';import { TOKENS } from '@core/hotkey/tokens';import { registerScopeSignalHotkey } from '@core/hotkey/utils';import { createMethodRegistration } from '@core/orchestrator';@@ -18,9 +19,11 @@ import {createEffectOnEntityTypeNotification,isNotificationWithMetadata,} from '@notifications';-import { emailClient } from '@service-email/client';+import {+ useArchiveThreadMutation,+ useThreadQuery,+} from '@queries/email/thread';import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';-import type { Thread } from '@service-email/generated/schemas/thread';import { createCallback } from '@solid-primitives/rootless';import { useSearchParams } from '@solidjs/router';import {@@ -35,7 +38,6 @@ import {import { createStore } from 'solid-js/store';import { URL_PARAMS } from '../constants';import { isScrollingToMessage } from '../signal/scrollState';-import type { createThreadMessagesResource } from '../signal/threadMessages';import { registerEmailHotkeys } from '../util/emailHotkeys';import { getHeaderValue } from '../util/getHeaderValue';import {@@ -51,10 +53,7 @@ import { TopBar } from './TopBar';type EmailProps = {title: Accessor<string>;- threadMessagesResource: Accessor<ReturnType<- typeof createThreadMessagesResource- > | null>;- threadData: Accessor<Thread | undefined>;+ threadId: Accessor<string>;};export function Email(props: EmailProps) {@@ -69,6 +68,18 @@ export function Email(props: EmailProps) {},} = useSplitPanelOrThrow();+ const threadQuery = useThreadQuery(props.threadId);+ const threadData = () => threadQuery.data?.thread;+ const hasMore = () => threadQuery.data?.hasMore ?? false;+ const isFetching = () => threadQuery.isFetching;+ const fetchNextPage = () => threadQuery.fetchNextPage();++ const { mutate: archiveThreadMutate } = useArchiveThreadMutation({+ onError: () => {+ toast.failure('Failed to archive thread');+ },+ });+const [searchParams] = useSearchParams();const searchParamsMessageId = () => {if (typeof searchParams.message_id === 'string') {@@ -84,8 +95,7 @@ export function Email(props: EmailProps) {const filteredMessages = createMemo(() => {return (- props- .threadData()+ threadData()?.messages.filter((message) => !message.is_draft).sort((a, b) => {if (a.internal_date_ts && b.internal_date_ts) {@@ -111,7 +121,7 @@ export function Email(props: EmailProps) {const initialDraftChildren: Record<string, MessageWithBodyReplyless> =(() => {- const t = untrack(() => props.threadData());+ const t = untrack(threadData);const map: Record<string, MessageWithBodyReplyless> = {};if (!t) return map;for (const message of t.messages) {@@ -162,8 +172,7 @@ export function Email(props: EmailProps) {.map(recipientEntityMapper('user')).forEach((u) => optionsMap.set(u.data.email, u));- const t = props.threadData();-+ const t = threadData();if (t) {const seen = new Map<string, ContactInfo>();@@ -228,14 +237,12 @@ export function Email(props: EmailProps) {// ============================================/**- * Waits for a resource to finish loading+ * Waits for the query to finish fetching*/- const waitForResourceLoad = (- resource: ReturnType<typeof createThreadMessagesResource>- ): Promise<void> => {+ const waitForQueryLoad = (): Promise<void> => {return new Promise((resolve) => {const checkInterval = setInterval(() => {- if (!resource.loading()) {+ if (!threadQuery.isFetching) {clearInterval(checkInterval);resolve();}@@ -247,11 +254,10 @@ export function Email(props: EmailProps) {* Loads messages until the target message is found or no more messages available*/const loadMessagesUntilFound = async (- targetMessageId: string,- resource: ReturnType<typeof createThreadMessagesResource>+ targetMessageId: string): Promise<boolean> => {while (true) {- const data = resource.resource();+ const data = threadQuery.data;// Check if message exists in current batchconst messageExists = data?.thread.messages.some(@@ -264,8 +270,8 @@ export function Email(props: EmailProps) {if (!data?.hasMore) return false;// Load next batch and wait- resource.loadMore();- await waitForResourceLoad(resource);+ threadQuery.fetchNextPage();+ await waitForQueryLoad();}};@@ -273,12 +279,10 @@ export function Email(props: EmailProps) {* Loads one more batch of messages for better scroll context* (useful when target message is at the edge of loaded messages)*/- const loadContextBatch = async (- resource: ReturnType<typeof createThreadMessagesResource>- ): Promise<void> => {- if (resource.resource()?.hasMore && !resource.loading()) {- resource.loadMore();- await waitForResourceLoad(resource);+ const loadContextBatch = async (): Promise<void> => {+ if (hasMore() && !isFetching()) {+ fetchNextPage();+ await waitForQueryLoad();}};@@ -349,22 +353,16 @@ export function Email(props: EmailProps) {// This effect ensures we have enough messages to fill the viewport// to avoid a sparse UI on initial loadcreateEffect(() => {- const resource = props.threadMessagesResource();const messageList = messagesRef();const containerRef = messagesContainerRef();// Skip if dependencies not ready- if (- !resource ||- !messageList ||- !containerRef ||- !untrack(() => props.threadData()?.db_id)- ) {+ if (!messageList || !containerRef || !untrack(threadData)?.db_id) {return;}// Skip if still loading or already filled- if (resource.loading() || untrack(isContainerFilled)) {+ if (isFetching() || untrack(isContainerFilled)) {return;}@@ -372,8 +370,8 @@ export function Email(props: EmailProps) {const containerHeight = containerRef.getBoundingClientRect().height;// Load more if container isn't filled- if (messageListHeight < containerHeight) {- resource.loadMore();+ if (messageListHeight < containerHeight && hasMore()) {+ fetchNextPage();} else {setIsContainerFilled(true);}@@ -386,14 +384,11 @@ export function Email(props: EmailProps) {// This effect should only run once.createEffect(() => {if (hasHandledTarget()) return;- const resource = props.threadMessagesResource();- if (!resource) return;+ const data = threadQuery.data;+ if (!data) return;// Check if initial loading is complete- const resourceData = resource.resource();const isInitialLoadComplete =- !!resourceData &&- (isContainerFilled() || resourceData.hasMore === false) &&- !resource.loading();+ (isContainerFilled() || data.hasMore === false) && !isFetching();// Skip if not readyif (!isInitialLoadComplete) {@@ -401,7 +396,7 @@ export function Email(props: EmailProps) {}// Skip if basic requirements not met- if (!untrack(() => props.threadData()) || !untrack(() => messagesRef())) {+ if (!untrack(threadData) || !untrack(() => messagesRef())) {return;}@@ -436,17 +431,14 @@ export function Email(props: EmailProps) {const messages = untrack(() => filteredMessages());if (!messages) return;const targetIndex = messages.findIndex((m) => m.db_id === messageId);- const resource = untrack(() => props.threadMessagesResource());-- if (!resource) return;// Case 1: Message not in current loaded batch - need to load moreif (targetIndex < 0) {try {- const found = await loadMessagesUntilFound(messageId, resource);+ const found = await loadMessagesUntilFound(messageId);if (found) {// Load one more batch for scroll context- await loadContextBatch(resource);+ await loadContextBatch();// Scroll to the message after DOM updatessetTimeout(() => performScrollToMessage(messageId, 'smooth'));} else {@@ -460,7 +452,7 @@ export function Email(props: EmailProps) {}// Case 2: Message is first in current batch - load more for contextelse if (targetIndex === 0) {- await loadContextBatch(resource);+ await loadContextBatch();setTimeout(() => performScrollToMessage(messageId, 'smooth'));}// Case 3: Message is in current batch with sufficient context@@ -470,18 +462,25 @@ export function Email(props: EmailProps) {}const archiveThread = createCallback(() => {- if (!props.threadData()) return false;+ const thread = threadData();+ if (!thread?.db_id) return false;+ archiveThreadMutate({+ threadId: thread.db_id,+ archive: thread.inbox_visible,+ });++ if (!props) return false;const selectedEntity = entities()?.find(- (entity) => entity.id === props.threadData()!.db_id+ (entity) => entity.id === threadData()!.db_id);if (selectedEntity) {actionRegistry.execute('mark_as_done', selectedEntity);} else {- emailClient.flagArchived({- value: props.threadData()!.inbox_visible,- id: props.threadData()!.db_id!,+ archiveThreadMutate({+ threadId: thread.db_id,+ archive: thread.inbox_visible,});}@@ -541,7 +540,7 @@ export function Email(props: EmailProps) {const navigateToNextMessage = createCallback(() => navigateMessage('next'));onMount(() => {- registerEmailHotkeys(scopeId(), props.threadData, {+ registerEmailHotkeys(scopeId(), threadData, {archiveThread,navigateToPreviousMessage,navigateToNextMessage,@@ -576,10 +575,8 @@ export function Email(props: EmailProps) {const notificationThreadId = (metadata as { thread_id: string }).thread_id;- if (notificationThreadId === props.threadData()?.db_id) {- const resource = props.threadMessagesResource();- if (!resource) return;- resource.refresh();+ if (notificationThreadId === threadData()?.db_id) {+ threadQuery.refetch();break;}}@@ -601,6 +598,8 @@ export function Email(props: EmailProps) {hide: true,});+ const refetch = () => threadQuery.refetch();+return (<EmailProvidervalue={{@@ -610,11 +609,15 @@ export function Email(props: EmailProps) {setMessageDbIdToDraftChildren,messagesRef,setMessagesRef: setmessagesRef,- threadMessagesResource: props.threadMessagesResource,+ threadId: props.threadId,focusedMessageId,setFocusedMessageId,filteredMessages,- threadData: props.threadData,+ threadData,+ hasMore,+ isFetching,+ fetchNextPage,+ refetch,archiveThread,activeTargetMessageId,}}diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 76db4248ed..ad9dbaf4f2 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -10,7 +10,6 @@ import {useContext,} from 'solid-js';import type { SetStoreFunction } from 'solid-js/store';-import type { createThreadMessagesResource } from '../signal/threadMessages';export type EmailRecipient = WithCustomUserInput<'user' | 'contact'>;@@ -23,13 +22,15 @@ export type EmailContextValue = {>;messagesRef: Accessor<HTMLDivElement | undefined>;setMessagesRef: Setter<HTMLDivElement | undefined>;- threadMessagesResource: Accessor<ReturnType<- typeof createThreadMessagesResource- > | null>;+ threadId: Accessor<string>;focusedMessageId: Accessor<string | undefined>;setFocusedMessageId: Setter<string | undefined>;filteredMessages: Accessor<MessageWithBodyReplyless[]>;threadData: Accessor<Thread | undefined>;+ hasMore: Accessor<boolean>;+ isFetching: Accessor<boolean>;+ fetchNextPage: () => void;+ refetch: () => void;archiveThread: Accessor<boolean>;activeTargetMessageId: Accessor<string | undefined>;};diff --git a/js/app/packages/block-email/component/EmailInput.tsx b/js/app/packages/block-email/component/EmailInput.tsxindex dd81c4e33a..99b6437ef2 100644--- a/js/app/packages/block-email/component/EmailInput.tsx+++ b/js/app/packages/block-email/component/EmailInput.tsx@@ -26,9 +26,6 @@ export function EmailInput(props: EmailInputProps) {});function afterSend(newMessageId: MessageToSendDbId | null) {- const resource = ctx.threadMessagesResource();- if (!resource) return;-// Delete the draft from our storeconst parentId = props.replyingTo()?.db_id?.toString();if (parentId) {@@ -42,7 +39,7 @@ export function EmailInput(props: EmailInputProps) {props.setShowReply?.(false);// Refresh to get the new message- resource.refresh();+ ctx.refetch();// Set focus to new message if providedif (newMessageId) ctx.setFocusedMessageId(newMessageId);diff --git a/js/app/packages/block-email/component/MessageList.tsx b/js/app/packages/block-email/component/MessageList.tsxindex 50a69143d4..67ff2b0af1 100644--- a/js/app/packages/block-email/component/MessageList.tsx+++ b/js/app/packages/block-email/component/MessageList.tsx@@ -35,16 +35,12 @@ export function MessageList(props: MessageListProps) {const threshold = 300;const isNearBeginning = e.currentTarget.scrollTop <= threshold;- const resource = context.threadMessagesResource();- if (isNearBeginning && resource && !resource.loading()) {- const resourceData = resource.resource();- if (resourceData?.hasMore) {- resource.loadMore();- }+ if (isNearBeginning && !context.isFetching() && context.hasMore()) {+ context.fetchNextPage();}}}>- <Show when={context.threadMessagesResource()?.loading()}>+ <Show when={context.isFetching()}><div class="flex items-center justify-center h-16"><CircleSpinner /></div>diff --git a/js/app/packages/block-email/definition.ts b/js/app/packages/block-email/definition.tsindex 224170c31f..4124b61b60 100644--- a/js/app/packages/block-email/definition.ts+++ b/js/app/packages/block-email/definition.ts@@ -1,7 +1,6 @@import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';-import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';import { isErr, ok } from '@core/util/maybeResult';-import { emailClient } from '@service-email/client';+import { fetchAndCacheThread } from '@queries/email/thread';import EmailBlock from './component/Block';export const definition = defineBlock({@@ -13,11 +12,11 @@ export const definition = defineBlock({async load(source) {if (source.type === 'dss') {- let email = await emailClient.getThread({- thread_id: source.id,- offset: 0,- limit: DEFAULT_THREAD_MESSAGES_LIMIT,- });+ let email = await fetchAndCacheThread(source.id);++ if (!email) {+ return LoadErrors.MISSING;+ }if (isErr(email)) {if (isErr(email, 'MISSING')) {diff --git a/js/app/packages/block-email/signal/threadMessages.ts b/js/app/packages/block-email/signal/threadMessages.tsdeleted file mode 100644index e491d75338..0000000000--- a/js/app/packages/block-email/signal/threadMessages.ts+++ /dev/null@@ -1,130 +0,0 @@-import { createBlockResource } from '@core/block';-import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';-import { isErr } from '@core/util/maybeResult';-import { logger } from '@observability/logger';-import { emailClient } from '@service-email/client';-import type { Thread } from '@service-email/generated/schemas/thread';-import { reconcile } from 'solid-js/store';--export type ThreadMessagesFetchResult = {- thread: Thread;- hasMore: boolean;-};--const fetchThreadMessages = async (- threadId: string,- {- value,- refetching,- }: {- value?: ThreadMessagesFetchResult;- refetching?: boolean | { offset?: number };- }-): Promise<ThreadMessagesFetchResult> => {- const offset =- refetching && typeof refetching === 'object' && refetching.offset- ? refetching.offset- : 0;-- const result = await emailClient.getThread({- thread_id: threadId,- offset,- limit: DEFAULT_THREAD_MESSAGES_LIMIT,- });-- if (isErr(result)) {- logger.error(`Failed to get email thread messages: ${result[0]}`);- throw new Error(`Failed to get email thread messages: ${result[0]}`);- }-- const [, data] = result;- const newMessages = data.thread.messages ?? [];-- const existingMessages = offset > 0 && value ? value.thread.messages : [];- const allMessages = [...existingMessages, ...newMessages];-- const hasMore = newMessages.length === DEFAULT_THREAD_MESSAGES_LIMIT;-- return {- thread: {- ...data.thread,- messages: allMessages,- },- hasMore,- };-};--export const createThreadMessagesResource = (- threadId: string,- initialThread?: Thread-) => {- // Create initial data from the thread if provided- const initialData: ThreadMessagesFetchResult | undefined = initialThread- ? {- thread: initialThread,- hasMore: initialThread.messages.length >= DEFAULT_THREAD_MESSAGES_LIMIT,- }- : undefined;-- const [resource, { mutate, refetch }] = createBlockResource(- () => threadId,- fetchThreadMessages,- { initialValue: initialData }- );-- const loadMore = () => {- const currentData = resource();- if (currentData && currentData.hasMore && !resource.loading) {- const nextOffset = currentData.thread.messages.length;- refetch({ offset: nextOffset });- }- };-- const refresh = async () => {- const freshResult = await emailClient.getThread({- thread_id: threadId,- offset: 0,- limit: DEFAULT_THREAD_MESSAGES_LIMIT,- });- if (isErr(freshResult)) {- logger.error(- `Failed to refresh email thread messages: ${freshResult[0]}`- );- return;- }- const [, freshData] = freshResult;- const currentData = resource();- if (!currentData) {- refetch({ offset: 0 });- return;- }-- // We need to manually reconcile messages in the thread, to maintain- // referential stability across updates. Without this solid will treat all the messages as new,- // re-render all of them, which will cause a flicker. With this only the new messages will be added.- mutate((prev) => {- if (!prev) return prev;-- return {- ...prev,- thread: {- ...freshData.thread,- messages: reconcile(freshData.thread.messages, {- key: 'db_id',- merge: false, // Don't merge partial updates, replace entirely- })(prev.thread.messages),- },- hasMore:- freshData.thread.messages.length >= DEFAULT_THREAD_MESSAGES_LIMIT,- };- });- };-- return {- resource,- mutate,- loadMore,- refresh,- loading: () => resource.loading,- };-};diff --git a/js/app/packages/block-email/util/markThreadAsSeen.ts b/js/app/packages/block-email/util/markThreadAsSeen.tsdeleted file mode 100644index 5c1cddd2a3..0000000000--- a/js/app/packages/block-email/util/markThreadAsSeen.ts+++ /dev/null@@ -1,12 +0,0 @@-import { isErr } from '@core/util/maybeResult';-import { logger } from '@observability';-import { emailClient } from '@service-email/client';--export async function markThreadAsSeen(threadId: string) {- const result = await emailClient.markThreadAsSeen({- thread_id: threadId,- });- if (isErr(result)) {- logger.error('Failed to mark email thread as seen', result[0]);- }-}diff --git a/js/app/packages/core/util/maybeResult.ts b/js/app/packages/core/util/maybeResult.tsindex c40d490781..0252f6780e 100644--- a/js/app/packages/core/util/maybeResult.ts+++ b/js/app/packages/core/util/maybeResult.ts@@ -313,6 +313,51 @@ export type ResultType<T extends MaybeResult<any, any>> = T extends MaybeResult<? NonNullable<R>: never;+/**+ * Error class that preserves MaybeResult errors when thrown.+ * Enables round-trip conversion between MaybeResult and throwable functions.+ */+export class MaybeResultError<E extends string = string> extends Error {+ constructor(public readonly errors: ResultError<E>[]) {+ super(errors.map((e) => e.message).join(', '));+ this.name = 'MaybeResultError';+ }+}++/**+ * Wraps a MaybeResult-returning async function to throw on error.+ * Useful for tanstack-query and other APIs that expect thrown errors.+ */+export async function throwOnErr<E extends string, T>(+ fn: () => Promise<MaybeResult<E, T>>+): Promise<T> {+ const result = await fn();+ if (isErr(result)) {+ throw new MaybeResultError(result[0]);+ }+ return result[1];+}++/**+ * Wraps an async throwable function to return MaybeResult instead.+ * Preserves MaybeResultError errors; wraps other errors as UNKNOWN.+ */+export async function catchToResult<T>(+ throwable: () => Promise<T>+): Promise<MaybeResult<string, T>> {+ try {+ return ok(await throwable());+ } catch (error) {+ if (error instanceof MaybeResultError) {+ return [error.errors, null];+ }+ return err(+ 'UNKNOWN',+ error instanceof Error ? error.message : String(error)+ );+ }+}+/*** A hybrid type that acts as both a single ResultError and an array containing that error.* Provides backward compatibility by allowing access to error properties directlydiff --git a/js/app/packages/macro-entity/src/queries/email.ts b/js/app/packages/macro-entity/src/queries/email.tsindex 872100956f..2532cab599 100644--- a/js/app/packages/macro-entity/src/queries/email.ts+++ b/js/app/packages/macro-entity/src/queries/email.ts@@ -1,17 +1,12 @@import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';import type { ApiPaginatedThreadCursor } from '@service-email/generated/schemas/apiPaginatedThreadCursor';import type { PreviewsInboxCursorParams } from '@service-email/generated/schemas/previewsInboxCursorParams';-import {- type InfiniteData,- partialMatchKey,- useInfiniteQuery,-} from '@tanstack/solid-query';+import { useInfiniteQuery } from '@tanstack/solid-query';import { SERVER_HOSTS } from 'core/constant/servers';import { platformFetch } from 'core/util/platformFetch';import { type Accessor, createMemo } from 'solid-js';import type { EmailEntity } from '../types/entity';import { createApiTokenQuery } from './auth';-import { queryClient } from './client';import { queryKeys } from './key';export type FetchPaginatedEmailsParams = PreviewsInboxCursorParams & {@@ -107,50 +102,3 @@ export function createEmailsInfiniteQuery(};});}--export const optimisticMarkEmailAsRead = (emailId: string) => {- queryClient.setQueriesData(- {- predicate(query) {- return partialMatchKey(- query.queryKey,- queryKeys.email({- infinite: true,- limit: 100,- view: 'inbox',- })- );- },- },- (- prev:- | InfiniteData<ApiPaginatedThreadCursor>- | ApiPaginatedThreadCursor- | undefined- ) => {- if (!prev) return;-- if ('pageParams' in prev) {- return {- ...prev,- pages: prev.pages.map((p) => ({- ...p,- items: p.items.map((item) => {- if (item.id !== emailId) return item;- return {- ...item,- isRead: true,- };- }),- })),- };- }-- return prev.items.map((item) => {- if (item.id !== emailId) return item;-- return { ...item, isRead: true };- });- }- );-};diff --git a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsxindex db05913919..5f72c93782 100644--- a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx+++ b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx@@ -1,7 +1,6 @@import type { Entity } from '@core/types';-import { emailClient } from '@service-email/client';+import { useMarkThreadAsSeenMutation } from '@queries/email/thread';import { onCleanup, onMount } from 'solid-js';-import { optimisticMarkEmailAsRead } from '../../macro-entity/src/queries/email';import {markNotificationForEntityIdAsRead,markNotificationsForEntityAsRead,@@ -111,15 +110,12 @@ export function EmailDebouncedReadMarker(props: {debounceTime?: number;threadId: string;}) {+ const markSeenMutation = useMarkThreadAsSeenMutation();+return (<DebouncedMarkerdebounceTime={props.debounceTime}- debouncedFn={() => {- optimisticMarkEmailAsRead(props.threadId);- emailClient.markThreadAsSeen({- thread_id: props.threadId,- });- }}+ debouncedFn={() => markSeenMutation.mutate({ threadId: props.threadId })}/>);}diff --git a/js/app/packages/queries/client.ts b/js/app/packages/queries/client.tsnew file mode 100644index 0000000000..5f1699bb03--- /dev/null+++ b/js/app/packages/queries/client.ts@@ -0,0 +1,16 @@+import { QueryClient } from '@tanstack/solid-query';++export const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 1000 * 60 * 5, // 5 minutes+ gcTime: 1000 * 60 * 10, // 10 minutes+ refetchOnWindowFocus: false,+ retry: 1,+ },+ },+});++export function useQueryClient() {+ return queryClient;+}diff --git a/js/app/packages/queries/email/keys.ts b/js/app/packages/queries/email/keys.tsnew file mode 100644index 0000000000..f309e65af6--- /dev/null+++ b/js/app/packages/queries/email/keys.ts@@ -0,0 +1,21 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';+import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';++export const emailKeys = createQueryKeys('email', {+ all: null,+ links: null,+ threads: null,+ thread: (threadId: string) => ({+ queryKey: [threadId],+ }),+ threadMessages: (threadId: string) => ({+ queryKey: ['messages', threadId],+ }),+ previews: (params: {+ view: PreviewViewStandardLabel;+ limit?: number;+ sort_method?: string;+ }) => ({+ queryKey: [{ infinite: true, ...params }],+ }),+});diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.tsnew file mode 100644index 0000000000..26f2840895--- /dev/null+++ b/js/app/packages/queries/email/thread.ts@@ -0,0 +1,242 @@+import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';+import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';+import { emailClient } from '@service-email/client';+import type {+ MessageToSend,+ SendMessageResponse,+ APIThread as Thread,+} from '@service-email/generated/schemas';+import {+ type InfiniteData,+ useInfiniteQuery,+ useMutation,+} from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';+import { emailKeys } from './keys';++const THREAD_STALE_TIME = 5 * 60 * 1000;++/**+ * Shared infinite query options for thread fetching.+ */+function threadQueryOptions(threadId: string) {+ return {+ queryKey: emailKeys.threadMessages(threadId).queryKey,+ queryFn: async ({ pageParam }: { pageParam: number }) => {+ const result = await throwOnErr(+ async () =>+ await emailClient.getThread({+ thread_id: threadId,+ offset: pageParam,+ limit: DEFAULT_THREAD_MESSAGES_LIMIT,+ })+ );++ return result.thread;+ },+ initialPageParam: 0,+ getNextPageParam: (lastPage: Thread, allPages: Thread[]) => {+ if (lastPage.messages.length < DEFAULT_THREAD_MESSAGES_LIMIT) {+ return undefined;+ }+ return allPages.reduce((sum, p) => sum + p.messages.length, 0);+ },+ staleTime: THREAD_STALE_TIME,+ };+}++/**+ * Flatten infinite query pages into a single thread with all messages.+ */+function flattenThreadPages(+ data: InfiniteData<Thread, number>+): Thread | undefined {+ if (!data?.pages[0]) return undefined;+ const firstPage = data.pages[0];+ return {+ ...firstPage,+ messages: data.pages.flatMap((p) => p.messages),+ };+}++/**+ * Imperatively fetch a thread (for use outside of components).+ * Returns cached data if fresh, otherwise fetches from server.+ *+ * TODO: Most of the time we have the updated_at timestamp of an email before we fetch it.+ * Would be nice to accept that as a parameter and only fetch if it's stale.+ */+export async function fetchAndCacheThread(+ threadId: string+): ReturnType<typeof emailClient.getThread> {+ let data: InfiniteData<Thread, number> | undefined;++ const result = await catchToResult(+ async () =>+ await queryClient.fetchInfiniteQuery(threadQueryOptions(threadId))+ );++ if (isErr(result)) {+ return result;+ }++ data = result[1];++ const thread = flattenThreadPages(data);+ return ok({ thread: thread! });+}++export type ThreadQueryData = {+ thread: Thread;+ hasMore: boolean;+};++/**+ * Query hook for fetching a thread with paginated messages.+ */+export function useThreadQuery(threadId: Accessor<string>) {+ return useInfiniteQuery(() => ({+ ...threadQueryOptions(threadId()),+ select: (data: InfiniteData<Thread, number>): ThreadQueryData => {+ const lastPage = data.pages.at(-1)!;+ return {+ thread: flattenThreadPages(data)!,+ hasMore: lastPage.messages.length === DEFAULT_THREAD_MESSAGES_LIMIT,+ };+ },+ }));+}++type MarkThreadAsSeenParams = { threadId: string };++/**+ * Mutation to mark a thread as seen.+ */+export function useMarkThreadAsSeenMutation(+ callbacks?: MutationCallbacks<void, Error, MarkThreadAsSeenParams>+) {+ return useMutation(() => ({+ mutationFn: async (params: MarkThreadAsSeenParams) =>+ void (await throwOnErr(+ async () =>+ await emailClient.markThreadAsSeen({+ thread_id: params.threadId,+ })+ )),+ ...withCallbacks<void, Error, MarkThreadAsSeenParams>(+ {+ onSuccess: (_, params) => {+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(params.threadId).queryKey,+ });+ },+ },+ callbacks+ ),+ }));+}++type ArchiveThreadParams = { threadId: string; archive: boolean };+type ArchiveThreadContext = {+ previousData: InfiniteData<Thread, number> | undefined;+};++/**+ * Mutation to archive or unarchive a thread.+ * Uses optimistic updates to immediately reflect the change in UI.+ */+export function useArchiveThreadMutation(+ callbacks?: MutationCallbacks<+ void,+ Error,+ ArchiveThreadParams,+ ArchiveThreadContext+ >+) {+ return useMutation(() => ({+ mutationFn: async (params: ArchiveThreadParams) =>+ void throwOnErr(+ async () =>+ await emailClient.flagArchived({+ id: params.threadId,+ value: params.archive,+ })+ ),+ ...withCallbacks<void, Error, ArchiveThreadParams, ArchiveThreadContext>(+ {+ onMutate: async (params) => {+ await queryClient.cancelQueries({+ queryKey: emailKeys.threadMessages(params.threadId).queryKey,+ });++ const previousData = queryClient.getQueryData<+ InfiniteData<Thread, number>+ >(emailKeys.threadMessages(params.threadId).queryKey);++ queryClient.setQueryData<InfiniteData<Thread, number>>(+ emailKeys.threadMessages(params.threadId).queryKey,+ (old) =>+ old && {+ ...old,+ pages: old.pages.map((page) => ({+ ...page,+ inbox_visible: !params.archive,+ })),+ }+ );++ return { previousData };+ },+ onError: (_err, params, context) => {+ if (context?.previousData) {+ queryClient.setQueryData(+ emailKeys.threadMessages(params.threadId).queryKey,+ context.previousData+ );+ }+ },+ onSettled: (_data, _error, params) => {+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(params.threadId).queryKey,+ });+ queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });+ },+ },+ callbacks+ ),+ }));+}++type SendMessageParams = { message: MessageToSend };++/**+ * Mutation to send an email message.+ */+export function useSendMessageMutation(+ callbacks?: MutationCallbacks<SendMessageResponse, Error, SendMessageParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: SendMessageParams) =>+ await throwOnErr(+ async () => await emailClient.sendMessage({ message: vars.message })+ ),+ ...withCallbacks<SendMessageResponse, Error, SendMessageParams>(+ {+ onSuccess: (_data, params) => {+ if (params.message.thread_db_id) {+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(params.message.thread_db_id)+ .queryKey,+ });+ }+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/queries/index.ts b/js/app/packages/queries/index.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/js/app/packages/queries/keys.ts b/js/app/packages/queries/keys.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/js/app/packages/queries/utils.ts b/js/app/packages/queries/utils.tsnew file mode 100644index 0000000000..e29acc3ecc--- /dev/null+++ b/js/app/packages/queries/utils.ts@@ -0,0 +1,67 @@+/**+ * Standard mutation callback types matching TanStack Query's mutation options.+ * Use this to ensure consistent callback signatures across mutations.+ */+export type MutationCallbacks<+ TData,+ TError = Error,+ TVariables = void,+ TContext = unknown,+> = {+ onMutate?: (variables: TVariables) => Promise<TContext> | TContext;+ onSuccess?: (+ data: TData,+ variables: TVariables,+ context: TContext+ ) => void | Promise<unknown>;+ onError?: (+ error: TError,+ variables: TVariables,+ context: TContext | undefined+ ) => void | Promise<unknown>;+ onSettled?: (+ data: TData | undefined,+ error: TError | null,+ variables: TVariables,+ context: TContext | undefined+ ) => void | Promise<unknown>;+};++/**+ * Helper to merge user-provided callbacks with default mutation behavior.+ * Ensures callbacks are called in order: defaults first, then user callbacks.+ *+ * For onMutate: default runs first, override can augment the context.+ * For onSuccess/onError/onSettled: default runs first, then override.+ */+export function withCallbacks<+ TData,+ TError = Error,+ TVariables = void,+ TContext = unknown,+>(+ defaults: MutationCallbacks<TData, TError, TVariables, TContext>,+ overrides?: MutationCallbacks<TData, TError, TVariables, TContext>+): MutationCallbacks<TData, TError, TVariables, TContext> {+ if (!overrides) return defaults;++ return {+ onMutate: async (variables) => {+ const defaultContext = await defaults.onMutate?.(variables);+ const overrideContext = await overrides.onMutate?.(variables);+ return (overrideContext ?? defaultContext) as TContext;+ },+ onSuccess: async (data, variables, context) => {+ await defaults.onSuccess?.(data, variables, context);+ await overrides.onSuccess?.(data, variables, context);+ },+ onError: async (error, variables, context) => {+ await defaults.onError?.(error, variables, context);+ await overrides.onError?.(error, variables, context);+ },+ onSettled: async (data, error, variables, context) => {+ await defaults.onSettled?.(data, error, variables, context);+ await overrides.onSettled?.(data, error, variables, context);+ },+ };+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts b/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.tsindex 26062c724d..4c1e357334 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts@@ -4,6 +4,7 @@* email_service* OpenAPI spec version: 0.1.0*/+import type { AccessLevel } from './accessLevel';import type { APIThreadDbId } from './aPIThreadDbId';import type { APIThreadLatestInboundMessageTs } from './aPIThreadLatestInboundMessageTs';import type { APIThreadLatestNonSpamMessageTs } from './aPIThreadLatestNonSpamMessageTs';@@ -15,6 +16,7 @@ import type { APIThreadProviderId } from './aPIThreadProviderId';* Thread object exposed to the FE in Get Threads Call*/export interface APIThread {+ access_level: AccessLevel;created_at: string;db_id?: APIThreadDbId;inbox_visible: boolean;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.tsindex 416efc2556..41ddad1e28 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts@@ -4,14 +4,12 @@* email_service* OpenAPI spec version: 0.1.0*/-import type { AccessLevel } from './accessLevel';import type { APIThread } from './aPIThread';/*** The response returned from the get thread endpoint*/export interface GetThreadResponse {- access_level: AccessLevel;/** the thread, with messages inside */thread: APIThread;}diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 37da1ce0c8..0eb20b0533 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -1398,11 +1398,13 @@"link_id","inbox_visible","is_read",+ "access_level","created_at","updated_at","messages"],"properties": {+ "access_level": { "$ref": "#/components/schemas/AccessLevel" },"created_at": { "type": "string", "format": "date-time" },"db_id": { "type": ["string", "null"], "format": "uuid" },"inbox_visible": { "type": "boolean" },@@ -1799,9 +1801,8 @@"GetThreadResponse": {"type": "object","description": "The response returned from the get thread endpoint",- "required": ["thread", "access_level"],+ "required": ["thread"],"properties": {- "access_level": { "$ref": "#/components/schemas/AccessLevel" },"thread": {"$ref": "#/components/schemas/APIThread","description": "the thread, with messages inside"diff --git a/js/app/tsconfig.json b/js/app/tsconfig.jsonindex 7252c72c74..644fd7bfef 100644--- a/js/app/tsconfig.json+++ b/js/app/tsconfig.json@@ -198,6 +198,9 @@],"@app/*": ["./packages/app/*"+ ],+ "@queries/*": [+ "./packages/queries/*"]},"rootDir": ".",