📧✨ Beautiful email. For everyone.
fix: preserve draft revisions across delayed saves (#40)
Paul Koeck823cbe34fc01
diff --git a/apps/desktop/src/main/service.ts b/apps/desktop/src/main/service.tsindex ebe4a01..687ae5e 100644--- a/apps/desktop/src/main/service.ts+++ b/apps/desktop/src/main/service.ts@@ -1141,6 +1141,19 @@ export class MailService {if (this.busyDrafts.has(draft.id) || old?.status === 'uncertain' || old?.status === 'sent')return old || draftif (old && old.updatedAt > draft.updatedAt) return old+ // Server revisions belong to the main process. An edit captured before a sync reply+ // must not restore an ID that we have already replaced and removed from the server.+ // Clearing the link after a conflict is the explicit “Keep both versions” action.+ if (+ old?.serverId &&+ old.accountId === draft.accountId &&+ !(old.errorKind === 'conflict' && !draft.serverId)+ )+ draft = {+ ...draft,+ serverId: old.serverId,+ serverFingerprint: old.serverFingerprint,+ }if (draft.encryption !== 'encrypt' &&(old?.encryption === 'encrypt' || draft.encryptionRequired) &&@@ -1156,6 +1169,7 @@ export class MailService {...draft,earlierPlaintext:draft.earlierPlaintext ||+ old?.earlierPlaintext ||(!!old && old.encryption !== 'encrypt') ||(!!draft.serverId && old?.encryption !== 'encrypt'),}@@ -1460,15 +1474,15 @@ export class MailService {}send = async (input: Draft): Promise<SendResult> => {if (this.protectionTransition) throw new Error('The vault is locking.')- const draft = sendDraftSchema.parse(input)+ let draft = sendDraftSchema.parse(input)if (!draft.to.length && !draft.cc.length && !draft.bcc.length)throw new Error('Add at least one recipient.')if (this.busyDrafts.has(draft.id))throw new Error('This draft is still saving. Try again in a moment.')const existing = this.journals.get(draft.id)if (existing && existing.state !== 'rejected') return this.reconcile(draft.id)+ draft = sendDraftSchema.parse(await this.saveDraft(draft))const { provider, account } = this.provider(draft.accountId)- await this.saveDraft(draft)this.busyDrafts.add(draft.id)const journal: Journal = {draftId: draft.id,diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 599fb55..89b34eb 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -25,6 +25,7 @@ import { Modal, Button, IconButton, Select, Spinner } from '@inlark/ui'import {friendlyError,identitySignature,+ isValidRecipientEmail as validAddress,type Address,type Account,type Draft,@@ -44,7 +45,6 @@ import { SignatureNode } from './signature'import { linkTarget } from './link-target'import { SignatureParagraph, hasDraftContent, replaceSignature } from './composer-document'-const validAddress = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)/** One From choice: an account and one of its sending addresses. */const senderKey = (accountId: string, identityId: string) => JSON.stringify([accountId, identityId])/** The editor's own formatting keys, which follow the platform (⌘ on macOS, Ctrl elsewhere). */@@ -368,7 +368,7 @@ export function Composer({serverId: result.serverId || current.serverId,serverFingerprint: result.serverFingerprint || current.serverFingerprint,...(current.updatedAt === captured.updatedAt- ? { status: result.status, error: result.error }+ ? { status: result.status, error: result.error, errorKind: result.errorKind }: {}),}latest.current = mergeddiff --git a/apps/desktop/src/renderer/src/RecipientField.tsx b/apps/desktop/src/renderer/src/RecipientField.tsxindex 9760717..392f26c 100644--- a/apps/desktop/src/renderer/src/RecipientField.tsx+++ b/apps/desktop/src/renderer/src/RecipientField.tsx@@ -1,10 +1,9 @@import { cn } from '@inlark/ui'import { useId, useRef, useState, type ReactNode } from 'react'import { Lock, LockOpen, X } from '@inlark/ui/icons'-import { parseAddresses, type Address } from '@inlark/core'+import { isValidRecipientEmail as valid, parseAddresses, type Address } from '@inlark/core'import { Avatar } from '@inlark/ui'-const valid = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)const same = (a: Address, b: Address) => a.email.toLowerCase() === b.email.toLowerCase()const format = (a: Address) => (a.name ? a.name + ' <' + a.email + '>' : a.email)/** Whether mail to a recipient can be encrypted, shown on their chip while encrypting. */diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.tsindex 7d29e53..4985d7b 100644--- a/packages/core/src/schemas.ts+++ b/packages/core/src/schemas.ts@@ -3,6 +3,10 @@ import type { DesktopMailAPI } from './model'const id = z.string().min(1).max(2048)const address = z.object({ name: z.string().max(1000), email: z.string().max(320) })+const recipientEmailSchema = z.email().max(320)+/** Uses the same validation for composer recipients and encryption IPC requests. */+export const isValidRecipientEmail = (email: string): boolean =>+ recipientEmailSchema.safeParse(email).successexport const serverUrlSchema = z.string().url()@@ -185,7 +189,7 @@ export const sendDraftSchema = draftSchema(d) =>[...d.to, ...d.cc, ...d.bcc].length > 0 &&[...d.to, ...d.cc, ...d.bcc].every(- (a) => z.email().safeParse(a.email).success && !/[\r\n]/.test(a.name),+ (a) => isValidRecipientEmail(a.email) && !/[\r\n]/.test(a.name),),'Add valid recipients before sending.',)@@ -230,7 +234,7 @@ export const ipcSchemas = {z.string().regex(/^[a-f0-9]{40,64}$/),z.boolean(),]),- encryptionReadiness: z.tuple([id, id, z.array(z.email().max(320)).max(600)]),+ encryptionReadiness: z.tuple([id, id, z.array(recipientEmailSchema).max(600)]),unlockEncryption: z.tuple([z.string().max(4096).optional()]),lockEncryption: z.tuple([]),transferEncryption: z.tuple([diff --git a/tests/core.test.ts b/tests/core.test.tsindex 17d0b2f..4061f49 100644--- a/tests/core.test.ts+++ b/tests/core.test.ts@@ -11,6 +11,8 @@ import {mailtoDraft,draftSchema,sendDraftSchema,+ isValidRecipientEmail,+ ipcSchemas,defaultSettings,identityKey,identitySignature,@@ -55,6 +57,26 @@ export const draft = (overrides: Partial<Draft> = {}): Draft => ({...overrides,})describe('mail domain', () => {+ it('waits for complete recipients before requesting encryption readiness', () => {+ for (const email of [+ 'paul',+ 'paul@',+ 'paul@blinkdisk.',+ '[email protected]',+ '[email protected]',+ '[email protected]',+ '[email protected]',+ '[email protected]',+ ]) {+ const valid = isValidRecipientEmail(email)+ expect(+ ipcSchemas.encryptionReadiness.safeParse(['account', 'identity', [email]]).success,+ ).toBe(valid)+ expect(sendDraftSchema.safeParse(draft({ to: [{ name: '', email }] })).success).toBe(valid)+ }+ expect(isValidRecipientEmail('[email protected]')).toBe(false)+ expect(isValidRecipientEmail('[email protected]')).toBe(true)+ })it('keeps identical remote IDs in different connections and accounts separate', () => {const a = accountKey('connection-a', 'same'),b = accountKey('connection-b', 'same')diff --git a/tests/encryption-service.test.ts b/tests/encryption-service.test.tsindex 8fb67cd..d8c90dd 100644--- a/tests/encryption-service.test.ts+++ b/tests/encryption-service.test.ts@@ -398,6 +398,9 @@ it('keeps protected main-process drafts and attachments encrypted through crashawait expect(readFile(join(directory, 'attachments', input.attachments[0].id)),).rejects.toMatchObject({ code: 'ENOENT' })+ // A first autosave can finish just before encryption is enabled in the composer.+ const plaintext = await main.syncDraft({ ...input, encryption: undefined })+ expect(plaintext.status).toBe('synced')await main.saveDraft(input)expect(await readFile(join(directory, 'drafts.json'), 'utf8')).not.toContain('MARKER')expect(await readFile(join(directory, 'encryption-vault.json'), 'utf8')).not.toContain('MARKER')@@ -408,8 +411,25 @@ it('keeps protected main-process drafts and attachments encrypted through crashawait expect(main.saveDraft({ ...input, encryption: 'none' })).rejects.toThrow('Confirm')const saved = await main.syncDraft(input)expect(saved.status).toBe('synced')+ expect(saved.earlierPlaintext).toBe(true)expect(saved.serverFingerprint).toMatch(/^[a-f0-9]{64}$/)- const sent = await main.send(saved)+ expect(server.box('Drafts').messages).toHaveLength(1)+ expect(saved.serverId).not.toBe(plaintext.serverId)+ // A delayed edit still carries the plaintext revision we have already removed.+ const edited = await main.syncDraft({+ ...saved,+ serverId: plaintext.serverId,+ serverFingerprint: plaintext.serverFingerprint,+ text: 'PRIVATE BODY MARKER edited',+ html: '<p>PRIVATE BODY MARKER edited</p>',+ updatedAt: new Date(Date.parse(saved.updatedAt) + 1000).toISOString(),+ })+ expect(edited.status).toBe('synced')+ expect(edited.serverId).not.toBe(saved.serverId)+ expect(edited.serverFingerprint).not.toBe(saved.serverFingerprint)+ expect(server.box('Drafts').messages).toHaveLength(1)+ expect(await readFile(join(directory, 'drafts.json'), 'utf8')).not.toContain('MARKER')+ const sent = await main.send(edited)expect(sent.status).toBe('sent')expect(Buffer.from(submit.mock.calls[0][2]).toString()).not.toContain('MARKER')const tombstone = (await main.drafts()).find((d) => d.id === input.id)!diff --git a/tests/service-imap.test.ts b/tests/service-imap.test.tsindex 5d9d617..d0ef05a 100644--- a/tests/service-imap.test.ts+++ b/tests/service-imap.test.ts@@ -461,6 +461,60 @@ describe('IMAP drafts', () => {expect(second).toMatchObject({ status: 'error', errorKind: 'conflict', text: 'Mine' })expect(server.box('Drafts').messages.map((m) => m.input.text)).toEqual(['Their edit'])})+ it('retains the latest server revision when a delayed local save carries the replaced ID', async () => {+ const first = await service.syncDraft(draft)+ const second = await service.syncDraft({+ ...first,+ text: 'Second revision',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ // This edit started before the renderer received the replacement's server ID.+ const edited = await service.saveDraft({+ ...first,+ text: 'Third revision',+ updatedAt: '2026-09-23T10:02:00.000Z',+ status: 'local',+ })+ expect(edited.serverId).toBe(second.serverId)+ expect(edited.serverFingerprint).toBe(second.serverFingerprint)+ const third = await service.syncDraft(edited)+ expect(third.status).toBe('synced')+ expect(server.box('Drafts').messages.map((m) => m.input.text?.trim())).toEqual([+ 'Third revision',+ ])+ })+ it('retains a confirmed first server save when a delayed edit has no server ID yet', async () => {+ const first = await service.syncDraft(draft)+ const edited = await service.saveDraft({+ ...draft,+ text: 'Newer edit',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(edited.serverId).toBe(first.serverId)+ expect((await service.syncDraft(edited)).status).toBe('synced')+ expect(server.box('Drafts').messages).toHaveLength(1)+ })+ it('allows explicitly keeping a separate copy after a real remote conflict', async () => {+ const first = await service.syncDraft(draft)+ server.setFlags('Drafts', server.box('Drafts').messages[0].uid, ['\\Seen'])+ const conflict = await service.syncDraft({+ ...first,+ text: 'Mine',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(conflict.errorKind).toBe('conflict')+ const separate = await service.syncDraft({+ ...conflict,+ serverId: undefined,+ serverFingerprint: undefined,+ error: undefined,+ errorKind: undefined,+ status: 'local',+ updatedAt: '2026-09-23T10:02:00.000Z',+ })+ expect(separate.status).toBe('synced')+ expect(server.box('Drafts').messages).toHaveLength(2)+ })it('keeps the previous server draft when the replacement cannot be confirmed', async () => {const first = await service.syncDraft(draft)server.hooks.set('APPEND:before', () => {diff --git a/tests/service.test.ts b/tests/service.test.tsindex 97bbbc9..bf6d574 100644--- a/tests/service.test.ts+++ b/tests/service.test.ts@@ -277,6 +277,88 @@ describe('durable mail operations', () => {expect(saved.text).toBe('Hello')expect(JmapProvider.prototype.createDraft).not.toHaveBeenCalled()})+ it.each([false, true])(+ 'keeps JMAP replacement IDs through delayed saves (encrypted: %s)',+ async (encrypted) => {+ const remote = new Map<string, { message: Message; raw: Uint8Array }>()+ if (encrypted) {+ await service.encryption.vault.create('test-vault-password')+ const fixture = await readFile(+ new URL('./fixtures/openpgp/encrypted-signed.eml', import.meta.url),+ )+ vi.spyOn(service.encryption, 'compose').mockImplementation(async (_draft, _own, id) =>+ Buffer.concat([Buffer.from('X-Draft-Revision: ' + id + '\r\n'), fixture]),+ )+ }+ let revision = 0+ vi.mocked(JmapProvider.prototype.createDraft).mockImplementation(+ async (_account, input, _messageId, mime) => {+ const id = 'revision-' + ++revision+ remote.set(id, {+ message: {+ ...mail,+ id,+ subject: input.subject,+ to: input.to,+ html: input.html,+ text: input.text,+ keywords: { $draft: true, $seen: true },+ },+ raw: mime || Buffer.from('Content-Type: text/plain\r\n\r\n' + input.text),+ })+ return id+ },+ )+ vi.mocked(JmapProvider.prototype.messages).mockImplementation(async (_account, ids) =>+ ids.flatMap((id) => (remote.has(id) ? [remote.get(id)!.message] : [])),+ )+ vi.spyOn(JmapProvider.prototype, 'rawMessage').mockImplementation(+ async (_account, id) => remote.get(id)!.raw,+ )+ vi.mocked(JmapProvider.prototype.update).mockImplementation(async (_a, _changes, ids) => {+ for (const id of ids || []) remote.delete(id)+ return { updated: [], failures: [] }+ })+ const first = await service.syncDraft(draft)+ const second = await service.syncDraft({+ ...first,+ encryption: encrypted ? 'encrypt' : undefined,+ text: 'Second revision',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(second.status).toBe('synced')+ expect(remote.has(first.serverId!)).toBe(false)+ // The next edit was captured before the replacement reply reached the composer.+ const third = await service.syncDraft({+ ...second,+ serverId: first.serverId,+ serverFingerprint: first.serverFingerprint,+ text: 'Third revision',+ updatedAt: '2026-09-23T10:02:00.000Z',+ })+ expect(third.status).toBe('synced')+ expect([...remote.keys()]).toEqual([third.serverId])+ if (encrypted) {+ expect(third.serverFingerprint).toMatch(/^[a-f0-9]{64}$/)+ expect(await readFile(join(directory, 'drafts.json'), 'utf8')).not.toContain(+ 'Third revision',+ )+ }+ vi.spyOn(JmapProvider.prototype, 'submit').mockResolvedValue({+ accepted: ['[email protected]'],+ rejected: [],+ })+ expect(+ (+ await service.send({+ ...third,+ serverId: first.serverId,+ serverFingerprint: first.serverFingerprint,+ })+ ).status,+ ).toBe('sent')+ },+ )it('does not undo over a subsequent change from another client', async () => {const result = await service.mutate({