Hold a message in the server's queue until the time you asked for
Scheduled send, which the README listed as needing server support that Stalwart has had all along. The delay cannot be asked for directly -- RFC 8621 makes `sendAt` read-only and server-derived -- so it goes on the envelope as an RFC 4865 `HOLDUNTIL` parameter, and the server reports back the time it settled on. Stalwart advertises this in the *account* capability, not the session-level one (which is empty): `maxDelayedSend` of thirty days and `FUTURERELEASE` among its `submissionExtensions`. The composer offers scheduling only when both are there, and never offers a time the server would refuse. A held message goes to a Scheduled folder rather than Sent, because `onSuccessUpdateEmail` would otherwise file it as sent the moment the submission is created, and it has not been sent. Nothing moves it out when the hold expires, so the folder is reconciled on the way in: released messages to Sent, cancelled ones back to Drafts. Cancelling uses a separate `Email/set` rather than `onSuccessUpdateEmail`, whose key Stalwart reads as an Email id and not, as the RFC says, a submission id. The mock grows the whole lifecycle, and learns to resolve creation references while it is there -- it had been quietly declining to create any submission at all, since sending names its message as `#m`. Because Stalwart's own `futureRelease` setting defaults to off and then drops the hold in silence, `npm run dev:mock:no-future-release` reproduces that. Verified end to end against the mock; not yet against the live server.
This commit is contained in:
@@ -18,7 +18,7 @@ function draft(over: Partial<Draft> = {}): Draft {
|
||||
requestReceipt: false, priority: "normal",
|
||||
showCc: false, showBcc: false, showReplyTo: false,
|
||||
minimized: false, maximized: false, dirty: false, savedAt: null,
|
||||
saving: false, sending: false, error: null, signatureHtml: "", replyMode: null,
|
||||
saving: false, sending: false, error: null, signatureHtml: "", replyMode: null, sendAt: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSubmission } from "@/store/compose";
|
||||
|
||||
/**
|
||||
* JMAP has no writable "send this later" property: `sendAt` is server-derived,
|
||||
* and the delay is asked for with an RFC 4865 FUTURERELEASE parameter on the
|
||||
* envelope. Getting that wrong sends the message immediately, which is not the
|
||||
* kind of mistake a user can undo.
|
||||
*/
|
||||
const base = {
|
||||
identityId: "i1",
|
||||
fromEmail: "[email protected]",
|
||||
emailRef: "#m",
|
||||
rcpts: [{ email: "[email protected]" }],
|
||||
sentId: "sent",
|
||||
draftsId: "drafts",
|
||||
scheduledId: "sched",
|
||||
};
|
||||
|
||||
describe("buildSubmission", () => {
|
||||
it("sends immediately when nothing is scheduled", () => {
|
||||
const { create, onSuccessUpdateEmail } = buildSubmission({ ...base, sendAt: null });
|
||||
const envelope = create.envelope as { mailFrom: Record<string, unknown> };
|
||||
expect(envelope.mailFrom).toEqual({ email: "[email protected]" });
|
||||
expect(envelope.mailFrom).not.toHaveProperty("parameters");
|
||||
expect(onSuccessUpdateEmail["mailboxIds/sent"]).toBe(true);
|
||||
expect(onSuccessUpdateEmail["mailboxIds/drafts"]).toBeNull();
|
||||
});
|
||||
|
||||
it("asks for the hold with HOLDUNTIL, not by setting sendAt", () => {
|
||||
const at = new Date("2026-11-20T05:00:00Z").getTime();
|
||||
const { create } = buildSubmission({ ...base, sendAt: at });
|
||||
const envelope = create.envelope as { mailFrom: { parameters?: Record<string, string> } };
|
||||
expect(envelope.mailFrom.parameters).toEqual({ HOLDUNTIL: "2026-11-20T05:00:00Z" });
|
||||
expect(create).not.toHaveProperty("sendAt");
|
||||
expect(create).not.toHaveProperty("undoStatus");
|
||||
});
|
||||
|
||||
it("files a held message under Scheduled, and keeps it out of Sent", () => {
|
||||
const { onSuccessUpdateEmail } = buildSubmission({ ...base, sendAt: Date.now() + 86_400_000 });
|
||||
expect(onSuccessUpdateEmail["mailboxIds/sched"]).toBe(true);
|
||||
// Sent would be a lie for as long as the hold lasts.
|
||||
expect(onSuccessUpdateEmail["mailboxIds/sent"]).toBeNull();
|
||||
expect(onSuccessUpdateEmail["mailboxIds/drafts"]).toBeNull();
|
||||
expect(onSuccessUpdateEmail["keywords/$draft"]).toBeNull();
|
||||
});
|
||||
|
||||
it("still sends when the server has no Scheduled folder to file it in", () => {
|
||||
const { create, onSuccessUpdateEmail } = buildSubmission({ ...base, scheduledId: null, sendAt: Date.now() + 86_400_000 });
|
||||
const envelope = create.envelope as { mailFrom: { parameters?: Record<string, string> } };
|
||||
expect(envelope.mailFrom.parameters).toHaveProperty("HOLDUNTIL");
|
||||
expect(onSuccessUpdateEmail).not.toHaveProperty("mailboxIds/sched");
|
||||
});
|
||||
|
||||
it("carries the identity, the message reference and every recipient", () => {
|
||||
const { create } = buildSubmission({
|
||||
...base,
|
||||
rcpts: [{ email: "[email protected]" }, { email: "[email protected]" }],
|
||||
sendAt: null,
|
||||
});
|
||||
expect(create.identityId).toBe("i1");
|
||||
expect(create.emailId).toBe("#m");
|
||||
expect((create.envelope as { rcptTo: unknown[] }).rcptTo).toEqual([{ email: "[email protected]" }, { email: "[email protected]" }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { CAP, client } from "@/jmap/client";
|
||||
import { useMail } from "@/store/mail";
|
||||
import { useScheduled } from "@/store/scheduled";
|
||||
import { useToasts } from "@/ui/toast";
|
||||
import type { JmapSession } from "@/jmap/types";
|
||||
|
||||
/**
|
||||
* Nothing on the server moves a message out of Scheduled when its hold
|
||||
* expires: Stalwart sends it and updates the submission, but the message stays
|
||||
* in the folder ihasmail filed it in. Left alone, Scheduled slowly fills with
|
||||
* mail that was sent days ago. Reconciling settles it on the way in.
|
||||
*/
|
||||
|
||||
const SCHED = "mbSched";
|
||||
const SENT = "mbSent";
|
||||
const DRAFTS = "mbDrafts";
|
||||
const FUTURE = "2099-01-01T00:00:00Z";
|
||||
|
||||
interface Sub {
|
||||
id: string;
|
||||
emailId: string;
|
||||
sendAt: string;
|
||||
undoStatus: "pending" | "final" | "canceled";
|
||||
}
|
||||
|
||||
/** A server holding `inFolder` messages in Scheduled, with these submissions. */
|
||||
function server(inFolder: string[], subs: Sub[]) {
|
||||
const updates: Record<string, Record<string, unknown>>[] = [];
|
||||
const submissionUpdates: Record<string, Record<string, unknown>>[] = [];
|
||||
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const body = JSON.parse(init.body as string) as { methodCalls: [string, Record<string, unknown>, string][] };
|
||||
let queried: string[] = [];
|
||||
const methodResponses = body.methodCalls.map(([name, args, id]) => {
|
||||
if (name === "Email/query") {
|
||||
return [name, { accountId: "a1", queryState: "q", canCalculateChanges: false, position: 0, ids: inFolder, total: inFolder.length }, id];
|
||||
}
|
||||
if (name === "EmailSubmission/query") {
|
||||
const f = (args.filter ?? {}) as { undoStatus?: string; emailIds?: string[] };
|
||||
queried = subs
|
||||
.filter((s) => (!f.undoStatus || s.undoStatus === f.undoStatus) && (!f.emailIds || f.emailIds.includes(s.emailId)))
|
||||
.map((s) => s.id);
|
||||
return [name, { accountId: "a1", queryState: "q", canCalculateChanges: false, position: 0, ids: queried, total: queried.length }, id];
|
||||
}
|
||||
if (name === "EmailSubmission/get") {
|
||||
const ids = (args.ids as string[] | null) ?? queried;
|
||||
return [name, { accountId: "a1", state: "1", list: subs.filter((s) => ids.includes(s.id)), notFound: [] }, id];
|
||||
}
|
||||
if (name === "EmailSubmission/set") {
|
||||
submissionUpdates.push(args.update as Record<string, Record<string, unknown>>);
|
||||
return [name, { accountId: "a1", oldState: "1", newState: "2", updated: Object.fromEntries(Object.keys((args.update ?? {}) as object).map((k) => [k, null])) }, id];
|
||||
}
|
||||
if (name === "Email/set" && args.update) {
|
||||
updates.push(args.update as Record<string, Record<string, unknown>>);
|
||||
return [name, { accountId: "a1", oldState: "1", newState: "2", updated: {} }, id];
|
||||
}
|
||||
return [name, { accountId: "a1", state: "1", list: [], notFound: [], ids: [], total: 0, queryState: "q", position: 0, canCalculateChanges: false }, id];
|
||||
});
|
||||
return { ok: true, status: 200, json: async () => ({ methodResponses, sessionState: "1" }) } as Response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
return { updates, submissionUpdates };
|
||||
}
|
||||
|
||||
/** The mailbox a patch files a message into, and the one it takes it out of. */
|
||||
function moved(patch: Record<string, unknown>) {
|
||||
const into = Object.keys(patch).find((k) => k.startsWith("mailboxIds/") && patch[k] === true);
|
||||
const outOf = Object.keys(patch).find((k) => k.startsWith("mailboxIds/") && patch[k] === null);
|
||||
return { into: into?.slice("mailboxIds/".length), outOf: outOf?.slice("mailboxIds/".length) };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
client.session = {
|
||||
capabilities: { [CAP.core]: { maxObjectsInGet: 500, maxObjectsInSet: 500 }, [CAP.mail]: {}, [CAP.submission]: {} },
|
||||
accounts: { a1: { accountCapabilities: { [CAP.submission]: { maxDelayedSend: 2592000, submissionExtensions: { FUTURERELEASE: [] } } } } },
|
||||
primaryAccounts: {},
|
||||
state: "s1",
|
||||
} as unknown as JmapSession;
|
||||
useMail.setState({
|
||||
accountId: "a1",
|
||||
mailboxes: {
|
||||
[SCHED]: { id: SCHED, role: null, parentId: null, name: "Scheduled" },
|
||||
[SENT]: { id: SENT, role: "sent", parentId: null, name: "Sent" },
|
||||
[DRAFTS]: { id: DRAFTS, role: "drafts", parentId: null, name: "Drafts" },
|
||||
} as never,
|
||||
list: null,
|
||||
emails: {},
|
||||
});
|
||||
useScheduled.setState({ pending: {}, loaded: false });
|
||||
useToasts.setState({ toasts: [] });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("reconcile", () => {
|
||||
it("leaves a message alone while its hold is still ahead", async () => {
|
||||
const s = server(["e1"], [{ id: "s1", emailId: "e1", sendAt: FUTURE, undoStatus: "pending" }]);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toEqual([]);
|
||||
expect(useScheduled.getState().pending.e1?.id).toBe("s1");
|
||||
});
|
||||
|
||||
it("moves a released message to Sent, where it actually is", async () => {
|
||||
const s = server(["e1"], [{ id: "s1", emailId: "e1", sendAt: "2026-01-01T00:00:00Z", undoStatus: "final" }]);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toHaveLength(1);
|
||||
expect(moved(s.updates[0]!.e1!)).toEqual({ into: SENT, outOf: SCHED });
|
||||
expect(useScheduled.getState().pending).toEqual({});
|
||||
});
|
||||
|
||||
it("returns a message cancelled elsewhere to Drafts, as a draft again", async () => {
|
||||
const s = server(["e1"], [{ id: "s1", emailId: "e1", sendAt: FUTURE, undoStatus: "canceled" }]);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(moved(s.updates[0]!.e1!)).toEqual({ into: DRAFTS, outOf: SCHED });
|
||||
expect(s.updates[0]!.e1!["keywords/$draft"]).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a message with no submission at all as sent, not as a draft", async () => {
|
||||
const s = server(["e1"], []);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(moved(s.updates[0]!.e1!).into).toBe(SENT);
|
||||
});
|
||||
|
||||
it("settles a mixed folder in one call, keeping only what is still waiting", async () => {
|
||||
const s = server(
|
||||
["held", "gone", "dropped"],
|
||||
[
|
||||
{ id: "s1", emailId: "held", sendAt: FUTURE, undoStatus: "pending" },
|
||||
{ id: "s2", emailId: "gone", sendAt: "2026-01-01T00:00:00Z", undoStatus: "final" },
|
||||
{ id: "s3", emailId: "dropped", sendAt: FUTURE, undoStatus: "canceled" },
|
||||
],
|
||||
);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toHaveLength(1);
|
||||
const patch = s.updates[0]!;
|
||||
expect(Object.keys(patch).sort()).toEqual(["dropped", "gone"]);
|
||||
expect(moved(patch.gone!).into).toBe(SENT);
|
||||
expect(moved(patch.dropped!).into).toBe(DRAFTS);
|
||||
expect(Object.keys(useScheduled.getState().pending)).toEqual(["held"]);
|
||||
});
|
||||
|
||||
it("believes the newest submission when a message was rescheduled", async () => {
|
||||
const s = server(
|
||||
["e1"],
|
||||
[
|
||||
{ id: "old", emailId: "e1", sendAt: "2026-01-01T00:00:00Z", undoStatus: "canceled" },
|
||||
{ id: "new", emailId: "e1", sendAt: FUTURE, undoStatus: "pending" },
|
||||
],
|
||||
);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toEqual([]);
|
||||
expect(useScheduled.getState().pending.e1?.id).toBe("new");
|
||||
});
|
||||
|
||||
it("keeps a message whose live hold was moved earlier than the one it replaced", async () => {
|
||||
// Rescheduling to a sooner time leaves the cancelled submission holding the
|
||||
// later sendAt. Going by timestamp alone would file a message back to
|
||||
// Drafts while the queue still has it.
|
||||
const s = server(
|
||||
["e1"],
|
||||
[
|
||||
{ id: "old", emailId: "e1", sendAt: "2099-06-01T00:00:00Z", undoStatus: "canceled" },
|
||||
{ id: "new", emailId: "e1", sendAt: FUTURE, undoStatus: "pending" },
|
||||
],
|
||||
);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toEqual([]);
|
||||
expect(useScheduled.getState().pending.e1?.id).toBe("new");
|
||||
});
|
||||
|
||||
it("does nothing at all when there is no Scheduled folder", async () => {
|
||||
useMail.setState({ mailboxes: { [SENT]: { id: SENT, role: "sent", parentId: null, name: "Sent" } } as never });
|
||||
const s = server(["e1"], []);
|
||||
await useScheduled.getState().reconcile();
|
||||
expect(s.updates).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancel", () => {
|
||||
it("cancels the submission and puts the message back in Drafts", async () => {
|
||||
const s = server(["e1"], [{ id: "s1", emailId: "e1", sendAt: FUTURE, undoStatus: "pending" }]);
|
||||
await useScheduled.getState().load();
|
||||
expect(useScheduled.getState().pending.e1?.id).toBe("s1");
|
||||
await useScheduled.getState().cancel("e1");
|
||||
expect(s.submissionUpdates[0]).toEqual({ s1: { undoStatus: "canceled" } });
|
||||
expect(moved(s.updates[0]!.e1!)).toEqual({ into: DRAFTS, outOf: SCHED });
|
||||
expect(useScheduled.getState().pending).toEqual({});
|
||||
});
|
||||
|
||||
it("refuses to cancel a message that is no longer waiting", async () => {
|
||||
server([], []);
|
||||
await expect(useScheduled.getState().cancel("e1")).rejects.toThrow(/no longer waiting/);
|
||||
});
|
||||
});
|
||||
+72
-13
@@ -7,6 +7,8 @@ import { escapeHtml, htmlToText, quoteText, replySubject, textToHtml } from "@/l
|
||||
import { sanitizeEmailHtml, sanitizeEditorHtml } from "@/lib/html";
|
||||
import { toast } from "@/ui/toast";
|
||||
import { useMail, FULL_PROPS, BODY_PROPS } from "./mail";
|
||||
import { ensureScheduledMailbox, useScheduled } from "./scheduled";
|
||||
import { formatScheduleTime, holdUntil } from "@/lib/schedule";
|
||||
import { settings } from "./settings";
|
||||
|
||||
export interface ComposeAttachment {
|
||||
@@ -59,6 +61,8 @@ export interface Draft {
|
||||
signatureHtml: string;
|
||||
replyMode: "reply" | "replyAll" | "forward" | null;
|
||||
mailboxIdOnSend?: Id | null;
|
||||
/** When set, hand the message to the server held until this instant. */
|
||||
sendAt: number | null;
|
||||
}
|
||||
|
||||
interface ComposeState {
|
||||
@@ -116,6 +120,7 @@ function blankDraft(init: Partial<Draft> = {}): Draft {
|
||||
error: null,
|
||||
signatureHtml: "",
|
||||
replyMode: null,
|
||||
sendAt: null,
|
||||
...init,
|
||||
};
|
||||
}
|
||||
@@ -378,6 +383,8 @@ export const useCompose = create<ComposeState>((set, get) => ({
|
||||
const d = get().drafts.find((x) => x.key === key);
|
||||
if (!d) return;
|
||||
const delay = settings().undoSendSeconds;
|
||||
// A schedule the user left sitting until it passed is just a send now.
|
||||
const scheduling = d.sendAt !== null && d.sendAt > Date.now();
|
||||
// Hide the composer immediately; actually send after the undo window.
|
||||
const t = autosaveTimers.get(key);
|
||||
if (t) window.clearTimeout(t);
|
||||
@@ -390,7 +397,7 @@ export const useCompose = create<ComposeState>((set, get) => ({
|
||||
});
|
||||
try {
|
||||
await sendInternal(d, get);
|
||||
toast.success("Message sent");
|
||||
toast.success(scheduling ? `Send scheduled for ${formatScheduleTime(new Date(d.sendAt!))}` : "Message sent");
|
||||
} catch (err) {
|
||||
toast.error(`Send failed: ${(err as Error).message}`, {
|
||||
action: { label: "Open draft", onClick: () => set((s) => ({ drafts: [...s.drafts, { ...d, sending: false, error: (err as Error).message }], activeKey: d.key })) },
|
||||
@@ -398,7 +405,10 @@ export const useCompose = create<ComposeState>((set, get) => ({
|
||||
});
|
||||
}
|
||||
};
|
||||
if (delay <= 0) {
|
||||
// A scheduled send is already delayed, and cancelling it is a server-side
|
||||
// operation from the Scheduled folder -- holding it locally first would
|
||||
// only add a second, different kind of undo.
|
||||
if (delay <= 0 || scheduling) {
|
||||
await doSend();
|
||||
return;
|
||||
}
|
||||
@@ -481,7 +491,7 @@ function scheduleAutosave(key: string, get: () => ComposeState) {
|
||||
}
|
||||
|
||||
/** Build the JMAP Email creation object from a draft. */
|
||||
export async function buildEmailObject(d: Draft, opts: { forSend: boolean }): Promise<Record<string, unknown>> {
|
||||
export async function buildEmailObject(d: Draft, opts: { forSend: boolean; mailboxId?: Id | null }): Promise<Record<string, unknown>> {
|
||||
const mail = useMail.getState();
|
||||
const accountId = mail.accountId!;
|
||||
const ident = mail.identities.find((i) => i.id === d.identityId) ?? mail.identities[0];
|
||||
@@ -591,7 +601,7 @@ export async function buildEmailObject(d: Draft, opts: { forSend: boolean }): Pr
|
||||
obj.mailboxIds = draftsId ? { [draftsId]: true } : { [mail.roleId("inbox")!]: true };
|
||||
obj.keywords = { $draft: true, $seen: true };
|
||||
} else {
|
||||
const sentId = mail.roleId("sent") ?? mail.roleId("inbox");
|
||||
const sentId = opts.mailboxId ?? mail.roleId("sent") ?? mail.roleId("inbox");
|
||||
obj.mailboxIds = { [sentId!]: true };
|
||||
obj.keywords = { $seen: true };
|
||||
}
|
||||
@@ -628,29 +638,67 @@ async function saveDraftInternal(d: Draft, get: () => ComposeState, set: (fn: (s
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `EmailSubmission/set` create for a message, and the `Email` patch that
|
||||
* files it once the server accepts it.
|
||||
*
|
||||
* A scheduled send differs in two places: the envelope carries a
|
||||
* `HOLDUNTIL` parameter (RFC 4865 FUTURERELEASE, which is how JMAP asks for a
|
||||
* delay -- `sendAt` itself is read-only and server-derived), and the message is
|
||||
* filed under Scheduled rather than Sent, because it has not been sent yet.
|
||||
*/
|
||||
export function buildSubmission(opts: {
|
||||
identityId: Id;
|
||||
fromEmail: string;
|
||||
emailRef: string;
|
||||
rcpts: { email: string }[];
|
||||
sentId: Id | null;
|
||||
draftsId: Id | null;
|
||||
scheduledId: Id | null;
|
||||
sendAt: number | null;
|
||||
}): { create: Record<string, unknown>; onSuccessUpdateEmail: Record<string, unknown> } {
|
||||
const scheduled = opts.sendAt !== null;
|
||||
const mailFrom: Record<string, unknown> = { email: opts.fromEmail };
|
||||
if (scheduled) mailFrom.parameters = { HOLDUNTIL: holdUntil(new Date(opts.sendAt!)) };
|
||||
const filedIn = scheduled ? opts.scheduledId : opts.sentId;
|
||||
const onSuccess: Record<string, unknown> = { "keywords/$draft": null, "keywords/$seen": true };
|
||||
if (filedIn) onSuccess[`mailboxIds/${filedIn}`] = true;
|
||||
if (opts.draftsId && opts.draftsId !== filedIn) onSuccess[`mailboxIds/${opts.draftsId}`] = null;
|
||||
if (scheduled && opts.sentId && opts.sentId !== filedIn) onSuccess[`mailboxIds/${opts.sentId}`] = null;
|
||||
return {
|
||||
create: { identityId: opts.identityId, emailId: opts.emailRef, envelope: { mailFrom, rcptTo: opts.rcpts } },
|
||||
onSuccessUpdateEmail: onSuccess,
|
||||
};
|
||||
}
|
||||
|
||||
async function sendInternal(d: Draft, _get: () => ComposeState): Promise<void> {
|
||||
const mail = useMail.getState();
|
||||
const accountId = mail.accountId!;
|
||||
const ident = mail.identities.find((i) => i.id === d.identityId) ?? mail.identities[0];
|
||||
if (!ident) throw new Error("No sending identity available");
|
||||
if (d.attachments.some((a) => !a.blobId && !a.error)) throw new Error("Attachments are still uploading");
|
||||
const email = await buildEmailObject(d, { forSend: true });
|
||||
const scheduled = d.sendAt !== null && d.sendAt > Date.now();
|
||||
const scheduledId = scheduled ? await ensureScheduledMailbox() : null;
|
||||
const email = await buildEmailObject(d, { forSend: true, mailboxId: scheduledId });
|
||||
const sentId = mail.roleId("sent");
|
||||
const draftsId = mail.roleId("drafts");
|
||||
const onSuccess: Record<string, unknown> = { "keywords/$draft": null, "keywords/$seen": true };
|
||||
if (sentId) onSuccess[`mailboxIds/${sentId}`] = true;
|
||||
if (draftsId) onSuccess[`mailboxIds/${draftsId}`] = null;
|
||||
const rcpts = uniqueAddresses([...d.to, ...d.cc, ...d.bcc]).map((a) => ({ email: a.email }));
|
||||
if (!rcpts.length) throw new Error("No recipients");
|
||||
const sub = buildSubmission({
|
||||
identityId: ident.id,
|
||||
fromEmail: ident.email,
|
||||
emailRef: "#m",
|
||||
rcpts,
|
||||
sentId,
|
||||
draftsId,
|
||||
scheduledId,
|
||||
sendAt: scheduled ? d.sendAt : null,
|
||||
});
|
||||
const calls: Array<[string, Record<string, unknown>, string]> = [
|
||||
["Email/set", { accountId, create: { m: email }, ...(d.draftId ? { destroy: [d.draftId] } : {}) }, "e"],
|
||||
[
|
||||
"EmailSubmission/set",
|
||||
{
|
||||
accountId,
|
||||
create: { s: { identityId: ident.id, emailId: "#m", envelope: { mailFrom: { email: ident.email }, rcptTo: rcpts } } },
|
||||
onSuccessUpdateEmail: { "#s": onSuccess },
|
||||
},
|
||||
{ accountId, create: { s: sub.create }, onSuccessUpdateEmail: { "#s": sub.onSuccessUpdateEmail } },
|
||||
"s",
|
||||
],
|
||||
];
|
||||
@@ -676,6 +724,17 @@ async function sendInternal(d: Draft, _get: () => ComposeState): Promise<void> {
|
||||
return cur ? { emails: { ...st.emails, [d.relatedEmailId!]: { ...cur, keywords: { ...cur.keywords, [d.relatedKeyword!]: true } } } } : {};
|
||||
});
|
||||
}
|
||||
if (scheduled) {
|
||||
// The server decides the release time, so take its word for it rather than
|
||||
// ours -- and say so if the two disagree, which means the hold did not land
|
||||
// the way we asked.
|
||||
const created = (s.created?.s ?? {}) as { id?: Id; sendAt?: string; undoStatus?: string };
|
||||
const settled = created.sendAt ? Date.parse(created.sendAt) : NaN;
|
||||
if (!Number.isNaN(settled) && Math.abs(settled - d.sendAt!) > 60_000) {
|
||||
toast.error(`The server scheduled this for ${formatScheduleTime(new Date(settled))}, not the time requested.`);
|
||||
}
|
||||
await useScheduled.getState().load();
|
||||
}
|
||||
void mail.loadMailboxes();
|
||||
void mail.refreshList();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { create } from "zustand";
|
||||
import { client, ref, setErrorMessage } from "@/jmap/client";
|
||||
import type { EmailSubmission, GetResponse, Id, Mailbox, QueryResponse, SetResponse } from "@/jmap/types";
|
||||
import { toast } from "@/ui/toast";
|
||||
import { useMail } from "./mail";
|
||||
import { canScheduleSend, maxDelayMs, SUBMISSION_CAP, type SubmissionCapability } from "@/lib/schedule";
|
||||
|
||||
/**
|
||||
* A held message lives in a folder of its own, the way Gmail's does, because
|
||||
* the alternatives are both wrong: leaving it in Drafts invites the user to
|
||||
* edit a message the queue has already frozen, and `onSuccessUpdateEmail`
|
||||
* files it in Sent the instant the submission is created -- which for a
|
||||
* scheduled send is a lie for however long the hold lasts.
|
||||
*
|
||||
* JMAP has no role for this (the IANA attribute registry has no `\Scheduled`),
|
||||
* so it is an ordinary folder found by name.
|
||||
*/
|
||||
export const SCHEDULED_MAILBOX = "Scheduled";
|
||||
|
||||
/** What this account's server says about holding a message before sending it. */
|
||||
export function submissionCapability(): SubmissionCapability | undefined {
|
||||
const accountId = useMail.getState().accountId;
|
||||
if (!accountId) return undefined;
|
||||
return client.accountCapability<SubmissionCapability>(accountId, SUBMISSION_CAP);
|
||||
}
|
||||
|
||||
/** Whether to offer scheduled send at all. */
|
||||
export function scheduleSupported(): boolean {
|
||||
return canScheduleSend(submissionCapability());
|
||||
}
|
||||
|
||||
/** How far ahead this server will hold a message, in milliseconds. */
|
||||
export function scheduleWindowMs(): number {
|
||||
return maxDelayMs(submissionCapability());
|
||||
}
|
||||
|
||||
/** Whether this folder is the one held messages wait in. */
|
||||
export function isScheduledMailbox(m: Pick<Mailbox, "role" | "parentId" | "name">): boolean {
|
||||
return !m.role && !m.parentId && m.name.toLowerCase() === SCHEDULED_MAILBOX.toLowerCase();
|
||||
}
|
||||
|
||||
/** The Scheduled folder in a given set of mailboxes, if one exists yet. */
|
||||
export function scheduledMailboxIdFrom(mailboxes: Record<Id, Mailbox>): Id | null {
|
||||
return Object.values(mailboxes).find(isScheduledMailbox)?.id ?? null;
|
||||
}
|
||||
|
||||
/** The Scheduled folder, if one exists yet. */
|
||||
export function scheduledMailboxId(): Id | null {
|
||||
return scheduledMailboxIdFrom(useMail.getState().mailboxes);
|
||||
}
|
||||
|
||||
/** The Scheduled folder, creating it the first time something is scheduled. */
|
||||
export async function ensureScheduledMailbox(): Promise<Id> {
|
||||
const existing = scheduledMailboxId();
|
||||
if (existing) return existing;
|
||||
const accountId = useMail.getState().accountId!;
|
||||
const res = await client.call<SetResponse<Mailbox>>("Mailbox/set", {
|
||||
accountId,
|
||||
create: { sched: { name: SCHEDULED_MAILBOX, parentId: null, isSubscribed: true } },
|
||||
});
|
||||
const err = res.notCreated?.sched;
|
||||
// A racing tab (or another client) may have created it between the two calls.
|
||||
if (err) {
|
||||
await useMail.getState().loadMailboxes();
|
||||
const again = scheduledMailboxId();
|
||||
if (again) return again;
|
||||
throw new Error(setErrorMessage(err));
|
||||
}
|
||||
const id = res.created!.sched!.id;
|
||||
await useMail.getState().loadMailboxes();
|
||||
return id;
|
||||
}
|
||||
|
||||
export interface PendingSend {
|
||||
id: Id;
|
||||
emailId: Id;
|
||||
/** Epoch milliseconds, as the server settled on it. */
|
||||
sendAt: number;
|
||||
undoStatus: EmailSubmission["undoStatus"];
|
||||
}
|
||||
|
||||
interface ScheduledState {
|
||||
/** Pending submissions, keyed by the message they will send. */
|
||||
pending: Record<Id, PendingSend>;
|
||||
loaded: boolean;
|
||||
load(): Promise<void>;
|
||||
cancel(emailId: Id): Promise<void>;
|
||||
reconcile(): Promise<void>;
|
||||
}
|
||||
|
||||
const SUB_PROPS = ["id", "emailId", "sendAt", "undoStatus"];
|
||||
|
||||
function toPending(s: EmailSubmission): PendingSend {
|
||||
return { id: s.id, emailId: s.emailId, sendAt: Date.parse(s.sendAt), undoStatus: s.undoStatus };
|
||||
}
|
||||
|
||||
/** Every submission still sitting in the server's queue. */
|
||||
async function loadPending(accountId: Id): Promise<PendingSend[]> {
|
||||
const res = await client.chain([
|
||||
["EmailSubmission/query", { accountId, filter: { undoStatus: "pending" } }, "q"],
|
||||
["EmailSubmission/get", { accountId, "#ids": ref("q", "EmailSubmission/query", "/ids"), properties: SUB_PROPS }, "g"],
|
||||
]);
|
||||
const got = res.get("g")?.[0] as unknown as GetResponse<EmailSubmission> | undefined;
|
||||
return (got?.list ?? []).map(toPending);
|
||||
}
|
||||
|
||||
/** The submissions belonging to a specific set of messages, whatever their status. */
|
||||
async function loadFor(accountId: Id, emailIds: Id[]): Promise<PendingSend[]> {
|
||||
if (!emailIds.length) return [];
|
||||
const res = await client.chain([
|
||||
["EmailSubmission/query", { accountId, filter: { emailIds } }, "q"],
|
||||
["EmailSubmission/get", { accountId, "#ids": ref("q", "EmailSubmission/query", "/ids"), properties: SUB_PROPS }, "g"],
|
||||
]);
|
||||
const got = res.get("g")?.[0] as unknown as GetResponse<EmailSubmission> | undefined;
|
||||
return (got?.list ?? []).map(toPending);
|
||||
}
|
||||
|
||||
export const useScheduled = create<ScheduledState>((set, get) => ({
|
||||
pending: {},
|
||||
loaded: false,
|
||||
|
||||
async load() {
|
||||
const accountId = useMail.getState().accountId;
|
||||
if (!accountId) return;
|
||||
try {
|
||||
const list = await loadPending(accountId);
|
||||
const pending: Record<Id, PendingSend> = {};
|
||||
for (const s of list) pending[s.emailId] = s;
|
||||
set({ pending, loaded: true });
|
||||
} catch {
|
||||
// A server without the submission capability simply has nothing to show.
|
||||
set({ loaded: true });
|
||||
}
|
||||
},
|
||||
|
||||
async cancel(emailId) {
|
||||
const accountId = useMail.getState().accountId!;
|
||||
const sub = get().pending[emailId];
|
||||
if (!sub) throw new Error("This message is no longer waiting to be sent");
|
||||
const draftsId = useMail.getState().roleId("drafts");
|
||||
const scheduledId = scheduledMailboxId();
|
||||
// Not `onSuccessUpdateEmail`: RFC 8621 keys it by submission id, but
|
||||
// Stalwart takes a plain key as an Email id and would patch the wrong
|
||||
// object. Moving the message back is a separate call in the same request.
|
||||
const res = await client.chain([
|
||||
["EmailSubmission/set", { accountId, update: { [sub.id]: { undoStatus: "canceled" } } }, "s"],
|
||||
[
|
||||
"Email/set",
|
||||
{
|
||||
accountId,
|
||||
update: {
|
||||
[emailId]: {
|
||||
"keywords/$draft": true,
|
||||
...(draftsId ? { [`mailboxIds/${draftsId}`]: true } : {}),
|
||||
...(scheduledId ? { [`mailboxIds/${scheduledId}`]: null } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
"e",
|
||||
],
|
||||
], { allowErrors: true });
|
||||
const setRes = res.get("s")?.[0] as unknown as SetResponse & { __error?: { type: string; description?: string } };
|
||||
if (setRes.__error) throw new Error(setErrorMessage(setRes.__error));
|
||||
const err = setRes.notUpdated?.[sub.id];
|
||||
if (err) throw new Error(setErrorMessage(err));
|
||||
set((s) => {
|
||||
const { [emailId]: _drop, ...rest } = s.pending;
|
||||
return { pending: rest };
|
||||
});
|
||||
const mail = useMail.getState();
|
||||
void mail.loadMailboxes();
|
||||
void mail.refreshList();
|
||||
},
|
||||
|
||||
/**
|
||||
* Nothing moves a message out of Scheduled when its hold expires -- the
|
||||
* server sends it and updates the submission, but the message stays where we
|
||||
* filed it. So on the way into the folder, settle up: what went out belongs
|
||||
* in Sent, what was cancelled elsewhere belongs back in Drafts.
|
||||
*/
|
||||
async reconcile() {
|
||||
const mail = useMail.getState();
|
||||
const accountId = mail.accountId;
|
||||
const scheduledId = scheduledMailboxId();
|
||||
if (!accountId || !scheduledId) return;
|
||||
try {
|
||||
const q = await client.call<QueryResponse>("Email/query", {
|
||||
accountId,
|
||||
filter: { inMailbox: scheduledId },
|
||||
limit: 200,
|
||||
});
|
||||
if (!q.ids.length) {
|
||||
set({ pending: {} });
|
||||
return;
|
||||
}
|
||||
const subs = await loadFor(accountId, q.ids);
|
||||
// A message may carry several submissions if it was rescheduled. One
|
||||
// still pending settles it whatever the timestamps say -- the queue holds
|
||||
// a copy either way -- and otherwise the most recent wins.
|
||||
const latest = new Map<Id, PendingSend>();
|
||||
for (const s of subs) {
|
||||
const prev = latest.get(s.emailId);
|
||||
if (!prev) { latest.set(s.emailId, s); continue; }
|
||||
if (prev.undoStatus === "pending") continue;
|
||||
if (s.undoStatus === "pending" || s.sendAt >= prev.sendAt) latest.set(s.emailId, s);
|
||||
}
|
||||
const sentId = mail.roleId("sent");
|
||||
const draftsId = mail.roleId("drafts");
|
||||
const update: Record<Id, Record<string, unknown>> = {};
|
||||
const pending: Record<Id, PendingSend> = {};
|
||||
for (const emailId of q.ids) {
|
||||
const s = latest.get(emailId);
|
||||
if (s?.undoStatus === "pending") {
|
||||
pending[emailId] = s;
|
||||
continue;
|
||||
}
|
||||
// Cancelled goes back to Drafts; sent (or a submission the server no
|
||||
// longer knows about) goes to Sent, which is where it actually is.
|
||||
const toDrafts = s?.undoStatus === "canceled";
|
||||
const dest = toDrafts ? draftsId : sentId;
|
||||
if (!dest) continue;
|
||||
update[emailId] = {
|
||||
[`mailboxIds/${scheduledId}`]: null,
|
||||
[`mailboxIds/${dest}`]: true,
|
||||
...(toDrafts ? { "keywords/$draft": true } : {}),
|
||||
};
|
||||
}
|
||||
set({ pending, loaded: true });
|
||||
if (Object.keys(update).length) {
|
||||
await client.call("Email/set", { accountId, update });
|
||||
void mail.loadMailboxes();
|
||||
void mail.refreshList();
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(`Could not update the Scheduled folder: ${(err as Error).message}`);
|
||||
}
|
||||
},
|
||||
}));
|
||||
Reference in New Issue
Block a user