Compare commits

...
1 Commits
Author SHA1 Message Date
thuttuandCopilot bb34eedb44 Add conversation threads and prepare 0.6.0
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 22:46:11 +02:00
38 changed files with 532 additions and 23 deletions
+4
View File
@@ -8,6 +8,10 @@ The Electron app runs in its own window. On Windows, ep-mail also shows its icon
On Windows, `npm run build` runs `scripts\build.ps1`, building the Android debug APK and Windows portable executable. For all targets, run `npm run build:all`: it also builds the Windows installer and uses the default WSL distribution to build the Linux AppImage and Debian package. To select a distribution, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-all.ps1 -WslDistribution Ubuntu`. WSL needs Linux Node.js, npm and tar, plus the usual Electron packaging prerequisites and network access to install the locked dependencies. Linux builds use a temporary Linux filesystem workspace, then copy both packages into `release\`. Both build scripts preserve the legacy `ep-mail <version>.apk` copy of the debug APK; it is **not a signed release APK** and will overwrite a same-named signed APK. Use `npm run android:release-apk` afterwards when a signed release is needed.
See [SIGNING.md](./SIGNING.md) for private Android and Windows signing, verification, key backups, and the Android debug-to-release transition.
The message list groups related messages using Message-ID, References, and In-Reply-To headers. Expand or collapse each conversation to access its individual messages; collapsing deselects hidden messages, and bulk selection applies to visible rows. Grouping covers only the messages currently loaded in the selected folder or search results, not other folders or unloaded pages. Older offline cache entries gain threading information when refreshed.
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
### Google and Microsoft OAuth2
+143
View File
@@ -0,0 +1,143 @@
# Signing ep-mail builds
This guide covers privately distributed Android APKs and Windows executables built on Windows. Neither Google Play nor the Microsoft Store is required. Signing identifies the key used to produce an artifact and detects subsequent changes; it does not by itself prove the application is safe.
Android OpenPGP remains experimental and is not independently security reviewed. Signing the application does not change that status.
## Keep signing keys safe
- Keep private keys, keystores, PFX files, and passwords outside the repository and release artifacts. Never commit them or paste passwords into chat, issues, logs, or scripts.
- Restrict access to the files and store passwords separately in a password manager. Keep a secure backup of each private key and its password.
- Exchange and verify public certificate fingerprints through a separate trusted channel before trusting a certificate or installing an artifact.
- Run the PowerShell commands below from the repository root unless stated otherwise. Environment variables set here last only for the current PowerShell session, but are available to child processes during the build.
## Android: create a release signing key
Android accepts a self-signed app certificate; a paid certificate and Google Play account are unnecessary. Install the Android SDK and JDK 21 as described in the [README](./README.md).
Choose a secure directory outside the repository. Create it with appropriate access restrictions before proceeding. The following example uses Android Studio's JDK and prompts for the keystore password and certificate details:
```powershell
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
$env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA "Android\Sdk"
& "$env:JAVA_HOME\bin\keytool.exe" -genkeypair -v `
-keystore "C:\secure\ep-mail-android.p12" -storetype PKCS12 `
-alias ep-mail -keyalg RSA -keysize 3072 -validity 10000
```
Replace `C:\secure` with your secured directory. Do not overwrite or recreate an existing production keystore. With PKCS12, use the same password for the keystore and key entry. Back up the keystore and password securely; losing the key prevents ordinary in-place updates of apps signed with it. Record the alias and public certificate SHA-256 fingerprint:
```powershell
& "$env:JAVA_HOME\bin\keytool.exe" -list -v `
-keystore "C:\secure\ep-mail-android.p12" -storetype PKCS12 -alias ep-mail
```
### Build and verify
In the same PowerShell session, configure the existing release build. The password prompt avoids entering the password as a command-line argument, although the environment variables contain plaintext for the duration of the build session.
```powershell
$env:EP_MAIL_ANDROID_STORE_FILE = "C:\secure\ep-mail-android.p12"
$env:EP_MAIL_ANDROID_KEY_ALIAS = "ep-mail"
$env:EP_MAIL_ANDROID_STORE_PASSWORD = Read-Host "Keystore password" -AsSecureString |
ForEach-Object { [System.Net.NetworkCredential]::new("", $_).Password }
$env:EP_MAIL_ANDROID_KEY_PASSWORD = $env:EP_MAIL_ANDROID_STORE_PASSWORD
npm run android:release-apk
```
The output is `release\ep-mail <version>.apk`. Confirm the build succeeded before using it. Verify the signature and certificate fingerprint using the Android SDK build-tools version installed on your machine, replacing the example version if necessary:
```powershell
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
$apksigner = Join-Path $env:ANDROID_HOME "build-tools\36.0.0\apksigner.bat"
& $apksigner verify --verbose --print-certs "release\ep-mail $version.apk"
```
Compare the displayed signer SHA-256 fingerprint with the fingerprint recorded from the keystore. Afterwards, remove the password variables from the session:
```powershell
Remove-Item Env:\EP_MAIL_ANDROID_STORE_PASSWORD, Env:\EP_MAIL_ANDROID_KEY_PASSWORD
```
**Build order matters:** `npm run build` and `npm run build:all` build a debug APK and overwrite `release\ep-mail <version>.apk` with a debug-signed copy. Run `npm run android:release-apk` **after** those commands, then verify the resulting APK. The `-debug.apk` remains a debug build.
### Moving from the existing debug app
Android normally requires the installed app and its update to have the same signing certificate. A new release key will not match the currently installed debug key, so `adb install -r` will fail rather than replace it.
Before uninstalling, securely back up any private OpenPGP keys and revocation certificates, local-only drafts and other local data you need; ensure account settings can be recreated. Uninstalling removes the app's local data. After verifying your backups, uninstall the debug app using Android's app settings and install the verified release APK:
```powershell
& "$env:ANDROID_HOME\platform-tools\adb.exe" install "release\ep-mail $version.apk"
```
Future builds signed with the same release key can normally be installed with `adb install -r`. Keep the same package ID and use an appropriate version code for upgrades; do not assume that a different signing key will update the app.
## Windows: self-signed certificate for internal use
For private machines you control, a self-signed code-signing certificate is an option without buying a certificate. This does **not** make the publisher publicly trusted and does not guarantee that Microsoft Defender SmartScreen will stop warning. An unsigned build is also an option if these trust changes are not wanted.
The example below creates an exportable certificate in the current user's personal certificate store and exports a password-protected private-key PFX plus a public-only CER. Use a securely permissioned directory outside the repository and a name appropriate for your project. Do not replace an existing key without a plan for distributing and trusting the new public certificate.
```powershell
$cert = New-SelfSignedCertificate -Type CodeSigningCert `
-Subject "CN=ep-mail Internal" -CertStoreLocation "Cert:\CurrentUser\My" `
-KeyAlgorithm RSA -KeyLength 3072 -HashAlgorithm SHA256 `
-KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(5)
$pfxPassword = Read-Host "Choose a PFX password" -AsSecureString
Export-PfxCertificate -Cert $cert -FilePath "C:\secure\ep-mail-windows.pfx" -Password $pfxPassword
Export-Certificate -Cert $cert -FilePath "C:\secure\ep-mail-windows.cer"
$cert | Format-List Subject, Thumbprint, NotBefore, NotAfter
```
Back up the PFX and password securely. The CER is the public certificate: share it only with people who need to verify your builds, and verify its fingerprint independently. Renew or replace the certificate before expiry; use a trusted timestamp when signing so signature validity can be evaluated after expiry. Timestamping requires network access.
### Build and verify
Electron-builder accepts a PFX and password from the environment:
```powershell
$env:WIN_CSC_LINK = "C:\secure\ep-mail-windows.pfx"
$env:WIN_CSC_KEY_PASSWORD = Read-Host "PFX password" -AsSecureString |
ForEach-Object { [System.Net.NetworkCredential]::new("", $_).Password }
npm run dist:win
```
This builds the portable executable and installer in `release\`. `npm run build:all` also builds both Windows targets and uses these signing variables when supplied. Check the build output for signing errors; a build without credentials can otherwise produce unsigned artifacts. Verify **both** outputs:
```powershell
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
Get-AuthenticodeSignature "release\ep-mail $version.exe" |
Format-List Status, StatusMessage, SignerCertificate, TimeStamperCertificate
Get-AuthenticodeSignature "release\ep-mail Setup $version.exe" |
Format-List Status, StatusMessage, SignerCertificate, TimeStamperCertificate
Remove-Item Env:\WIN_CSC_KEY_PASSWORD
```
Compare each signer certificate fingerprint with the independently verified certificate. `Status` may indicate an untrusted chain until the public certificate is trusted on the verifying machine; a missing signer, invalid signature, or unexpected fingerprint must not be treated as success. A timestamp is distinct from the signer certificate; inspect its presence and validity as well.
### Trust the public certificate on a private machine
Only do this on machines you control, after independently verifying the CER fingerprint. Importing a root certificate changes trust for the current user, not just for ep-mail: software signed by a trusted key may also be trusted. Protect and distribute the key accordingly. Never import the PFX on machines that only need to verify builds.
```powershell
$publicCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\secure\ep-mail-windows.cer")
$publicCert | Format-List Subject, Thumbprint, NotBefore, NotAfter
# Proceed only after checking the thumbprint through a separate trusted channel.
Import-Certificate -FilePath "C:\secure\ep-mail-windows.cer" -CertStoreLocation "Cert:\CurrentUser\Root"
Import-Certificate -FilePath "C:\secure\ep-mail-windows.cer" -CertStoreLocation "Cert:\CurrentUser\TrustedPublisher"
```
Re-run `Get-AuthenticodeSignature` on each artifact and confirm a `Valid` status, the expected signer and the timestamp. Trust is per user with these commands; other users or machines require their own trust configuration. If the certificate is compromised or no longer needed, remove its entries from those stores and stop trusting or distributing builds signed by the compromised key.
For distribution to machines where manually installing trust is impractical, use a certificate from a publicly trusted code-signing provider instead. Such certificates have costs and provider-specific requirements; a valid signature does not guarantee SmartScreen reputation.
## References
- [Android app signing](https://developer.android.com/studio/publish/app-signing)
- [Android apksigner](https://developer.android.com/tools/apksigner)
- [electron-builder Windows code signing](https://www.electron.build/docs/features/code-signing/code-signing-win/)
- [Microsoft: New-SelfSignedCertificate](https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate)
+1 -1
View File
@@ -15,7 +15,7 @@
- [ ] Add a configurable Undo Send delay and scheduled sending.
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
- [x] Group related messages into conversations, with controls to expand or collapse threads.
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
@@ -166,6 +166,9 @@ internal object AndroidMailService {
add(FetchProfile.Item.FLAGS)
add(FetchProfile.Item.CONTENT_INFO)
add(UIDFolder.FetchProfileItem.UID)
add("Message-ID")
add("In-Reply-To")
add("References")
}
folder.fetch(batch.toTypedArray(), profile)
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
@@ -380,6 +383,11 @@ internal object AndroidMailService {
message.sentDate = Date()
message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
val idPattern = Regex("<[\\x21-\\x3b\\x3d\\x3f-\\x7e]+@[\\x21-\\x3b\\x3d\\x3f-\\x7e]+>")
val parent = idPattern.find(input.optString("inReplyTo").take(254))?.value
val references = idPattern.findAll(input.optString("references").take(900)).map { it.value }.toList()
if (parent != null) message.setHeader("In-Reply-To", parent)
if (references.isNotEmpty()) message.setHeader("References", references.joinToString(" "))
}
val transport = session.getTransport("smtp")
@@ -750,6 +758,9 @@ internal object AndroidMailService {
.put("sender", senderName)
.put("email", senderEmail)
.put("subject", subject)
.put("messageId", message.getHeader("Message-ID")?.joinToString(" ") ?: "")
.put("inReplyTo", message.getHeader("In-Reply-To")?.joinToString(" ") ?: "")
.put("references", message.getHeader("References")?.joinToString(" ") ?: "")
.put("snippet", snippet)
.put("encrypted", encrypted)
.put("signed", signed)
@@ -830,6 +830,8 @@ class EpMailPlugin : Plugin() {
.put("cc", input.optString("cc").take(4000))
.put("subject", input.optString("subject").take(998))
.put("text", input.optString("text").take(500000))
.put("inReplyTo", input.optString("inReplyTo").take(254))
.put("references", input.optString("references").take(900))
.put("attachments", input.optJSONArray("attachments") ?: JSONArray())
.put("updatedAt", System.currentTimeMillis())
AndroidAccountVault.saveDraft(account.optString("id"), draft)
+48 -1
View File
@@ -18,7 +18,54 @@ function returnToMessageList() {
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
readerListPosition = null;
}
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
const collapsedThreads = new Set();
function renderList() {
const rows = state.messages.filter(m => {
if (state.activeFolder === 'Starred' && !m.star) return false;
if (state.activeFolder === 'Inbox' && m.archived) return false;
if (state.activeFolder === 'Archive' && !m.archived) return false;
if (state.activeFolder === 'Trash' && !m.deleted) return false;
if (state.activeFolder === 'Sent' && !m.sent) return false;
if (state.activeFolder === 'Drafts' || state.activeFolder === 'Snoozed') return false;
if (m.deleted && state.activeFolder !== 'Trash') return false;
return !state.query || `${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase());
});
const groups = window.epMailConversationThreads.groupMessages(rows);
const scope = `${window.epMailFeatures?.mail?.connectedAccount?.id || ''}:${state.activeFolder}:`;
const keyFor = message => scope + (window.epMailConversationThreads.messageIds(message.messageId)[0] || `uid:${message.sourceFolder || ''}:${message.id}`);
const rowHtml = m => `<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${esc(m.id)}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`;
$('#message-list').innerHTML = rows.length ? groups.map((group, index) => {
if (group.length === 1) return rowHtml(group[0]);
const collapsed = group.some(message => collapsedThreads.has(keyFor(message)));
if (collapsed) group.slice(1).forEach(message => state.selectedIds.delete(message.id));
const unread = group.filter(message => message.unread).length;
return `<section class="conversation"><button type="button" class="conversation-toggle" data-thread="${index}" aria-expanded="${!collapsed}" aria-label="${collapsed ? 'Expand' : 'Collapse'} conversation: ${esc(group[0].subject)}">${collapsed ? '▸' : '▾'} Conversation · ${group.length} messages${unread ? ` · ${unread} unread` : ''}</button>${rowHtml(group[0])}<div class="conversation-replies"${collapsed ? ' hidden' : ''}>${group.slice(1).map(rowHtml).join('')}</div></section>`;
}).join('') : `<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;
$$('.conversation-toggle').forEach(button => button.addEventListener('click', () => {
const group = groups[Number(button.dataset.thread)];
const collapsing = button.getAttribute('aria-expanded') === 'true';
group.forEach(message => collapsing ? collapsedThreads.add(keyFor(message)) : collapsedThreads.delete(keyFor(message)));
if (collapsing) group.slice(1).forEach(message => state.selectedIds.delete(message.id));
const scrollTop = $('#message-list').scrollTop;
renderList();
$('#message-list').scrollTop = scrollTop;
}));
$$('.message').forEach(row => row.addEventListener('click', e => {
if (e.target.closest('.row-check')) {
const id = +row.dataset.id;
state.selectedIds.has(id) ? state.selectedIds.delete(id) : state.selectedIds.add(id);
return;
}
if (e.target.closest('.star')) {
const m = state.messages.find(x => x.id === +row.dataset.id);
m.star = !m.star;
renderList();
return;
}
openMessage(+row.dataset.id);
}));
if (!rows.length) { document.body.classList.remove('reader-open'); $('#reader-pane').innerHTML = emptyReader(); }
}
function openMessage(id){
state.activeMessage=id;
const m=state.messages.find(x=>x.id===id);
+47
View File
@@ -0,0 +1,47 @@
(function installConversationThreads(root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.epMailConversationThreads = api;
})(typeof window === 'undefined' ? globalThis : window, function () {
function messageIds(value) {
const text = Array.isArray(value) ? value.join(' ') : String(value || '');
return [...new Set((text.match(/<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>/g) || [])
.filter(id => id.length <= 254))];
}
function replyHeaders(message) {
const inReplyTo = messageIds(message?.messageId)[0] || '';
if (!inReplyTo) return { inReplyTo: '', references: '' };
const ids = [...new Set([...messageIds(message.references), inReplyTo])];
while (ids.join(' ').length > 900 && ids.length > 1) ids.splice(1, 1);
return { inReplyTo, references: ids.join(' ') };
}
function groupMessages(messages) {
const parents = messages.map((_, index) => index);
const find = index => {
while (parents[index] !== index) {
parents[index] = parents[parents[index]];
index = parents[index];
}
return index;
};
const owners = new Map();
messages.forEach((message, index) => {
const ids = [...messageIds(message.messageId), ...messageIds(message.inReplyTo), ...messageIds(message.references)];
for (const id of new Set(ids)) {
if (owners.has(id)) parents[find(index)] = find(owners.get(id));
else owners.set(id, index);
}
});
const groups = new Map();
messages.forEach((message, index) => {
const root = find(index);
if (!groups.has(root)) groups.set(root, []);
groups.get(root).push(message);
});
return [...groups.values()];
}
return { messageIds, replyHeaders, groupMessages };
});
+6
View File
@@ -202,6 +202,8 @@ registerIpcHandler('mail:save-draft', async (_event, input) => {
cc: String(input?.cc || '').slice(0, 4000),
subject: String(input?.subject || '').slice(0, 998),
text: String(input?.text || '').slice(0, 500000),
inReplyTo: String(input?.inReplyTo || '').slice(0, 254),
references: String(input?.references || '').slice(0, 900),
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
updatedAt: Date.now()
};
@@ -341,6 +343,8 @@ registerIpcHandler('mail:send', async (event, message) => {
text: message.text,
displayName: message.displayName,
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
inReplyTo: message.inReplyTo,
references: message.references,
attachments: message.attachments
};
const attachments = normalizeOutgoingAttachments(message?.attachments);
@@ -376,6 +380,8 @@ registerIpcHandler('mail:send', async (event, message) => {
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: queuedMessage.messageId,
inReplyTo: queuedMessage.inReplyTo,
references: queuedMessage.references,
encrypt: Boolean(pgpOptions.encrypt),
sign: Boolean(pgpOptions.sign),
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
+3
View File
@@ -1,6 +1,7 @@
const { randomUUID } = require('node:crypto');
const nodemailer = require('nodemailer');
const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs');
const { messageIds } = require('../../conversation-threads.js');
function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) {
async function sendMailNow(account, message) {
@@ -19,6 +20,8 @@ function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTr
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
inReplyTo: messageIds(message.inReplyTo)[0] || undefined,
references: messageIds(message.references),
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
+3
View File
@@ -344,6 +344,9 @@ async function toUiMessage(item, folder) {
sender: sender?.name || sender?.address || 'Unknown sender',
email: sender?.address || '',
subject: parsed.subject || '(no subject)',
messageId: parsed.messageId || '',
inReplyTo: parsed.inReplyTo || '',
references: parsed.references || [],
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
encrypted,
pgpSignatures,
+6 -1
View File
@@ -267,7 +267,7 @@ function createPgpMail({ keyStore, cache }) {
},
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
async build({ from, to, cc, subject, text, messageId, inReplyTo, references, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
const toList = parseAddresses(to);
const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.');
@@ -290,6 +290,9 @@ function createPgpMail({ keyStore, cache }) {
}
await cache.remember(signerEntry.fingerprint, secret);
}
const { messageIds } = require('../conversation-threads.js');
const parentIds = messageIds(inReplyTo).slice(0, 1);
const referenceIds = messageIds(references);
const headers = [
`From: ${formatAddress(from)}`,
`To: ${toList.map(formatAddress).join(', ')}`,
@@ -297,6 +300,8 @@ function createPgpMail({ keyStore, cache }) {
`Subject: ${encodeHeader(subject || '(no subject)')}`,
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
...parentIds.map(id => `In-Reply-To: ${id}`),
...(referenceIds.length ? [`References: ${referenceIds.join(' ')}`] : []),
'MIME-Version: 1.0'
];
const inner = await innerEntity(text, attachments);
+3 -2
View File
@@ -53,6 +53,7 @@ const objectFieldSchemas = {
'mail:create-folder': [{ name: str(100) }],
'mail:save-draft': [{
id: str(256), to: str(4000), cc: str(4000), subject: str(998), text: str(500_000),
inReplyTo: str(254), references: str(900),
attachments: array(record(attachmentFields))
}],
'mail:set-snooze': [{
@@ -67,7 +68,7 @@ const objectFieldSchemas = {
'mail:preview-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
'mail:send': [{
to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), displayName: str(80),
messageId: str(998), attachments: array(record(attachmentFields)),
messageId: str(998), inReplyTo: str(254), references: str(900), attachments: array(record(attachmentFields)),
pgp: record({ encrypt: bool(), sign: bool(), passphrase: str(4096, { nullable: true }) }, { nullable: true })
}],
'pgp:generate': [{ name: str(200), email: str(320), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
@@ -115,7 +116,7 @@ const positionalFieldSchemas = {
'pgp:remove-key-server': { 0: str(256) }
};
const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'attachments', 'pgp']);
const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'inReplyTo', 'references', 'attachments', 'pgp']);
const schemas = {
'app:get-version': [],
+1
View File
@@ -65,6 +65,7 @@
<div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="renderer-state.js"></script>
<script src="conversation-threads.js"></script>
<script src="mail-content-security.js"></script>
<script src="app.js"></script>
<script src="platform-bridge-loader.js"></script>
+6 -1
View File
@@ -529,6 +529,9 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
modal._replyHeaders = draft
? { inReplyTo: draft.inReplyTo || '', references: draft.references || '' }
: reply && !forward ? window.epMailConversationThreads.replyHeaders(reply) : { inReplyTo: '', references: '' };
let attachments = Array.isArray(draft?.attachments) ? draft.attachments : [];
modal._composeAttachments = attachments;
const fields = modal.querySelector('.compose-fields');
@@ -630,7 +633,8 @@ function setupDraftComposer() {
cc: modal.querySelector('#compose-cc').value,
subject: modal.querySelector('#compose-subject').value,
text: modal.querySelector('#compose-body').value,
attachments: [...attachments]
attachments: [...attachments],
...modal._replyHeaders
};
if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false);
values.id = modal.dataset.draftId || window.crypto.randomUUID();
@@ -1053,6 +1057,7 @@ if (window.daybreakMail) {
text: selectMailUi('#compose-body').value,
attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [],
displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '',
...(selectMailUi('#modal-root .compose-modal')?._replyHeaders || {}),
...(pgp ? { pgp } : {})
});
if (result.failed) {
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.5.23",
"version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.5.23",
"version": "0.6.0",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.5.23",
"version": "0.6.0",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
@@ -46,6 +46,7 @@
"styles.css",
"branding.css",
"renderer-state.js",
"conversation-threads.js",
"mail-content-security.js",
"renderer-mail-api.js",
"app.js",
+2
View File
@@ -10859,6 +10859,8 @@ ${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
`Subject: ${encodeHeader(message.subject || "(no subject)")}`,
`Date: ${(/* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000")}`,
`Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`,
...message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : [],
...message.references ? [`References: ${safeHeader(message.references, 900)}`] : [],
"MIME-Version: 1.0"
];
let contentType;
+1 -1
View File
@@ -59,7 +59,7 @@ function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message').filter(row=>!row.closest('[hidden]'));const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
const state = productivityMailUi.state;
+2
View File
@@ -405,6 +405,8 @@ export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.conf
`Subject: ${encodeHeader(message.subject || '(no subject)')}`,
`Date: ${new Date().toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`,
...(message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : []),
...(message.references ? [`References: ${safeHeader(message.references, 900)}`] : []),
'MIME-Version: 1.0'
];
let contentType;
+1
View File
@@ -10,6 +10,7 @@ const assets = [
'branding.css',
'platform-bridge-loader.js',
'renderer-state.js',
'conversation-threads.js',
'mail-content-security.js',
'renderer-mail-api.js',
'app.js',
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v22';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
const CACHE='ep-mail-v23';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./conversation-threads.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
self.addEventListener('fetch', event => {
+3
View File
@@ -235,3 +235,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.reader-pane{padding-bottom:10px}
}
@media(max-width:1000px),(max-height:500px) and (orientation:landscape) and (max-width:1200px){.sidebar{overflow:hidden}#mail-nav{display:flex;flex-direction:row;align-items:center;height:42px;min-height:0;max-height:42px;flex:none;overflow-x:auto;overflow-y:hidden;align-content:normal}#mail-nav .folder{height:34px;align-self:center}}
.conversation-toggle{display:block;width:100%;padding:8px 12px;border:0;border-bottom:1px solid var(--border,#ddd);background:transparent;color:inherit;text-align:left;font:inherit;font-size:.8rem;font-weight:600;cursor:pointer}
.conversation-toggle:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
.conversation-replies .message{padding-left:22px}
+5 -1
View File
@@ -88,7 +88,9 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
const built = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
messageId: '<test-message@example.test>', inReplyTo: '<parent@example.test>',
references: '<root@example.test> <parent@example.test>',
pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
attachments: [
{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') },
{ filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') }
@@ -97,6 +99,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
assert.ok(built.rawBase64);
saveMimeFixture('encrypted-signed', built.rawBase64);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
assert.match(raw, /\r\nIn-Reply-To: <parent@example\.test>\r\n/);
assert.match(raw, /\r\nReferences: <root@example\.test> <parent@example\.test>\r\n/);
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
assert.doesNotMatch(raw, /hello from Android|private attachment/);
recipient.setMessage({ rawBase64: built.rawBase64 });
+37
View File
@@ -0,0 +1,37 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { groupMessages, messageIds, replyHeaders } = require('../conversation-threads.js');
test('groups linked messages transitively in the original order, including absent ancestors', () => {
const messages = [
{ id: 1, messageId: '<one@example>', references: '<root@example>' },
{ id: 2, messageId: '<other@example>', subject: 'Same subject' },
{ id: 3, messageId: '<three@example>', inReplyTo: '<one@example>' },
{ id: 4, messageId: '<four@example>', references: ['<root@example>', '<missing@example>'] }
];
assert.deepEqual(groupMessages(messages).map(group => group.map(message => message.id)), [[1, 3, 4], [2]]);
});
test('messages without reference headers do not group by subject or invalid IDs', () => {
const messages = [
{ id: 1, subject: 'Hello', messageId: 'not-an-id' },
{ id: 2, subject: 'Re: Hello', inReplyTo: 'not-an-id' }
];
assert.deepEqual(groupMessages(messages).map(group => group.length), [1, 1]);
assert.deepEqual(messageIds('<a@example>\r\nBcc: <b@example>'), ['<a@example>', '<b@example>']);
assert.deepEqual(messageIds(`<${'a'.repeat(255)}@example>`), []);
});
test('reply headers retain the parent and bounded ancestry', () => {
assert.deepEqual(replyHeaders({ messageId: '<parent@example>', references: ['<root@example>', '<parent@example>'] }), {
inReplyTo: '<parent@example>', references: '<root@example> <parent@example>'
});
assert.deepEqual(replyHeaders({ references: '<root@example>' }), { inReplyTo: '', references: '' });
const result = replyHeaders({
messageId: '<parent@example>',
references: Array.from({ length: 100 }, (_, i) => `<${i}@example.test>`)
});
assert.ok(result.references.length <= 900);
assert.ok(result.references.startsWith('<0@example.test>'));
assert.ok(result.references.endsWith('<parent@example>'));
});
+43
View File
@@ -0,0 +1,43 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const threads = require('../conversation-threads.js');
test('conversation toggle hides older messages, clears their selection and preserves scroll', () => {
const source = fs.readFileSync(path.join(__dirname, '..', 'app.js'), 'utf8');
const code = source.slice(source.indexOf('const collapsedThreads = new Set();'), source.indexOf('function openMessage(id)'));
const list = { innerHTML: '', scrollTop: 42 };
const state = {
activeFolder: 'Inbox', query: '', activeMessage: null, selectedIds: new Set([1, 2]),
messages: [
{ id: 1, messageId: '<one@test>', inReplyTo: '<root@test>', subject: 'Re: Topic', unread: true },
{ id: 2, messageId: '<root@test>', subject: 'Topic' }
]
};
let handler;
const context = {
state, window: { epMailConversationThreads: threads },
document: { body: { classList: { remove() {} } } },
esc: value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;'),
$: selector => selector === '#message-list' ? list : {},
$$: selector => selector === '.conversation-toggle' ? [{
dataset: { thread: '0' },
getAttribute: () => list.innerHTML.includes('aria-expanded="true"') ? 'true' : 'false',
addEventListener(_type, callback) { handler = callback; }
}] : [],
emptyReader: () => '', openMessage() {}
};
vm.runInNewContext(`${code}\nrenderList();`, context);
assert.match(list.innerHTML, /aria-expanded="true"/);
assert.match(list.innerHTML, /2 messages · 1 unread/);
handler();
assert.match(list.innerHTML, /aria-expanded="false"/);
assert.match(list.innerHTML, /class="conversation-replies" hidden/);
assert.deepEqual([...state.selectedIds], [1]);
assert.equal(list.scrollTop, 42);
handler();
assert.match(list.innerHTML, /aria-expanded="true"/);
assert.doesNotMatch(list.innerHTML, /class="conversation-replies" hidden/);
});
+16 -3
View File
@@ -9,7 +9,7 @@ const mailSource = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
const pgpSource = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const setupSource = mailSource.slice(mailSource.indexOf('function setupDraftComposer()'), mailSource.indexOf('\nasync function syncMailbox('));
function harness(initialDraft = null) {
function harness(initialDraft = null, reply = null, forward = false) {
const saved = [];
const deleted = [];
const toasts = [];
@@ -40,7 +40,7 @@ function harness(initialDraft = null) {
appShell: { wrapShowCompose(fn) { wrapped = fn(() => {}); } },
selectMailUi: selector => selector === '#modal-root' ? modalRoot : elements.get(selector),
document: { createElement: node },
window: { crypto: { randomUUID: () => 'new-id' }, daybreakMail: {
window: { epMailConversationThreads: require('../conversation-threads.js'), crypto: { randomUUID: () => 'new-id' }, daybreakMail: {
saveDraft: values => saveDraft(values),
async deleteDraft(id) { deleted.push(id); }
} },
@@ -52,7 +52,7 @@ function harness(initialDraft = null) {
btoa: value => Buffer.from(value, 'binary').toString('base64')
};
vm.runInNewContext(`${setupSource}\nsetupDraftComposer();`, context);
wrapped(null, false, initialDraft);
wrapped(reply, forward, initialDraft);
return {
modal, modalRoot, elements, saved, deleted, toasts,
setSave(fn) { saveDraft = fn; },
@@ -85,6 +85,19 @@ test('reopening a draft restores fields, attachments, and its identity', () => {
assert.equal(h.elements.get('.modal-head span').textContent, 'Edit draft');
});
test('reply draft preserves thread headers when saved and restored; forwards do not inherit them', async () => {
const h = harness(null, { messageId: '<parent@example.test>', references: '<root@example.test>' });
h.elements.get('#compose-body').value = 'Reply';
h.modal.dispatch('input');
await h.runTimers();
assert.equal(h.saved[0].inReplyTo, '<parent@example.test>');
assert.equal(h.saved[0].references, '<root@example.test> <parent@example.test>');
const restored = harness(h.saved[0]);
assert.equal(restored.modal._replyHeaders.inReplyTo, '<parent@example.test>');
const forward = harness(null, { messageId: '<parent@example.test>' }, true);
assert.equal(forward.modal._replyHeaders.inReplyTo, '');
});
test('blank and whitespace-only new messages are not saved on close or manual save', async () => {
const h = harness();
h.elements.get('#compose-body').value = ' \n ';
+1
View File
@@ -71,6 +71,7 @@ test('validates channel-specific field shapes, limits, and enums', () => {
test('prevents renderer-supplied raw SMTP messages while accepting standard compose fields', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
to: 'friend@example.test', cc: '', subject: 'Hello', text: 'Body',
inReplyTo: '<parent@example.test>', references: '<root@example.test> <parent@example.test>',
attachments: [{ filename: 'note.txt', contentBase64: 'aGVsbG8=' }],
pgp: { encrypt: true, sign: false, passphrase: null }
}]));
+14
View File
@@ -82,6 +82,20 @@ test('reports Sent-copy failures without retrying a message accepted by SMTP', a
assert.equal(calls.appended.length, 0);
});
test('preserves reply headers in the SMTP message and Sent copy', async () => {
const { sendMailNow, calls } = makeSender();
await sendMailNow({ email: 'sender@example.com' }, {
to: 'recipient@example.com',
inReplyTo: '<parent@example.test>',
references: '<root@example.test> <parent@example.test>'
});
assert.equal(calls.smtp[0].inReplyTo, '<parent@example.test>');
assert.deepEqual(calls.smtp[0].references, ['<root@example.test>', '<parent@example.test>']);
const saved = JSON.parse(calls.appended[0].content.toString());
assert.equal(saved.inReplyTo, calls.smtp[0].inReplyTo);
assert.deepEqual(saved.references, calls.smtp[0].references);
});
test('closes SMTP transport and reports send failures', async () => {
const { sendMailNow, calls } = makeSender({ smtpFails: true });
await assert.rejects(
+6 -1
View File
@@ -32,11 +32,16 @@ test('encrypts and signs for a recipient and the sender can read the copy', asyn
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob <bob@example.com>', { encrypt: true, sign: true, passphrase: alice.passphrase }));
const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob <bob@example.com>', {
encrypt: true, sign: true, passphrase: alice.passphrase,
inReplyTo: '<parent@example.test>', references: '<root@example.test> <parent@example.test>'
}));
assert.deepEqual(envelope.to, ['bob@example.com']);
assert.ok(!raw.toString('latin1').includes('Top secret'));
const parsed = await simpleParser(raw);
assert.equal(parsed.subject, 'Héllo secrèt');
assert.equal(parsed.inReplyTo, '<parent@example.test>');
assert.deepEqual(parsed.references, ['<root@example.test>', '<parent@example.test>']);
assert.equal(detect(parsed), 'encrypted-mime');
await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED');
await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE');
+1 -1
View File
@@ -55,7 +55,7 @@ test('desktop, Android web generation, and offline cache include renderer suppor
const buildFiles = require(path.join(root, 'package.json')).build.files;
const androidAssets = read('scripts/prepare-android-web.cjs');
const worker = read('service-worker.js');
for (const file of ['renderer-state.js', 'mail-content-security.js', 'renderer-mail-api.js', 'platform-bridge-loader.js']) {
for (const file of ['renderer-state.js', 'conversation-threads.js', 'mail-content-security.js', 'renderer-mail-api.js', 'platform-bridge-loader.js']) {
assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`);
assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`);
assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`);
+48 -1
View File
@@ -18,7 +18,54 @@ function returnToMessageList() {
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
readerListPosition = null;
}
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
const collapsedThreads = new Set();
function renderList() {
const rows = state.messages.filter(m => {
if (state.activeFolder === 'Starred' && !m.star) return false;
if (state.activeFolder === 'Inbox' && m.archived) return false;
if (state.activeFolder === 'Archive' && !m.archived) return false;
if (state.activeFolder === 'Trash' && !m.deleted) return false;
if (state.activeFolder === 'Sent' && !m.sent) return false;
if (state.activeFolder === 'Drafts' || state.activeFolder === 'Snoozed') return false;
if (m.deleted && state.activeFolder !== 'Trash') return false;
return !state.query || `${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase());
});
const groups = window.epMailConversationThreads.groupMessages(rows);
const scope = `${window.epMailFeatures?.mail?.connectedAccount?.id || ''}:${state.activeFolder}:`;
const keyFor = message => scope + (window.epMailConversationThreads.messageIds(message.messageId)[0] || `uid:${message.sourceFolder || ''}:${message.id}`);
const rowHtml = m => `<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${esc(m.id)}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`;
$('#message-list').innerHTML = rows.length ? groups.map((group, index) => {
if (group.length === 1) return rowHtml(group[0]);
const collapsed = group.some(message => collapsedThreads.has(keyFor(message)));
if (collapsed) group.slice(1).forEach(message => state.selectedIds.delete(message.id));
const unread = group.filter(message => message.unread).length;
return `<section class="conversation"><button type="button" class="conversation-toggle" data-thread="${index}" aria-expanded="${!collapsed}" aria-label="${collapsed ? 'Expand' : 'Collapse'} conversation: ${esc(group[0].subject)}">${collapsed ? '▸' : '▾'} Conversation · ${group.length} messages${unread ? ` · ${unread} unread` : ''}</button>${rowHtml(group[0])}<div class="conversation-replies"${collapsed ? ' hidden' : ''}>${group.slice(1).map(rowHtml).join('')}</div></section>`;
}).join('') : `<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;
$$('.conversation-toggle').forEach(button => button.addEventListener('click', () => {
const group = groups[Number(button.dataset.thread)];
const collapsing = button.getAttribute('aria-expanded') === 'true';
group.forEach(message => collapsing ? collapsedThreads.add(keyFor(message)) : collapsedThreads.delete(keyFor(message)));
if (collapsing) group.slice(1).forEach(message => state.selectedIds.delete(message.id));
const scrollTop = $('#message-list').scrollTop;
renderList();
$('#message-list').scrollTop = scrollTop;
}));
$$('.message').forEach(row => row.addEventListener('click', e => {
if (e.target.closest('.row-check')) {
const id = +row.dataset.id;
state.selectedIds.has(id) ? state.selectedIds.delete(id) : state.selectedIds.add(id);
return;
}
if (e.target.closest('.star')) {
const m = state.messages.find(x => x.id === +row.dataset.id);
m.star = !m.star;
renderList();
return;
}
openMessage(+row.dataset.id);
}));
if (!rows.length) { document.body.classList.remove('reader-open'); $('#reader-pane').innerHTML = emptyReader(); }
}
function openMessage(id){
state.activeMessage=id;
const m=state.messages.find(x=>x.id===id);
+47
View File
@@ -0,0 +1,47 @@
(function installConversationThreads(root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.epMailConversationThreads = api;
})(typeof window === 'undefined' ? globalThis : window, function () {
function messageIds(value) {
const text = Array.isArray(value) ? value.join(' ') : String(value || '');
return [...new Set((text.match(/<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>/g) || [])
.filter(id => id.length <= 254))];
}
function replyHeaders(message) {
const inReplyTo = messageIds(message?.messageId)[0] || '';
if (!inReplyTo) return { inReplyTo: '', references: '' };
const ids = [...new Set([...messageIds(message.references), inReplyTo])];
while (ids.join(' ').length > 900 && ids.length > 1) ids.splice(1, 1);
return { inReplyTo, references: ids.join(' ') };
}
function groupMessages(messages) {
const parents = messages.map((_, index) => index);
const find = index => {
while (parents[index] !== index) {
parents[index] = parents[parents[index]];
index = parents[index];
}
return index;
};
const owners = new Map();
messages.forEach((message, index) => {
const ids = [...messageIds(message.messageId), ...messageIds(message.inReplyTo), ...messageIds(message.references)];
for (const id of new Set(ids)) {
if (owners.has(id)) parents[find(index)] = find(owners.get(id));
else owners.set(id, index);
}
});
const groups = new Map();
messages.forEach((message, index) => {
const root = find(index);
if (!groups.has(root)) groups.set(root, []);
groups.get(root).push(message);
});
return [...groups.values()];
}
return { messageIds, replyHeaders, groupMessages };
});
+1
View File
@@ -65,6 +65,7 @@
<div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="renderer-state.js"></script>
<script src="conversation-threads.js"></script>
<script src="mail-content-security.js"></script>
<script src="app.js"></script>
<script src="platform-bridge-loader.js"></script>
+6 -1
View File
@@ -529,6 +529,9 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
modal._replyHeaders = draft
? { inReplyTo: draft.inReplyTo || '', references: draft.references || '' }
: reply && !forward ? window.epMailConversationThreads.replyHeaders(reply) : { inReplyTo: '', references: '' };
let attachments = Array.isArray(draft?.attachments) ? draft.attachments : [];
modal._composeAttachments = attachments;
const fields = modal.querySelector('.compose-fields');
@@ -630,7 +633,8 @@ function setupDraftComposer() {
cc: modal.querySelector('#compose-cc').value,
subject: modal.querySelector('#compose-subject').value,
text: modal.querySelector('#compose-body').value,
attachments: [...attachments]
attachments: [...attachments],
...modal._replyHeaders
};
if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false);
values.id = modal.dataset.draftId || window.crypto.randomUUID();
@@ -1053,6 +1057,7 @@ if (window.daybreakMail) {
text: selectMailUi('#compose-body').value,
attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [],
displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '',
...(selectMailUi('#modal-root .compose-modal')?._replyHeaders || {}),
...(pgp ? { pgp } : {})
});
if (result.failed) {
+2
View File
@@ -10859,6 +10859,8 @@ ${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
`Subject: ${encodeHeader(message.subject || "(no subject)")}`,
`Date: ${(/* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000")}`,
`Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`,
...message.inReplyTo ? [`In-Reply-To: ${safeHeader(message.inReplyTo, 254)}`] : [],
...message.references ? [`References: ${safeHeader(message.references, 900)}`] : [],
"MIME-Version: 1.0"
];
let contentType;
+1 -1
View File
@@ -59,7 +59,7 @@ function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message').filter(row=>!row.closest('[hidden]'));const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
const state = productivityMailUi.state;
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v22';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
const CACHE='ep-mail-v23';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./conversation-threads.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
self.addEventListener('fetch', event => {
+3
View File
@@ -235,3 +235,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.reader-pane{padding-bottom:10px}
}
@media(max-width:1000px),(max-height:500px) and (orientation:landscape) and (max-width:1200px){.sidebar{overflow:hidden}#mail-nav{display:flex;flex-direction:row;align-items:center;height:42px;min-height:0;max-height:42px;flex:none;overflow-x:auto;overflow-y:hidden;align-content:normal}#mail-nav .folder{height:34px;align-self:center}}
.conversation-toggle{display:block;width:100%;padding:8px 12px;border:0;border-bottom:1px solid var(--border,#ddd);background:transparent;color:inherit;text-align:left;font:inherit;font-size:.8rem;font-weight:600;cursor:pointer}
.conversation-toggle:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
.conversation-replies .message{padding-left:22px}