diff --git a/CHANGELOG.md b/CHANGELOG.md index 61fa24db..591e5617 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [1.5.0] - 2026-11-24 +## [1.5.0] - 2026-11-25 ### Added - **Inbox Agent works through a request step by step.** It now decides for @@ -108,6 +108,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 goes to the agent like any other request, which finds the emails it means and prepares a card. +### Fixed +- **Keyboard shortcuts keep working after you click inside a message.** + Clicking a link in an email (or anywhere in its text) moved the keyboard into + the message, and every shortcut — next and previous mail, archive, delete, + search, Escape — stopped responding until you clicked somewhere outside it. + Shortcuts now work straight away, in the standard view and in chat view, + while copying text you selected in the message and typing into a field in it + work as before. +- **Searching for a common word no longer freezes the app.** A search used to + read the full text of every email that matched before showing the first + page, so a word found in thousands of emails (such as "meeting") could stop + the whole app for half a minute, and an Inbox Agent question that ran many + searches could hang it for minutes. Search now picks the page of results + first and reads only those emails. +- **A crashed extension comes back even when the computer is slow to + recover.** When an extension crashes, for example by running out of memory, + the app starts it again, up to three times. If the first of those starts was + slow because the computer was still freeing the memory the crash had used, + that one slow start ended the recovery: the extension stayed off until the + app was restarted. A start that is too slow now counts as one attempt and + the next one follows. You are told only once every attempt has failed. +- **New mail no longer stops arriving in a folder after one failed sync.** If + fetching a folder's new mail failed once (a timeout, a dropped connection, a + busy server), the app still noted the folder as up to date, and the regular + background sync then skipped it as unchanged. The missed mail stayed on the + server until something else arrived in that folder or you refreshed it by + hand. A folder is now noted as up to date only once its new mail has really + been downloaded, so the next sync picks up what the failed one missed. + +### Security +- **The XML reader used for office attachments is updated to 5.12.** It fixes a + low-severity slowdown on malformed tags + ([GHSA-474x-hrwr-fgx4](https://github.com/advisories/GHSA-474x-hrwr-fgx4)). + Sarv Inbox never used the affected feature, so earlier versions were not + exposed. +- **The log file no longer names your accounts, folders or user folder.** + Every line about an account carried its internal id, which spells out the + email address, and lines about syncing named your folders, labels and AI + categories. These are now written as short codes (system folders such as + Inbox and Sent keep their names), file locations are written without your + home folder, and failures that could quote mail or a server's answer are + recorded by their kind only. +- **Crash reports carry less about you.** A report no longer identifies you by + a shortened hash of your email address, which anyone guessing your address + could confirm; it uses a random code made on your computer instead. Web + requests in a report no longer keep their query string (which can hold keys + and search words), and sign-in codes, keys, passphrases and `Basic` + passwords are removed from reports and the log file wherever they appear. +- **Sign-in tokens are never resent to a redirected address.** If an email + provider's token service answered a refresh with a redirect, the app would + have sent your refresh token again to wherever it pointed. It now refuses + the redirect and retries later, and the same goes for fetching your profile + after sign-in. + + ## [1.4.12] - 2026-11-24 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index 4a200ab3..1627419a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,6 +67,15 @@ lands in `app.log` consistently: field NAMES (`setFieldNamesForLog`), a URL's scheme (`urlSchemeForLog`) and `errorDiagnostic(error)` instead of the error, whose message can quote any of those. Prove it with a sentinel test (`captureLogs`). +- **Names that belong to the user are labels in a log line.** An account id + spells out its owner's address (`acct----`): + write `accountLogLabel(id)`. A folder, Gmail label, keyword or AI category + the user created is text they typed: `folderLogLabel(path)` (system folders + stay readable), `labelLogLabel(name)`, `categoryLogLabel(slug, isSystem)`. + An absolute path names the user through their home folder: `logPath(p)` in + main (`/…`, `~/…`), `pathForLog` / `basename` elsewhere. The file + logger rewrites the home folder as `~` and, in a release, account ids it + finds, and crash reports get the same — a backstop, not a licence. ## Native modules: better-sqlite3 has TWO ABIs — never flip it by hand @@ -422,12 +431,36 @@ Established shared helpers (extend this list as you add more): user's approval (or within the "Approve for me" cap), each row at most once, protected rows only when ticked, Undo only for rows still as the set left them. A new agent write tool stages through it; never call a mail action from a tool. +- `accountLogLabel(id, missing?)` / `folderLogLabel(path)` / `labelLogLabel(name)` / + `categoryLogLabel(slug, system)` / `redactAccountIds(text)` — + `packages/core/src/utils/log-labels.ts` (renderer: `@sarvinbox/core/log-labels`). + The stand-ins a log line uses for the account (`acct#1a2b3c4d`), a folder, + label or AI category the user named: a short stable hash, so lines still + match and grep. `redactAccountIds` is the backstop the release file logger + and the crash-report scrubber run over every line. +- `pathForLog(path, { userData, home })` / `redactHomeDir(text, home)` — + `packages/core/src/utils/log-paths.ts` (Node only); in main, `logPath(path)` / + `withoutHomeDir(text)` — `apps/desktop/electron/utils/log-path.ts`, rooted at + this app's data folder and the user's home. A path for a log line without the + home folder (and the user's name in it). +- `crashReportInstallId()` — `apps/desktop/electron/services/crash-report-pref.ts`. + The crash reports' user id: a random UUID kept in userData, never anything + derived from an address. +- `apps/desktop/test/helpers/core-log-helpers.ts` — the REAL core log helpers + (`errorDiagnostic`, the log labels, `pathForLog`) for a desktop test that mocks + `@sarvinbox/core` partially. Spread it first in the mock factory; a mock + without them fails at the first log line the code under test writes. - `createAssistantHarness()` — `apps/desktop/test/helpers/assistant-harness.ts`. The real Inbox Agent end to end for tests (real databases, history store and provider call path; scripted network). Use it instead of hand-wiring `InboxAssistantServiceDeps` when a test asks the agent a question. The evaluation in `apps/desktop/test/eval/assistant/` is built on it; see [docs/TESTING.md](docs/TESTING.md), "Inbox Agent evaluation". +- `appJsFlags(extra?)` / `V8_MAX_OLD_SPACE_MB` — `apps/desktop/electron/v8-flags.ts`. + The app's V8 flags. Chromium passes `--js-flags` to every renderer, the extension + sandboxes included, so this 2 GB heap cap is also how much an extension can + take. Use it wherever Electron is launched with `js-flags`, the sandbox-escape + harness included, so a test runs under the cap that ships. ## Prefer a mature library over hand-rolled / regex logic diff --git a/SECURITY.md b/SECURITY.md index 2d4e3c4b..c3285080 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -125,33 +125,56 @@ A handful cannot be fixed that way. Those are listed in pnpm 8 offers — and every entry must be justified here. An undocumented entry is a bug: the point of the gate is that nothing high-severity is silently carried. -Reviewed 2026-10-12 (`pnpm audit --audit-level=high` exits 0; the full report -without the ignore list shows 2 high, both below, and 3 moderate, noted after -the table). Neither high advisory has a fixed version that an override could -reach, so both exceptions stay: - -| CVE | Package | Why it is accepted | Removed when | -| --- | --- | --- | --- | -| [CVE-2026-93748](https://github.com/advisories/GHSA-ch52-4w7c-c8xp) | `http-cache-semantics` <= 4.2.0 | Cross-user response disclosure requires a shared HTTP cache accepting attacker-controlled `max-stale` directives. The dependency is reached only through the desktop **build tool** `electron-builder` → `app-builder-lib` → `@electron/get` → `got` → `cacheable-request`. Inbox does not use this chain to handle mail, OAuth, scanner requests, or shared user caches. **No patched release exists.** 4.3.0 (2026-10-04) is not one: it fixes a different advisory (CVE-2026-93750, `Vary` matching) and leaves `max-stale` handling unchanged. Because the advisory's range stops at 4.2.0, `pnpm audit` would nonetheless report this CVE as gone on 4.3.0, so do not read a clean audit after such a bump as a fix. This is a temporary exception for that reviewed tooling scope, not a vulnerability fix. | A release that actually changes `max-stale` handling ships (check its diff, not the advisory range), the build tool drops it, or a runtime/shared-cache path appears (reassess before shipping). | -| [CVE-2026-93687](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) | `braces` <= 3.0.3 | Stack exhaustion requires deeply nested glob patterns. All dependency paths are **tooling**: ESLint/globby, Tailwind/chokidar/fast-glob, and Metro/Jest. These tools process project patterns, not mail bodies, attachments, or user-supplied runtime patterns. **No patched release exists** (3.0.3 is the latest published version). The remaining build-tool risk is accepted temporarily; the package itself remains vulnerable. | A patched release becomes available, the tooling drops it, or an untrusted runtime-pattern path appears (reassess before shipping). | - -Moderate, no fixed version (below the gate, so not in `ignoreCves`; listed so -the full report holds no surprises): - -- [CVE-2026-97058](https://github.com/advisories/GHSA-hp3w-g68c-fv3c), - `sprintf-js` <= 1.1.3 (denial of service through unbounded precision - specifiers). 1.1.3 is the latest release. Reached only by dev and build - tooling: 1.0.3 via `packages/ui-primitives` → `react-native` (an optional - peer) → `babel-jest` → … → `js-yaml@3` → `argparse@1`, and 1.1.3 via - `electron-builder` → `@electron/get` → `global-agent` → `roarr`. Neither is - in the shipped app. -- [CVE-2026-104844](https://github.com/advisories/GHSA-rj75-hqrm-r3gf), - `postcss-selector-parser` < 7.1.6 (quadratic parsing of flat selectors). - Fixed only in 7.1.6. 6.1.4, the last 6.x release, comes from Tailwind CSS 3 - (`tailwindcss` and its `postcss-nested`), a devDependency that requires the - 6.x line. Forcing 7.x on it would be an incompatible major-version override. - It runs at build time over the app's own stylesheets and never parses email - or user CSS. +Reviewed 2026-11-19: `pnpm audit --audit-level=high` exits 0 with **no ignore +list**, and the full report shows no high or critical advisory. The list was +emptied because GitHub withdrew both advisories it held, so there is nothing +left to accept: + +- [CVE-2026-93748](https://github.com/advisories/GHSA-ch52-4w7c-c8xp), + `http-cache-semantics` <= 4.2.0, withdrawn 2026-10-28. It was reached only + through the build tool `electron-builder`. +- [CVE-2026-93687](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm), + `braces` <= 3.0.3, withdrawn 2026-10-23. It was reached only through + tooling (ESLint, Tailwind, Metro, Jest). + +[GHSA-fc5q-39xc-vjpf](https://github.com/advisories/GHSA-fc5q-39xc-vjpf) +(`picomatch` <= 4.0.7, high, no fixed version) failed the gate until GitHub +withdrew it on 2026-11-18, so no entry was added for it. If a withdrawn advisory +is ever reinstated, the gate fails again and it is reviewed here like any other. + +The one advisory in a package the app ships was fixed by upgrading: +[GHSA-474x-hrwr-fgx4](https://github.com/advisories/GHSA-474x-hrwr-fgx4) +(low, quadratic CPU when scanning unterminated stop-node tags) in +`fast-xml-parser` <= 5.11.2, which reads the text of office attachments for the +Inbox Agent. The app configures no stop nodes, so 1.4.11 and earlier never ran +the affected code; the dependency and its override now require 5.12.0 or later. + +Moderate, no fixed version these tools accept (below the gate, so not in +`ignoreCves`; listed so the full report holds no surprises): + +- [CVE-2026-118773](https://github.com/advisories/GHSA-3g3m-2fjr-6pw4), + `glob` 9.0.0 to 14.0.1 (an aborted walk can keep reading the filesystem + after its `AbortSignal` fires). Fixed only in 14.0.2. 13.0.6 comes from + `@electron/asar` and `@sentry/vite-plugin`, both desktop devDependencies used + while packaging. They walk the project's own build output and never cancel a + walk to bound untrusted input. +- [CVE-2026-118764](https://github.com/advisories/GHSA-g3hv-75wg-m249), + `minimatch` 7.0.0 to 11.0.0 (denial of service through globparts + amplification). Fixed only in 11.0.1. 9.0.9 comes from `@typescript-eslint` + 6 (lint) and `electron-builder` → `@electron/universal`; 10.2.6 from + `@electron/asar`, `electron-builder` → `app-builder-lib` and + `@sentry/bundler-plugins`. Every pattern is one the project's own build or + lint configuration supplies; none comes from mail or the user. + +Forcing either onto its new major line would be an incompatible major-version +override on those tools. Neither package is in the shipped app. + +The 2026-10-12 review also listed two moderates that are now gone: +[CVE-2026-97058](https://github.com/advisories/GHSA-hp3w-g68c-fv3c) +(`sprintf-js`) was withdrawn on 2026-10-22, and +[CVE-2026-104844](https://github.com/advisories/GHSA-rj75-hqrm-r3gf) +(`postcss-selector-parser`) gained a 6.x fix, 6.1.5, which the +`postcss-selector-parser@6` override already requires. The previous Vite exception (`CVE-2026-53571`) was removed: the desktop now uses Vite 8. The two `image-size` exceptions (`CVE-2025-71329` and diff --git a/apps/desktop/electron/ipc/accounts-handlers.ts b/apps/desktop/electron/ipc/accounts-handlers.ts index 524fb2da..69a5bddf 100644 --- a/apps/desktop/electron/ipc/accounts-handlers.ts +++ b/apps/desktop/electron/ipc/accounts-handlers.ts @@ -16,10 +16,9 @@ * is active on launch, so no account can grab the primary's database. */ import type { EmailRecord, SearchQuery, ViewFilter } from '@sarvinbox/core'; -import { createLogger, errorDiagnostic } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, errorDiagnostic, redactAccountIds } from '@sarvinbox/core'; import { ipcMain } from 'electron'; - import { settleRevocation, type AccountRevocation } from '../services/account-revocation'; import { listRegistryAccounts, @@ -197,7 +196,7 @@ export function registerAccountsHandlers(): void { try { keepAccountIds = readRegistryAccounts().map((a) => a.id); const removed = cleanupOrphanedAccountDbs({ keepAccountIds, staleAfterMs: 0 }); - if (removed.length) logger.info(`[Accounts] removal swept ${removed.length} orphan file(s):`, removed.join(', ')); + if (removed.length) logger.info(`[Accounts] removal swept ${removed.length} orphan file(s):`, redactAccountIds(removed.join(', '))); } catch (e) { logger.warn('[Accounts] orphan DB sweep after removal failed or was skipped:', (e as Error).message); } @@ -360,7 +359,7 @@ export function registerAccountsHandlers(): void { ]); return { emails: emails.map((e) => ({ ...e, accountId })), total }; } catch (e) { - logger.warn('[Accounts] unifiedInbox: skipping account', accountId, (e as Error).message); + logger.warn('[Accounts] unifiedInbox: skipping account', accountLogLabel(accountId), (e as Error).message); return { emails: [], total: 0 }; } }), @@ -449,7 +448,7 @@ export function registerAccountsHandlers(): void { return { emails: emails.map((e) => ({ ...e, accountId })), total }; } catch (e) { // Class and code only: a search error can name the query's words. - logger.warn('[Accounts] unifiedSearch: skipping account', accountId, errorDiagnostic(e)); + logger.warn('[Accounts] unifiedSearch: skipping account', accountLogLabel(accountId), errorDiagnostic(e)); return { emails: [], total: 0 }; } }), diff --git a/apps/desktop/electron/ipc/agent-handlers.ts b/apps/desktop/electron/ipc/agent-handlers.ts index 1eccced6..47363c24 100644 --- a/apps/desktop/electron/ipc/agent-handlers.ts +++ b/apps/desktop/electron/ipc/agent-handlers.ts @@ -6,7 +6,7 @@ */ import type { UserActionType, ActionSource } from '@sarvinbox/core'; -import { createLogger, setEmailReadFlag } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, setEmailReadFlag } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { openAccountStorages, requireNamedOrActiveStorage, requireTargetAccountId } from '../services/account-target'; @@ -97,9 +97,9 @@ function runBackfillForNewAccounts(limit: number): void { const n = (store as any).getRepositories().agent.requeueRecentInboxForAgent(limit); done.push(id); changed = true; - logger.info(`[Agent] AI Assist on — re-queued ${n} existing Inbox emails for account ${id}`); + logger.info(`[Agent] AI Assist on — re-queued ${n} existing Inbox emails for account ${accountLogLabel(id)}`); } catch (e) { - logger.error(`[Agent] backfill re-queue failed for account ${id}:`, e); + logger.error(`[Agent] backfill re-queue failed for account ${accountLogLabel(id)}:`, e); } } if (changed) saveAgentConfig({ backfillRequeuedAccounts: done }); diff --git a/apps/desktop/electron/ipc/ai-handlers.ts b/apps/desktop/electron/ipc/ai-handlers.ts index ffddb6af..d5dd1463 100644 --- a/apps/desktop/electron/ipc/ai-handlers.ts +++ b/apps/desktop/electron/ipc/ai-handlers.ts @@ -5,6 +5,9 @@ */ import { + failureCause, + folderLogLabel, + accountLogLabel, conversationSenders, createLogger, errorDiagnostic, @@ -99,7 +102,7 @@ export async function clearFirstSplitsInEveryAccount(): Promise { failedAccounts.push(accountId); - logger.warn(`firstSplit:clearAll failed for account ${accountId}: ${(error as Error)?.message ?? error}`); + logger.warn(`firstSplit:clearAll failed for account ${accountLogLabel(accountId)}: ${failureCause(error)}`); }; const add = (counts: FirstSplitClearCounts): void => { cleared += counts.removed; @@ -189,7 +192,7 @@ export function registerAIHandlers(): void { const emails = await storage.getEmailsByDynamicCategory(category, { limit, offset, folderId }); return { success: true, data: emails }; } catch (error) { - logger.error('AI getByCategory error:', error); + logger.error('AI getByCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } } @@ -204,7 +207,7 @@ export function registerAIHandlers(): void { const counts = storage.getDynamicCategoryCounts(folderId, mode); return { success: true, data: counts }; } catch (error) { - logger.error('AI getCategoryCounts error:', error); + logger.error('AI getCategoryCounts error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -218,7 +221,7 @@ export function registerAIHandlers(): void { const defs = storage.getCategoryDefinitions(); return { success: true, data: defs }; } catch (error) { - logger.error('AI getCategoryDefinitions error:', error); + logger.error('AI getCategoryDefinitions error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -246,7 +249,7 @@ export function registerAIHandlers(): void { } return { success: true, data: merged }; } catch (error) { - logger.error('AI getEmailCategoriesBatch error:', error); + logger.error('AI getEmailCategoriesBatch error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -266,7 +269,7 @@ export function registerAIHandlers(): void { void onCategoryDefinitionUpserted(oldName, def?.name); return { success: true }; } catch (error) { - logger.error('AI upsertCategoryDefinition error:', error); + logger.error('AI upsertCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -280,7 +283,7 @@ export function registerAIHandlers(): void { const deleted = storage.deleteCategoryDefinition(slug); return { success: true, data: { deleted } }; } catch (error) { - logger.error('AI deleteCategoryDefinition error:', error); + logger.error('AI deleteCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -294,7 +297,7 @@ export function registerAIHandlers(): void { storage.toggleCategoryDefinition(slug, enabled); return { success: true }; } catch (error) { - logger.error('AI toggleCategoryDefinition error:', error); + logger.error('AI toggleCategoryDefinition error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -308,7 +311,7 @@ export function registerAIHandlers(): void { const summary = await storage.getThreadSummary(threadId); return { success: true, data: summary }; } catch (error) { - logger.error('AI getThreadSummary error:', error); + logger.error('AI getThreadSummary error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -322,7 +325,7 @@ export function registerAIHandlers(): void { await storage.upsertThreadSummary(summary); return { success: true }; } catch (error) { - logger.error('AI saveThreadSummary error:', error); + logger.error('AI saveThreadSummary error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -335,7 +338,7 @@ export function registerAIHandlers(): void { const storage = await requireAccountStorage(accountId); return { success: true, data: readFirstSplit(storage, threadId, !!options?.withSource) }; } catch (error) { - logger.warn(`firstSplit:get failed acct=${accountId} thread=${threadId}: ${(error as Error).message}`); + logger.warn(`firstSplit:get failed acct=${accountLogLabel(accountId)} thread=${threadId}: ${failureCause(error)}`); return { success: false, error: (error as Error).message }; } }, @@ -347,11 +350,11 @@ export function registerAIHandlers(): void { const storage = await requireAccountStorage(accountId); const result = storage.saveFirstSplit(request); if (result.reason === 'invalid') { - logger.warn(`firstSplit:save refused an invalid payload acct=${accountId} thread=${request?.key?.threadId ?? '?'} status=${request?.status ?? '?'}`); + logger.warn(`firstSplit:save refused an invalid payload acct=${accountLogLabel(accountId)} thread=${request?.key?.threadId ?? '?'} status=${request?.status ?? '?'}`); } return { success: true, data: result }; } catch (error) { - logger.warn(`firstSplit:save failed acct=${accountId} thread=${request?.key?.threadId ?? '?'}: ${(error as Error).message}`); + logger.warn(`firstSplit:save failed acct=${accountLogLabel(accountId)} thread=${request?.key?.threadId ?? '?'}: ${failureCause(error)}`); return { success: false, error: (error as Error).message }; } }); @@ -365,9 +368,8 @@ export function registerAIHandlers(): void { } catch (error) { // Only the registry read can throw here: which accounts exist is unknown, // so nothing may be reported as cleared. - const message = (error as Error)?.message ?? String(error); - logger.warn(`firstSplit:clearAll could not read the account list: ${message}`); - return { success: false, error: `Could not read the account list: ${message}` }; + logger.warn(`firstSplit:clearAll could not read the account list: ${failureCause(error)}`); + return { success: false, error: `Could not read the account list: ${(error as Error)?.message ?? String(error)}` }; } }); @@ -380,7 +382,7 @@ export function registerAIHandlers(): void { await storage.upsertEmailAICategory(category); return { success: true }; } catch (error) { - logger.error('AI saveCategory error:', error); + logger.error('AI saveCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -394,7 +396,7 @@ export function registerAIHandlers(): void { await storage.removeEmailAICategory(emailId); return { success: true }; } catch (error) { - logger.error('AI removeCategory error:', error); + logger.error('AI removeCategory error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -408,7 +410,7 @@ export function registerAIHandlers(): void { const emails = await storage.getEmailsWithoutAICategory(limit); return { success: true, data: emails }; } catch (error) { - logger.error('AI getUnprocessedEmails error:', error); + logger.error('AI getUnprocessedEmails error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -422,7 +424,7 @@ export function registerAIHandlers(): void { const saved = storage.upsertCategoryBatch(categories); return { success: true, data: { saved } }; } catch (error) { - logger.error('AI saveCategoriesBatch error:', error); + logger.error('AI saveCategoriesBatch error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -436,7 +438,7 @@ export function registerAIHandlers(): void { const count = await storage.getUnprocessedEmailCount(limit, skipRead); return { success: true, data: count }; } catch (error) { - logger.error('AI getUnprocessedEmailCount error:', error); + logger.error('AI getUnprocessedEmailCount error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -484,7 +486,7 @@ export function registerAIHandlers(): void { try { return { success: true, data: { cap: setAutoBacklogCap(cap) } }; } catch (error) { - logger.error('AI setBacklogCap error:', error); + logger.error('AI setBacklogCap error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -531,7 +533,7 @@ export function registerAIHandlers(): void { const repo = (storage as any).getRepositories?.()?.prompts; return { success: true, data: repo?.list?.() || [] }; } catch (error) { - logger.error('AI listPromptTemplates error:', error); + logger.error('AI listPromptTemplates error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -546,7 +548,7 @@ export function registerAIHandlers(): void { const updated = repo?.update?.(id, content) || false; return { success: updated }; } catch (error) { - logger.error('AI updatePromptTemplate error:', error); + logger.error('AI updatePromptTemplate error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -558,7 +560,7 @@ export function registerAIHandlers(): void { const reset = repo?.reset?.(id) || false; return { success: reset }; } catch (error) { - logger.error('AI resetPromptTemplate error:', error); + logger.error('AI resetPromptTemplate error:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } }); @@ -645,7 +647,7 @@ export function registerAIHandlers(): void { sortOrder: 'desc', }); - logger.info(`[AI Search] Found ${emails.length} results (folder=${folderPath || 'all'}, aiCategory=${searchQuery.aiCategory ? 'set' : 'none'})`); + logger.info(`[AI Search] Found ${emails.length} results (folder=${folderPath ? folderLogLabel(folderPath) : 'all'}, aiCategory=${searchQuery.aiCategory ? 'set' : 'none'})`); return { success: true, data: emails }; } catch (error) { // A full-text search error names the query's tokens: class and code only. diff --git a/apps/desktop/electron/ipc/contacts-handlers.ts b/apps/desktop/electron/ipc/contacts-handlers.ts index 8416d201..1ddd608a 100644 --- a/apps/desktop/electron/ipc/contacts-handlers.ts +++ b/apps/desktop/electron/ipc/contacts-handlers.ts @@ -4,7 +4,7 @@ * Handles contact management operations. */ -import { classifyDomainPhones, classifyDomainUrls, htmlMiningWindow, htmlToPlainText, isSentMailFolder, mineAttributedPhones, mineContactSignals, phoneDomainOf, parseAddresses, type SenderPhones, type SenderUrls, createLogger } from '@sarvinbox/core'; +import { folderLogLabel, accountLogLabel, classifyDomainPhones, classifyDomainUrls, htmlMiningWindow, htmlToPlainText, isSentMailFolder, mineAttributedPhones, mineContactSignals, phoneDomainOf, parseAddresses, type SenderPhones, type SenderUrls, createLogger } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { refreshContactClassifications } from '../services/contact-classification-service'; @@ -447,7 +447,7 @@ async function scanMailbox( // Report what was actually read, not the paging offset — a folder holding // one email used to log "500 emails" because `offset` jumps by batchSize. - logger.info(`[Contacts] ${label}: scanned folder "${folder.name}": ${inFolder} emails (${direction})`); + logger.info(`[Contacts] ${label}: scanned folder ${folderLogLabel(folder.path || folder.name)}: ${inFolder} emails (${direction})`); } // Write the tallied totals absolutely, so re-scanning converges instead of @@ -680,7 +680,7 @@ export function registerContactsHandlers(): void { } catch (err) { // One mailbox failing (a locked DB mid-sync, usually transient) must // not cost the scan every OTHER account's contacts. - logger.error(`[Contacts] Scan skipped mailbox ${accountId}:`, err); + logger.error(`[Contacts] Scan skipped mailbox ${accountLogLabel(accountId)}:`, err); } } diff --git a/apps/desktop/electron/ipc/draft-handlers.ts b/apps/desktop/electron/ipc/draft-handlers.ts index 5a05a44d..1a10c040 100644 --- a/apps/desktop/electron/ipc/draft-handlers.ts +++ b/apps/desktop/electron/ipc/draft-handlers.ts @@ -6,7 +6,7 @@ import { basename } from 'path'; -import { emailContentHash, errorDiagnostic, resolveStandardFolder, createLogger, messageIdKey, withFolderSelected } from '@sarvinbox/core'; +import { folderLogLabel, emailContentHash, errorDiagnostic, resolveStandardFolder, createLogger, messageIdKey, withFolderSelected } from '@sarvinbox/core'; import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, accountDraftRowSql, bodyLengthFromParam, cleanBodyExpression, rawBodyExpression, rawBodyForStorage, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, type IpcMainInvokeEvent } from 'electron'; @@ -421,7 +421,7 @@ export async function saveDraftToIMAP(draft: { draftLog('save:uid-update:error', { error: errorDiagnostic(e) }); } } - logger.info('[Drafts] Draft saved to IMAP', folderPath, messageId, 'uid', appendedUid); + logger.info('[Drafts] Draft saved to IMAP', folderLogLabel(folderPath), messageId, 'uid', appendedUid); } catch (err: any) { logger.error('[Drafts] IMAP append failed (local copy kept):', err); return { success: true, folderPath, messageId, error: `IMAP append failed: ${err?.message || err}` }; @@ -465,7 +465,7 @@ export async function writeLocalDraftRow(storage: ReturnType 0) { uid = uids[0]; } else { - logger.warn(`[Main] Message-ID ${msgId} not found in ${sourceFolder.path}, skipping IMAP ${mode}`); + logger.warn(`[Main] Message-ID ${msgId} not found in ${folderLogLabel(sourceFolder.path)}, skipping IMAP ${mode}`); return; } } finally { @@ -2089,7 +2089,7 @@ export function registerEmailHandlers(): void { const deletable = items.filter((i) => typeof i.uid === 'number' && i.uid > 0); failedIds.push(...items.filter((i) => !deletable.includes(i)).map((i) => i.id)); if (deletable.length < items.length) { - logger.warn(`[bulkAction] ${folderPath}: ${items.length - deletable.length} uid-less row(s) left in place for delete (no server UID — avoids a local/server mismatch)`); + logger.warn(`[bulkAction] ${folderLogLabel(folderPath)}: ${items.length - deletable.length} uid-less row(s) left in place for delete (no server UID — avoids a local/server mismatch)`); } // Permanent expunge ONLY when the source folder truly IS Trash (exact // classification, never a `path.includes('trash')` substring that @@ -2122,7 +2122,7 @@ export function registerEmailHandlers(): void { catch (error) { logger.error('[Main] Accepted bulk delete local cleanup failed:', error); } } else { if (isTrash && allowPermanent !== true) { - logger.warn(`[bulkAction] delete in ${folderPath}: permanent expunge NOT confirmed by renderer — moving to Trash instead (no silent data loss)`); + logger.warn(`[bulkAction] delete in ${folderLogLabel(folderPath)}: permanent expunge NOT confirmed by renderer — moving to Trash instead (no silent data loss)`); } // Find trash folder for local DB update (exact classification). const trashFolder = findFolderByType(allFolders as any, 'trash') as any; diff --git a/apps/desktop/electron/ipc/image-trust-handlers.ts b/apps/desktop/electron/ipc/image-trust-handlers.ts index 6f6c243d..dd606e85 100644 --- a/apps/desktop/electron/ipc/image-trust-handlers.ts +++ b/apps/desktop/electron/ipc/image-trust-handlers.ts @@ -11,7 +11,7 @@ * A named account is therefore resolved strictly (an unknown one is an error * the renderer sees and retries); no id means the active account, as before. */ -import { createLogger } from '@sarvinbox/core'; +import { accountLogLabel, createLogger } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { requireNamedOrActiveStorage } from '../services/account-target'; @@ -27,7 +27,7 @@ export function registerImageTrustHandlers(): void { await (await requireNamedOrActiveStorage(accountId)).allowSenderImages(address); return { success: true }; } catch (error) { - logger.warn(`images:allowSender failed for account ${accountId ?? '(active)'}: ${(error as Error)?.message ?? error}`); + logger.warn(`images:allowSender failed for account ${accountLogLabel(accountId, '(active)')}: ${(error as Error)?.message ?? error}`); return fail(error); } }); diff --git a/apps/desktop/electron/ipc/label-handlers.ts b/apps/desktop/electron/ipc/label-handlers.ts index 5acf4bf5..df5427ed 100644 --- a/apps/desktop/electron/ipc/label-handlers.ts +++ b/apps/desktop/electron/ipc/label-handlers.ts @@ -6,7 +6,7 @@ * Local-only, like AI-category tags — no IMAP keyword sync. */ -import { createLogger, type LabelInput } from '@sarvinbox/core'; +import { failureCause, labelLogLabel, createLogger, type LabelInput } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { ensureAccountRuntime } from '../services/accounts-runtime'; @@ -62,10 +62,10 @@ export function registerLabelHandlers(): void { if (engine?.isConnected?.()) { syncedToServer = await engine.createServerLabel(name); } else { - logger.warn(`[labels] syncToServer requested for "${name}" but the account isn't connected — created local-only`); + logger.warn(`[labels] syncToServer requested for ${labelLogLabel(name)} but the account isn't connected — created local-only`); } } catch (e) { - logger.warn(`[labels] server CREATE for "${name}" failed — created local-only: ${(e as Error).message}`); + logger.warn(`[labels] server CREATE for ${labelLogLabel(name)} failed — created local-only: ${failureCause(e)}`); } } return { success: true, data: await storage.createLabel({ name, color: input.color }, syncedToServer) }; diff --git a/apps/desktop/electron/ipc/smtp-handlers.ts b/apps/desktop/electron/ipc/smtp-handlers.ts index 36fae5b8..d47bcab9 100644 --- a/apps/desktop/electron/ipc/smtp-handlers.ts +++ b/apps/desktop/electron/ipc/smtp-handlers.ts @@ -7,7 +7,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import { SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, withFolderSelected, messageIdKey, parseAddresses, STARTTLS_UNAVAILABLE, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; +import { folderLogLabel, SMTPClient, emailContentHash, resolveStandardFolder, providerAutoSavesSentCopy, isAuthTokenError, isStarttlsRefusedError, withFolderSelected, messageIdKey, parseAddresses, STARTTLS_UNAVAILABLE, type SMTPConfig, type SendEmailOptions, createLogger } from '@sarvinbox/core'; import { PGP_ENCRYPTED_PLACEHOLDER } from '@sarvinbox/core/pgp'; import { UPSERT_BODY_SQL, bodyLengthFromParam, relocateBodyForInsert, writeImageLinks, writeThreadKey } from '@sarvinbox/storage-node'; import { ipcMain, dialog } from 'electron'; @@ -744,7 +744,7 @@ export async function appendSentCopy( } else { await run((syncEngine as any).getClient()); } - logger.info('[SMTP] Sent copy appended (UID stamped by the next Sent sync)', sentPath, messageId); + logger.info('[SMTP] Sent copy appended (UID stamped by the next Sent sync)', folderLogLabel(sentPath), messageId); } /** diff --git a/apps/desktop/electron/ipc/sync-handlers.ts b/apps/desktop/electron/ipc/sync-handlers.ts index 2ba2af36..bc199411 100644 --- a/apps/desktop/electron/ipc/sync-handlers.ts +++ b/apps/desktop/electron/ipc/sync-handlers.ts @@ -5,7 +5,7 @@ */ import type { IMAPConfig, SyncEngineOptions } from '@sarvinbox/core'; -import { withTimeout, transportOptInsOf, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, STARTTLS_UNAVAILABLE } from '@sarvinbox/core'; +import { failureCause, folderLogLabel, accountLogLabel, withTimeout, transportOptInsOf, limitTransport, ImapFlowClient, isAuthError, isQuotaError, isStartTlsUnavailableError, isTerminalOAuthError, createLogger, LogAggregator, planFolderDrift, applyFolderDrift, STARTTLS_UNAVAILABLE } from '@sarvinbox/core'; import { ipcMain } from 'electron'; import { identifyClient } from '../sentry'; @@ -259,14 +259,14 @@ async function reconcileFolderDrift( : polled; if (plan.reconcileFlags) { logger.info( - `[Accounts] flag drift in ${f.path} (server unseen ${st.unseen ?? 0}, ` + + `[Accounts] flag drift in ${folderLogLabel(f.path)} (server unseen ${st.unseen ?? 0}, ` + `modseq ${st.highestModseq ?? '-'} vs synced ${f.highestModseq ?? '-'}) — reconciling`, ); } else if (plan.recountFromRows) { // Named in the log: a badge that outlived its mail is invisible from the // outside, and this line is the only place it leaves a trace. logger.info( - `[Accounts] unread badge for ${f.path} disagrees with the server ` + + `[Accounts] unread badge for ${folderLogLabel(f.path)} disagrees with the server ` + `(stored ${f.unreadCount ?? 0} thread(s) vs server unseen ${st.unseen ?? 0}) — recounting from rows`, ); } @@ -297,7 +297,7 @@ async function reconcileFolderDrift( // renderer re-runs that folder's list query, not just the badges. notify: (path) => sendToWindow('folders:updated', { accountId, folderPath: path }), onError: (stage, path, error) => - logger.warn(`[Accounts] ${stage} reconcile failed for`, path, error.message), + logger.warn(`[Accounts] ${stage} reconcile failed for`, folderLogLabel(path), failureCause(error)), }); } catch { /* skip this folder */ } } @@ -394,7 +394,7 @@ export function registerSyncHandlers(): void { if (!getSyncEngine() && accountId && accountDbExists(accountId)) { await ensureAccountRuntime(accountId); setCurrentAccount(accountId); - logger.info(`[Main] imap:connect self-activated account ${accountId} (storage was uninitialized)`); + logger.info(`[Main] imap:connect self-activated account ${accountLogLabel(accountId)} (storage was uninitialized)`); } const syncEngine = requireSyncEngine(); const storage = getStorage(); @@ -416,7 +416,6 @@ export function registerSyncHandlers(): void { // Attribute every subsequent error/breadcrumb to this client + mailbox. // Set BEFORE connecting so a failed connect is also attributed correctly. identifyClient({ - email: config.username, provider: config.oauthProvider ?? 'imap', host: config.host, port: config.port, @@ -892,7 +891,7 @@ export function registerSyncHandlers(): void { const activeId = getCurrentAccountId(); const parkedMs = quotaBackoff.remainingMs(activeId); if (parkedMs > 0) { - logger.info(`[Main] resetAndReconnect skipped — quota back-off active for ${activeId} (server connection cap); ${Math.round(parkedMs / 1000)}s left`); + logger.info(`[Main] resetAndReconnect skipped — quota back-off active for ${accountLogLabel(activeId)} (server connection cap); ${Math.round(parkedMs / 1000)}s left`); return { success: true, data: { connected: syncEngine.isConnected() } }; } @@ -1196,7 +1195,7 @@ export function registerSyncHandlers(): void { const mode = await syncEngine.startRealTime(folderPath); if (mode) { - logger.info(`[Main] Real-time sync started using: ${mode} for ${folderPath}`); + logger.info(`[Main] Real-time sync started using: ${mode} for ${folderLogLabel(folderPath)}`); } return { success: true, data: !!mode, mode }; @@ -1345,9 +1344,9 @@ export function registerSyncHandlers(): void { registerIdleBridges(accountId, engine); try { const mode = await engine.startRealTime('INBOX'); - logger.info('[IDLE] backgroundSync re-armed IDLE (socket alive) for', accountId, '→', mode); + logger.info('[IDLE] backgroundSync re-armed IDLE (socket alive) for', accountLogLabel(accountId), '→', mode); } catch (e) { - logger.warn('[IDLE] backgroundSync IDLE re-arm failed for', accountId, (e as Error).message); + logger.warn('[IDLE] backgroundSync IDLE re-arm failed for', accountLogLabel(accountId), (e as Error).message); } return { success: true, data: { unread: await totalUnread(rt.storage), live: true, reidled: true } }; } @@ -1382,7 +1381,7 @@ export function registerSyncHandlers(): void { // that config for auto-reconnect to hammer). Skip this cycle; the next // background tick retries once the vault is readable. if (cfg.authMethod !== 'oauth2' && !cfg.password) { - logger.warn(`[Accounts] backgroundSync: no password available yet for ${accountId} — skipping connect this cycle`); + logger.warn(`[Accounts] backgroundSync: no password available yet for ${accountLogLabel(accountId)} — skipping connect this cycle`); return { success: false, error: 'Credentials not ready', retryable: true }; } const dialConfig = attachImapBearer(cfg); @@ -1414,7 +1413,7 @@ export function registerSyncHandlers(): void { 'Background sync timed out', ); } catch (e) { - logger.warn('[Accounts] background INBOX catch-up sync failed (going LIVE anyway) for', accountId, (e as Error).message); + logger.warn('[Accounts] background INBOX catch-up sync failed (going LIVE anyway) for', accountLogLabel(accountId), (e as Error).message); } // STATUS-then-reconcile sweep across this account's non-INBOX folders (fresh @@ -1423,7 +1422,7 @@ export function registerSyncHandlers(): void { try { await reconcileFolderDrift(engine, rt.storage, accountId); } catch (e) { - logger.warn('[Accounts] STATUS sweep failed for', accountId, (e as Error).message); + logger.warn('[Accounts] STATUS sweep failed for', accountLogLabel(accountId), (e as Error).message); } // Go LIVE: tagged IDLE bridges + real-time push. Idempotent. @@ -1434,9 +1433,9 @@ export function registerSyncHandlers(): void { retryPipelineInitOnConnect(); try { const mode = await engine.startRealTime('INBOX'); - logger.info('[IDLE] backgroundSync startRealTime for', accountId, '→ mode:', mode); + logger.info('[IDLE] backgroundSync startRealTime for', accountLogLabel(accountId), '→ mode:', mode); } catch (e) { - logger.warn('[IDLE] startRealTime FAILED for', accountId, (e as Error).message); + logger.warn('[IDLE] startRealTime FAILED for', accountLogLabel(accountId), (e as Error).message); } return { success: true, data: { unread: await totalUnread(rt.storage) } }; @@ -1455,14 +1454,14 @@ export function registerSyncHandlers(): void { // saturated cap, which prolongs the lockout and risks a real rate-limit. const parked = quotaBackoff.parkOnError(accountId, error); if (parked.reason === 'quota') { - logger.warn(`[Accounts] backgroundSync: quota hit for ${accountId} (too many connections) — backing off ${Math.round(parked.backoffMs / 1000)}s (attempt ${parked.attempt})`); + logger.warn(`[Accounts] backgroundSync: quota hit for ${accountLogLabel(accountId)} (too many connections) — backing off ${Math.round(parked.backoffMs / 1000)}s (attempt ${parked.attempt})`); return { success: false, error: (error as Error).message, quotaExceeded: true }; } if (parked.reason === 'timeout') { - logger.warn(`[Accounts] backgroundSync: connect timed out for ${accountId} — backing off ${Math.round(parked.backoffMs / 60000)}m`); + logger.warn(`[Accounts] backgroundSync: connect timed out for ${accountLogLabel(accountId)} — backing off ${Math.round(parked.backoffMs / 60000)}m`); return { success: false, error: (error as Error).message }; } - logger.warn('[Accounts] backgroundSync failed for', accountId, (error as Error).message); + logger.warn('[Accounts] backgroundSync failed for', accountLogLabel(accountId), (error as Error).message); return { success: false, error: (error as Error).message }; } }); diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index ffa3e232..cdb37c45 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -22,7 +22,7 @@ import netModule from 'net'; import { join } from 'path'; import { pathToFileURL } from 'url'; -import { SyncEngine, ExtensionManager, createLogger, errorDiagnostic, getEventBus, getLogLevel, setLogLevel, isConnectionError, raiseAutoSelectFamilyAttemptTimeout } from '@sarvinbox/core'; +import { accountLogLabel, SyncEngine, ExtensionManager, createLogger, errorDiagnostic, getEventBus, getLogLevel, setLogLevel, isConnectionError, raiseAutoSelectFamilyAttemptTimeout } from '@sarvinbox/core'; import { SQLiteStorage } from '@sarvinbox/storage-node'; import { app, BrowserWindow, Menu, dialog, ipcMain, powerMonitor, protocol, session, shell } from 'electron'; @@ -163,10 +163,12 @@ import { devServerUrlFor, isDevBuild, isReleaseBundle } from './utils/dev-mode'; import { initFileLogger, flushFileLogger, muteTerminalOutput, appendExternalLog } from './utils/file-logger'; import { installIpcSenderGuard } from './utils/ipc-sender-guard'; import { loadDotEnv, defaultDotEnvPaths } from './utils/load-env'; +import { logPath } from './utils/log-path'; import { mainWindowWebPreferences } from './utils/main-window-preferences'; import { installNavigationGuards } from './utils/navigation-guards'; import { installPermissionPolicy } from './utils/permission-policy'; import { restoreAndFocusWindow } from './utils/window-focus'; +import { appJsFlags } from './v8-flags'; // App identity MUST be set before ANYTHING reads app.getPath('userData') — // initSentryMain(), the file logger, and the DB key store all derive their paths @@ -423,7 +425,8 @@ if (process.platform === 'darwin') { // Disable security warnings in development process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'; -// Increase Node.js memory limit to 2GB. +// V8's heap limit, 2 GB, for main and (the switch propagates) every renderer, +// the extension sandboxes included: see v8-flags.ts. // Opt-in diagnostic: set SARV_PROFILE=1 (dev only) to also turn on V8's tick // profiler (--prof). Use it to find a synchronous main-thread CPU hog (a // renderer freeze / beachball): the switch propagates to renderer processes @@ -434,7 +437,7 @@ const V8_PROFILE = isDev && process.env['SARV_PROFILE'] ? ` --prof --logfile=${join(app.getPath('userData'), 'v8prof-%p.log')}` : ''; -app.commandLine.appendSwitch('js-flags', `--max-old-space-size=2048${V8_PROFILE}`); +app.commandLine.appendSwitch('js-flags', appJsFlags(V8_PROFILE)); // Suppress EGL/GPU driver error messages app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds'); @@ -643,7 +646,7 @@ async function initializeStorage(): Promise { send: sendToWindow, accountId: () => getAccountIdForStorage(storage), }); - logger.info('[Main] Storage initialized:', dbPath); + logger.info('[Main] Storage initialized:', logPath(dbPath)); } /** @@ -759,14 +762,14 @@ async function initializeAccountRegistry(): Promise { // mailbox for an id whose data isn't on disk. const isPrimary = loadPrimaryAccountId() === activeId && legacyDbExists(); if (!isPrimary && !accountDbExists(activeId)) { - logger.info('[Main] Persisted active account has no DB yet — deferring to renderer:', activeId); + logger.info('[Main] Persisted active account has no DB yet — deferring to renderer:', accountLogLabel(activeId)); return; } setCurrentAccount(activeId); if (!hasAccountRuntime(activeId)) await ensureAccountRuntime(activeId); rebindOutboxStorage(); - logger.info('[Main] Auto-activated persisted account:', activeId); + logger.info('[Main] Auto-activated persisted account:', accountLogLabel(activeId)); } catch (e) { logger.warn('[Main] Auto-activate persisted account failed:', (e as Error)?.message); } diff --git a/apps/desktop/electron/sentry.ts b/apps/desktop/electron/sentry.ts index 784aa016..c2d25e5a 100644 --- a/apps/desktop/electron/sentry.ts +++ b/apps/desktop/electron/sentry.ts @@ -33,7 +33,6 @@ * repo-root .env. A Sentry DSN is public by design (safe to embed in a shipped * client). With no DSN configured, Sentry stays completely inert. */ -import { createHash } from 'crypto'; import { rmSync } from 'fs'; import { join } from 'path'; @@ -42,7 +41,7 @@ import { setSlowQueryReporter, type SlowQueryEvent } from '@sarvinbox/storage-no import * as Sentry from '@sentry/electron/main'; import { app } from 'electron'; -import { readCrashReportChoice, writeCrashReportChoice, type CrashReportChoice } from './services/crash-report-pref'; +import { crashReportInstallId, readCrashReportChoice, writeCrashReportChoice, type CrashReportChoice } from './services/crash-report-pref'; let sentryEnabled = false; /** @@ -271,6 +270,11 @@ export function initSentryMain(): void { sentryEnabled = true; + // Which installation a report came from: a random id, never anything derived + // from the user's address (see crashReportInstallId). Nothing is sent + // without a yes, whatever is set here. + Sentry.setUser({ id: crashReportInstallId() }); + // Tag runtime versions/platform so we can slice issues by build & OS. The // OS/device/electron contexts are added automatically by @sentry/electron; // these are the app-specific bits worth filtering on. @@ -313,27 +317,22 @@ export function initSentryMain(): void { } /** - * Identify which client an event came from, and tag the mailbox it was talking - * to. Called on every successful IMAP connect. No-op when Sentry is disabled. + * Tag the mailbox server an event's client was talking to. Called on every + * IMAP connect. No-op when Sentry is disabled. * - * We DON'T send the raw email address (PII). Instead the user id is a stable, - * one-way hash of the email — it still groups a given client's events together - * for support, but the address itself never leaves the machine. Provider + host - * are infrastructure identifiers (not personal) and are kept for triage. + * Takes no address: the report's user is the installation's random id, set + * once at init (see crashReportInstallId). It used to be a hash of the + * address, which a guess at the address confirms. Provider + host are + * infrastructure identifiers (not personal) and are kept for triage. */ export function identifyClient(params: { - email?: string; provider?: string; host?: string; port?: number; }): void { if (!sentryEnabled) return; - const { email, provider, host, port } = params; + const { provider, host, port } = params; - if (email) { - const id = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16); - Sentry.setUser({ id }); - } if (provider) Sentry.setTag('imap.provider', provider); if (host) Sentry.setTag('imap.host', host); Sentry.setContext('imap', { diff --git a/apps/desktop/electron/services/accounts-registry.ts b/apps/desktop/electron/services/accounts-registry.ts index 9cc04dec..cd053e45 100644 --- a/apps/desktop/electron/services/accounts-registry.ts +++ b/apps/desktop/electron/services/accounts-registry.ts @@ -15,10 +15,9 @@ import { existsSync, unlinkSync } from 'fs'; import { join } from 'path'; -import { accountIdFor, oauthImapPreset, createLogger, type OAuthProviderId } from '@sarvinbox/core'; +import { accountLogLabel, accountIdFor, oauthImapPreset, createLogger, type OAuthProviderId } from '@sarvinbox/core'; import { app } from 'electron'; - import { getAccountIdForStorage } from '../shared'; import { loadPrimaryAccountId } from './accounts-runtime'; @@ -313,7 +312,7 @@ export async function seedAccountRegistryFromDurableStores(): Promise { smtpConfigured: false, }); existing.add(id); - logger.info('[Registry] seeded account from imap-account store:', id); + logger.info('[Registry] seeded account from imap-account store:', accountLogLabel(id)); } } } catch (e) { @@ -344,7 +343,7 @@ export async function seedAccountRegistryFromDurableStores(): Promise { smtpConfigured: false, }); existing.add(id); - logger.info(`[Registry] seeded OAuth account from oauth store: ${id} (${oa.provider})`); + logger.info(`[Registry] seeded OAuth account from oauth store: ${accountLogLabel(id)} (${oa.provider})`); } } catch (e) { logger.warn('[Registry] oauth store seed skipped:', (e as Error)?.message); diff --git a/apps/desktop/electron/services/accounts-runtime.ts b/apps/desktop/electron/services/accounts-runtime.ts index 78f7b98c..b5a1e249 100644 --- a/apps/desktop/electron/services/accounts-runtime.ts +++ b/apps/desktop/electron/services/accounts-runtime.ts @@ -13,15 +13,13 @@ import { createHash } from 'crypto'; import { existsSync, readdirSync, readFileSync, renameSync, unlinkSync, statSync, openSync, readSync, closeSync } from 'fs'; import { join } from 'path'; - -import { SyncEngine, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, failureCause, redactAccountIds, SyncEngine, createLogger } from '@sarvinbox/core'; import { SHARED_CONTACTS_FILE, SQLiteStorage } from '@sarvinbox/storage-node'; import { app } from 'electron'; - import type { AccountRuntime } from '../shared'; import { claimDefaultRuntime, getAccountIdForStorage, getAccountRuntime, hasAccountRuntime, registerAccountRuntime, rekeyRuntime, sendToWindow, unregisterRuntime } from '../shared'; - +import { logPath } from '../utils/log-path'; import { listRegistryAccounts } from './accounts-registry'; import { deleteAccountAttachments, rekeyAccountAttachments } from './attachment-cache'; @@ -114,7 +112,7 @@ export async function createAccountRuntime( // second account does not double the queries sent about the same sender. attachReputation(syncEngine); attachAutocrypt(syncEngine); - logger.info('[Accounts] Created runtime ->', dbPath); + logger.info('[Accounts] Created runtime ->', logPath(dbPath)); return { storage, syncEngine, smtpClient: null }; } @@ -237,7 +235,7 @@ export async function ensureAccountRuntime(accountId: string): Promise await rekeyAccountSecrets(oldId, newId); if (loadPrimaryAccountId() === oldId) savePrimaryAccountId(newId); rekeyRuntime(oldId, newId); - logger.info('[AccountMigration] rekeyed account', oldId, '->', newId); + logger.info('[AccountMigration] rekeyed account', accountLogLabel(oldId), '->', accountLogLabel(newId)); } // ===== Account removal (wipe local data) =================================== @@ -331,7 +329,7 @@ function deleteDbFiles(dbFullPath: string): void { try { if (existsSync(p)) unlinkSync(p); } catch (e) { - logger.warn('[Accounts] Failed to delete DB file', p, e); + logger.warn('[Accounts] Failed to delete DB file', logPath(p), failureCause(e)); } } } @@ -406,7 +404,7 @@ export async function deleteAccountData(accountId: string): Promise { try { await deleteAccountSecrets(accountId); } catch (e) { logger.warn('[Accounts] vault delete failed', e); } // Its cached attachments too (CASA M-7): they used to outlive the account. try { await deleteAccountAttachments(accountId); } catch (e) { logger.warn('[Accounts] attachment cache delete failed', e); } - logger.info('[Accounts] wiped account data', accountId, isPrimary ? '(primary/sarvinbox.db)' : `(${dbFile})`); + logger.info('[Accounts] wiped account data', accountLogLabel(accountId), isPrimary ? '(primary/sarvinbox.db)' : `(${dbFile})`); } finally { // The account is gone, but the id must not stay marked: re-adding the same // address later resolves to the same id, and it would be unopenable. @@ -493,7 +491,7 @@ export function cleanupOrphanedAccountDbs(opts?: { try { entries = readdirSync(dir); } catch (e) { - logger.warn('[Accounts] cleanup: could not read userData dir', e); + logger.warn('[Accounts] cleanup: could not read userData dir', failureCause(e)); return removed; } for (const name of entries) { @@ -508,7 +506,7 @@ export function cleanupOrphanedAccountDbs(opts?: { if (keepFiles && !keepFiles.has(name) && isStale(name)) { deleteDbFiles(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed orphaned hashed account DB:', name); + logger.info('[Accounts] removed orphaned hashed account DB:', redactAccountIds(name)); } continue; } @@ -519,12 +517,12 @@ export function cleanupOrphanedAccountDbs(opts?: { // file is far more likely to be a store added since this code was // written than a stale one. Leave it and say so. if (!LEGACY_ACCOUNT.test(name)) { - logger.warn('[Accounts] cleanup: keeping unrecognised DB file (not an account DB):', name); + logger.warn('[Accounts] cleanup: keeping unrecognised DB file (not an account DB):', redactAccountIds(name)); continue; } deleteDbFiles(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed orphaned legacy DB:', name); + logger.info('[Accounts] removed orphaned legacy DB:', redactAccountIds(name)); continue; } // Oldest scheme: per-account DB named by the RAW account id with no @@ -535,9 +533,9 @@ export function cleanupOrphanedAccountDbs(opts?: { try { unlinkSync(join(dir, name)); removed.push(name); - logger.info('[Accounts] removed legacy plaintext account DB:', name); + logger.info('[Accounts] removed legacy plaintext account DB:', redactAccountIds(name)); } catch (e) { - logger.warn('[Accounts] could not remove legacy plaintext DB', name, e); + logger.warn('[Accounts] could not remove legacy plaintext DB', redactAccountIds(name), failureCause(e)); } } } @@ -569,7 +567,7 @@ export function cleanupStaleUserDataArtifacts(): string[] { unlinkSync(p); removed.push(name); } catch (e) { - logger.warn('[Accounts] could not remove stale artifact', name, (e as Error).message); + logger.warn('[Accounts] could not remove stale artifact', redactAccountIds(name), failureCause(e)); } }; @@ -583,7 +581,7 @@ export function cleanupStaleUserDataArtifacts(): string[] { } } catch { /* dir unreadable — nothing to do */ } - if (removed.length) logger.info('[Accounts] removed stale artifacts:', removed.join(', ')); + if (removed.length) logger.info('[Accounts] removed stale artifacts:', redactAccountIds(removed.join(', '))); return removed; } diff --git a/apps/desktop/electron/services/ai-categorization-service.ts b/apps/desktop/electron/services/ai-categorization-service.ts index cd20b66e..1a633e79 100644 --- a/apps/desktop/electron/services/ai-categorization-service.ts +++ b/apps/desktop/electron/services/ai-categorization-service.ts @@ -7,7 +7,7 @@ * Runs entirely in the Electron main process for reliability. */ -import { parseLLMJsonArray, valueShapeForLog, cleanEmailHtmlForLLM, errorDiagnostic, failureCause, isConnectionError, isUpstreamError, describeNetworkError, classifyAIError, createLogger, applySecurityGate, buildSecurityContext, formatSecurityLines, buildCategorizationPrompt, buildAIAuthHeaders, buildAIChatRequestOptions, effectiveAIBaseUrl, aiApiKeyHeaders, existingCategoryClassification, automaticCategorizationDeferred, isSpamProtectedEmail, formatSenderBehaviorFacts, SENDER_BEHAVIOR_UNAVAILABLE } from '@sarvinbox/core'; +import { categoryLogLabel, parseLLMJsonArray, valueShapeForLog, cleanEmailHtmlForLLM, errorDiagnostic, failureCause, isConnectionError, isUpstreamError, describeNetworkError, classifyAIError, createLogger, applySecurityGate, buildSecurityContext, formatSecurityLines, buildCategorizationPrompt, buildAIAuthHeaders, buildAIChatRequestOptions, effectiveAIBaseUrl, aiApiKeyHeaders, existingCategoryClassification, automaticCategorizationDeferred, isSpamProtectedEmail, formatSenderBehaviorFacts, SENDER_BEHAVIOR_UNAVAILABLE } from '@sarvinbox/core'; import type { EmailRecord , AIErrorInfo, EmailSecurityContext, SenderSignals } from '@sarvinbox/core'; import { getMainWindow, requireStorage } from '../shared'; @@ -186,6 +186,8 @@ export class AICategorizationService { private skipRead: boolean = true; private categoryDefs: LoadedCategoryDef[] = []; private categorySlugs: Set = new Set(); + /** The built-in categories' slugs: logged as written; the user's own are logged as labels. */ + private systemCategorySlugs: Set = new Set(['spam']); private autoTimer: ReturnType | null = null; private autoConfig: AIProviderConfig | null = null; private autoOptions: { userEmail?: string; maxEmails?: number; skipRead?: boolean } = {}; @@ -265,6 +267,7 @@ export class AICategorizationService { const defs = storage.getEnabledCategoryDefinitions(); this.categoryDefs = defs.map(d => ({ slug: d.slug, name: d.name, prompt: d.prompt })); this.categorySlugs = new Set(defs.map(d => d.slug)); + this.systemCategorySlugs = new Set(['spam', ...defs.filter(d => d.isSystem).map(d => d.slug)]); logger.info(`[AICategorizationService] Starting in ${mode} mode (skipRead=${this.skipRead}, maxEmails=${this.maxEmails}, categories=${this.categoryDefs.length})`); if (mode === 'bulk') { await this.processBulk(run); @@ -1171,7 +1174,8 @@ Return format (categories is an array of matching slugs from: ${categorySlugs}): for (const c of r.categories) acc[c] = (acc[c] || 0) + 1; return acc; }, {} as Record); - const categorySummary = Object.entries(categoryCounts).map(([k, v]) => `${k}:${v}`).join(' ') || 'none'; + // A category the user created is named after what they typed: its label, never its slug. + const categorySummary = Object.entries(categoryCounts).map(([k, v]) => `${categoryLogLabel(k, this.systemCategorySlugs)}:${v}`).join(' ') || 'none'; this.emitLog('info', `Saved ${saved} categorizations (${categorySummary})`); // Update progress with category breakdown and recent activity diff --git a/apps/desktop/electron/services/backfill-scheduler.ts b/apps/desktop/electron/services/backfill-scheduler.ts index 4ab9ea4e..c1cfb8b0 100644 --- a/apps/desktop/electron/services/backfill-scheduler.ts +++ b/apps/desktop/electron/services/backfill-scheduler.ts @@ -21,7 +21,7 @@ * - Idle tick: 30 min once every folder's backfill is complete */ -import { buildStandardFolderAliasMap, createLogger, getEventBus, isTrashFolder, isSpamFolder, isAllMailSuperset, LARGE_MAILBOX_THRESHOLD } from '@sarvinbox/core'; +import { failureCause, folderLogLabel, accountLogLabel, buildStandardFolderAliasMap, createLogger, getEventBus, isTrashFolder, isSpamFolder, isAllMailSuperset, LARGE_MAILBOX_THRESHOLD } from '@sarvinbox/core'; import { getStorage, getSyncEngine, getAllAccountRuntimes, getCurrentAccountId, sendToWindow } from '../shared'; @@ -352,10 +352,10 @@ async function maybeReconcileDeletions(storage: any, engine: any, folder: any): try { const r = await engine.reconcileFolderDeletionsFull(folder.path); if (r && r.deleted > 0) { - logger.info(`[Backfill] Deletion reconcile ${folder.path}: ${r.deleted} removed, ${r.updated} flags updated`); + logger.info(`[Backfill] Deletion reconcile ${folderLogLabel(folder.path)}: ${r.deleted} removed, ${r.updated} flags updated`); } } catch (e) { - logger.warn(`[Backfill] Deletion reconcile ${folder.path} failed (isolated): ${(e as Error).message}`); + logger.warn(`[Backfill] Deletion reconcile ${folderLogLabel(folder.path)} failed (isolated): ${failureCause(e)}`); } } @@ -395,7 +395,7 @@ async function runTick(): Promise { // connection self-heals and the next tick picks it up. if (isConnectionRecentlyUnstable(t.engine)) { drained = false; // still has work; just deferred until it settles - logger.info(`[Backfill] skipping ${t.accountId} — connection churning, letting it settle`); + logger.info(`[Backfill] skipping ${accountLogLabel(t.accountId)} — connection churning, letting it settle`); continue; } // One-time bulk backfill (idempotent, self-throttled, fire-and-forget) so diff --git a/apps/desktop/electron/services/body-reheal-scheduler.ts b/apps/desktop/electron/services/body-reheal-scheduler.ts index 157fcdcb..79d160e0 100644 --- a/apps/desktop/electron/services/body-reheal-scheduler.ts +++ b/apps/desktop/electron/services/body-reheal-scheduler.ts @@ -28,7 +28,7 @@ * entirely (never downloaded — the body-prefetch's job) and are dropped by a * cheap probe rather than spending the repair budget; see drainEmptyBodies. */ -import { createLogger, createLoopYielder, isDeferredFetchError, isFirstSplitCurrent, repairedCleanBody } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, createLoopYielder, isDeferredFetchError, isFirstSplitCurrent, repairedCleanBody } from '@sarvinbox/core'; import { areBodyLengthsReady, cleanBodyExpression, rawBodyExpression, rawBodyLengthExpression } from '@sarvinbox/storage-node'; import { getAllAccountRuntimes } from '../shared'; @@ -115,8 +115,8 @@ async function scanAccount(accountId: string, storage: any): Promise { queues.set(accountId, q); emptyQueues.set(accountId, emptyIds); scanned.add(accountId); - if (q.length > 0) logger.info(`Body re-heal: queued ${q.length} corrupted bodies for ${accountId}`); - if (emptyIds.length > 0) logger.info(`Body re-heal: queued ${emptyIds.length} empty clean bodies for local repair for ${accountId}`); + if (q.length > 0) logger.info(`Body re-heal: queued ${q.length} corrupted bodies for ${accountLogLabel(accountId)}`); + if (emptyIds.length > 0) logger.info(`Body re-heal: queued ${emptyIds.length} empty clean bodies for local repair for ${accountLogLabel(accountId)}`); } /** @@ -308,7 +308,7 @@ async function tick(): Promise { // stuck — never reached app.log. One line per account per 3 minutes, // and only when there was work, so it costs nothing and goes quiet. logger.info( - `Body re-heal ${accountId}: repaired ${repaired}, failed ${failed}, ${remaining} queued` + + `Body re-heal ${accountLogLabel(accountId)}: repaired ${repaired}, failed ${failed}, ${remaining} queued` + (skippedOffline ? ` (SKIPPED — account offline, ${skippedOffline} waiting)` : '') + ` | local rebuild ${local.repaired} repaired, ${local.skipped} unrepairable, ` + `${local.notDownloaded} body not downloaded yet, ${localRemaining} queued`, @@ -318,7 +318,7 @@ async function tick(): Promise { // Isolate one account's failure so the loop still covers the rest — at // WARN, because at debug a permanently-failing account looked identical // to one with nothing to do. - logger.warn(`Body re-heal: account ${accountId} tick failed: ${(error as Error).message}`); + logger.warn(`Body re-heal: account ${accountLogLabel(accountId)} tick failed: ${(error as Error).message}`); } } } catch (error) { diff --git a/apps/desktop/electron/services/bulk-backfill.ts b/apps/desktop/electron/services/bulk-backfill.ts index 64a48d62..e2eb1009 100644 --- a/apps/desktop/electron/services/bulk-backfill.ts +++ b/apps/desktop/electron/services/bulk-backfill.ts @@ -14,7 +14,7 @@ * conversations (tagging prevents FUTURE mis-merges; it doesn't retroactively split). */ -import { addTag, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, addTag, createLogger } from '@sarvinbox/core'; import { getMeta, setMeta } from './core-db'; @@ -98,9 +98,9 @@ export async function maybeBackfillBulk(storage: any, engine: any, accountId: st // Mark done only on a clean full pass — a mid-run disconnect throws and leaves // the flag unset so it resumes (re-classifying is idempotent) next launch. setMeta(key, String(Date.now())); - logger.info(`[BulkBackfill] ${accountId}: done — scanned ${scanned}, tagged ${tagged} bulk in ${Date.now() - t0}ms`); + logger.info(`[BulkBackfill] ${accountLogLabel(accountId)}: done — scanned ${scanned}, tagged ${tagged} bulk in ${Date.now() - t0}ms`); } catch (e) { - logger.warn(`[BulkBackfill] ${accountId}: interrupted (scanned ${scanned}, tagged ${tagged}) — will resume: ${(e as Error).message}`); + logger.warn(`[BulkBackfill] ${accountLogLabel(accountId)}: interrupted (scanned ${scanned}, tagged ${tagged}) — will resume: ${(e as Error).message}`); } finally { inFlight.delete(accountId); } diff --git a/apps/desktop/electron/services/calendar-mail-sync.ts b/apps/desktop/electron/services/calendar-mail-sync.ts index c25fb4cc..39cbf2f5 100644 --- a/apps/desktop/electron/services/calendar-mail-sync.ts +++ b/apps/desktop/electron/services/calendar-mail-sync.ts @@ -1,5 +1,5 @@ import { authenticationFailed } from '@sarv-in/mailguard'; -import { classifyFolder, createLogger, getEventBus, hasTag, sanitizeIcsText, type EmailRecord } from '@sarvinbox/core'; +import { accountLogLabel, classifyFolder, createLogger, getEventBus, hasTag, sanitizeIcsText, type EmailRecord } from '@sarvinbox/core'; import type Database from 'better-sqlite3'; import { findStorageForEmail, getAccountIdForStorage, getAllAccountRuntimes, getMainWindow, getSyncEngineFor } from '../shared'; @@ -94,7 +94,7 @@ export class CalendarMailSync { const state = error instanceof BlockedCalendarMail ? 'blocked' : error instanceof InvalidCalendarMail ? 'ignored' : 'pending'; this.database().prepare('UPDATE local_calendar_mail_work SET state=?,attempts=attempts+1,next_attempt=? WHERE account_id=? AND email_id=?') .run(state, this.clock() + Math.min(30 * 60_000, 30_000 * 2 ** Math.min(row.attempts, 6)), row.accountId, row.emailId); - log.debug('Calendar invitation deferred or ignored', row.accountId, row.emailId, error instanceof Error ? error.message : 'Unavailable'); + log.debug('Calendar invitation deferred or ignored', accountLogLabel(row.accountId), row.emailId, error instanceof Error ? error.message : 'Unavailable'); } } } finally { this.draining = false; } diff --git a/apps/desktop/electron/services/contact-enrichment-scheduler.ts b/apps/desktop/electron/services/contact-enrichment-scheduler.ts index f5b232af..75c69763 100644 --- a/apps/desktop/electron/services/contact-enrichment-scheduler.ts +++ b/apps/desktop/electron/services/contact-enrichment-scheduler.ts @@ -18,7 +18,7 @@ * renderer-side (2s between LLM calls). */ -import { getEventBus, createLogger } from '@sarvinbox/core'; +import { accountLogLabel, getEventBus, createLogger } from '@sarvinbox/core'; import { getMainWindow, getStorage, getAllAccountRuntimes } from '../shared'; const logger = createLogger('contact-enrichment-scheduler'); @@ -279,7 +279,7 @@ async function runTick(manual = false): Promise { ...(excludeContactIds.length ? { excludeContactIds } : {}), }); } catch (e) { - logger.error(`[EnrichmentScheduler] list candidates failed (acct=${id ?? 'active'}):`, e); + logger.error(`[EnrichmentScheduler] list candidates failed (acct=${accountLogLabel(id, 'active')}):`, e); continue; } if (generation !== tickGeneration) return 0; @@ -294,7 +294,7 @@ async function runTick(manual = false): Promise { // Lock already held from the claim above; refresh the start time so the // stale-lock timeout measures from the actual dispatch, not the claim. batchStartedAt = Date.now(); - logger.info(`[EnrichmentScheduler] dispatching batch of ${candidates.length} contacts (acct=${id ?? 'active'})`); + logger.info(`[EnrichmentScheduler] dispatching batch of ${candidates.length} contacts (acct=${accountLogLabel(id, 'active')})`); activeBatch = { batchId: `${Date.now()}-${++batchSequence}`, contactIds: candidates.map((c) => c.id), diff --git a/apps/desktop/electron/services/conversation-extraction-scheduler.ts b/apps/desktop/electron/services/conversation-extraction-scheduler.ts index dd45ebd3..cc4ae9fd 100644 --- a/apps/desktop/electron/services/conversation-extraction-scheduler.ts +++ b/apps/desktop/electron/services/conversation-extraction-scheduler.ts @@ -36,6 +36,7 @@ */ import { + accountLogLabel, FIRST_SPLIT_MAX_ATTEMPTS, FIRST_SPLIT_VERSION, createLogger, @@ -148,7 +149,7 @@ async function nominateCandidates(): Promise { // again next pass. if (noEvidence.length > 0) retired += storage.skipFirstSplits(noEvidence, now); } catch (error) { - logger.warn(`nominate acct=${accountId} failed: ${(error as Error)?.message ?? error}`); + logger.warn(`nominate acct=${accountLogLabel(accountId)} failed: ${(error as Error)?.message ?? error}`); } } // The renderer re-nominates nothing it acted on, but a thread it cannot diff --git a/apps/desktop/electron/services/core-db.ts b/apps/desktop/electron/services/core-db.ts index 2150f1e1..53f04706 100644 --- a/apps/desktop/electron/services/core-db.ts +++ b/apps/desktop/electron/services/core-db.ts @@ -30,6 +30,7 @@ import { applyDbKey } from '@sarvinbox/storage-node/db-encryption'; import Database from 'better-sqlite3'; import { app } from 'electron'; +import { logPath } from '../utils/log-path'; import { getDbEncryptionKey } from './db-key-store'; @@ -83,7 +84,7 @@ export function getCoreDb(): Database.Database { ); `); db = handle; - logger.info('[CoreDB] opened', dbPath); + logger.info('[CoreDB] opened', logPath(dbPath)); return db; } diff --git a/apps/desktop/electron/services/crash-report-pref.ts b/apps/desktop/electron/services/crash-report-pref.ts index 854f2d00..f707bbfc 100644 --- a/apps/desktop/electron/services/crash-report-pref.ts +++ b/apps/desktop/electron/services/crash-report-pref.ts @@ -7,12 +7,15 @@ * module load in main.ts, before storage exists (and the DB may be what is * crashing), so the preference must be readable synchronously that early. */ +import { randomUUID } from 'crypto'; import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; +import { readRegularFileSync, writePrivateFileAtomicSync } from '@sarvinbox/core'; import { app } from 'electron'; const FILE = 'crash-reports.json'; +const ID_FILE = 'crash-report-id'; /** * The user's answer. `unasked` means no answer yet: nothing is sent, and the @@ -52,3 +55,32 @@ export function readCrashReportChoice(): CrashReportChoice { export function writeCrashReportChoice(choice: CrashReportAnswer): void { writeFileSync(prefPath(), `${JSON.stringify({ choice })}\n`, { encoding: 'utf8', mode: 0o600 }); } + +// A random UUID (v4), lower-case, nothing else. +const INSTALL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +/** + * The id crash reports from this installation carry, so reports from one + * computer group together: a random UUID made on first use and kept in its + * own file in userData. Random, so it is derived from nothing — it used to be + * a truncated SHA-256 of the account's address, which anyone holding a guess + * at the address could confirm, and which changed with whichever account + * connected last. The same for every account on this computer. + * + * A missing, unreadable or malformed file gets a new id (written owner-only, + * whole or not at all). If even that write fails, the new id is used for this + * run only: a fresh id each launch splits one computer's reports apart, which + * is better than tying them to anything about the user. + */ +export function crashReportInstallId(): string { + const path = join(app.getPath('userData'), ID_FILE); + try { + const saved = readRegularFileSync(path, { minBytes: 36, maxBytes: 64 }).toString('utf8').trim(); + if (INSTALL_ID.test(saved)) return saved; + } catch { /* missing or unreadable: make one */ } + const id = randomUUID(); + try { + writePrivateFileAtomicSync(path, `${id}\n`); + } catch { /* this run only */ } + return id; +} diff --git a/apps/desktop/electron/services/db-compact.ts b/apps/desktop/electron/services/db-compact.ts index 7bc7cbae..da7bf6dd 100644 --- a/apps/desktop/electron/services/db-compact.ts +++ b/apps/desktop/electron/services/db-compact.ts @@ -27,6 +27,7 @@ import { join } from 'node:path'; import { Worker } from 'node:worker_threads'; import { + accountLogLabel, compactionEstimate, formatBytes, hasCompactionHeadroom, @@ -37,7 +38,6 @@ import { } from '@sarvinbox/core'; import { app } from 'electron'; - import { getAccountRuntime } from '../shared'; import type { CompactWorkerResult } from '../workers/db-compact.worker'; @@ -118,7 +118,7 @@ export function estimateCompaction(accountId: string): CompactionReport | null { const estimate = compactionEstimate(storage.getPageStats()); return { accountId, ...estimate, worthwhile: isCompactionWorthwhile(estimate) }; } catch (error) { - logger.warn(`[Compact] could not read page stats for ${accountId}`, error); + logger.warn(`[Compact] could not read page stats for ${accountLogLabel(accountId)}`, error); return null; } } @@ -212,7 +212,7 @@ export async function compactAccountDatabase(accountId: string): Promise ${formatBytes(after.fileBytes)}, ` + `${result.rowsAfter ?? '?'} emails, auto_vacuum=${result.autoVacuum}`, ); @@ -248,7 +248,7 @@ export async function compactAccountDatabase(accountId: string): Promise 0) { logger.info( `${extensionId} changed ${email.id}: ` + - `+[${(changes.add ?? []).join(',')}] -[${(changes.remove ?? []).join(',')}]` + `+[${(changes.add ?? []).map(labelLogLabel).join(',')}] -[${(changes.remove ?? []).map(labelLogLabel).join(',')}]` ); } }, diff --git a/apps/desktop/electron/services/extension-marketplace.ts b/apps/desktop/electron/services/extension-marketplace.ts index 8a2d0ece..b59487c9 100644 --- a/apps/desktop/electron/services/extension-marketplace.ts +++ b/apps/desktop/electron/services/extension-marketplace.ts @@ -39,6 +39,7 @@ import { MAX_DOWNLOAD_BYTES, buildCatalog, createLogger, + errorDiagnostic, isNewerCompatibleRelease, isTrustedRegistryUrl, mergeRegistries, @@ -57,6 +58,7 @@ import { app } from 'electron'; import * as tar from 'tar'; import { getExtensionManager } from '../shared'; +import { logPath } from '../utils/log-path'; import { isAllowedArchiveEntry } from './extension-archive-rules.mjs'; import { chromiumFetch } from './net-fetch'; @@ -253,7 +255,7 @@ export function getExtensionsConfig(): ParsedExtensionsConfig { try { raw = JSON.parse(fs.readFileSync(configPath(), 'utf-8')); } catch (error) { - logger.warn(`Could not read ${configPath()}; using defaults:`, error); + logger.warn(`Could not read ${logPath(configPath())}; using defaults:`, errorDiagnostic(error)); } config = parseExtensionsConfig(raw); for (const warning of config.warnings) logger.warn(`extensions.config.json: ${warning}`); diff --git a/apps/desktop/electron/services/extension-workflow-runner.ts b/apps/desktop/electron/services/extension-workflow-runner.ts index ebf2a0e4..5705e0b5 100644 --- a/apps/desktop/electron/services/extension-workflow-runner.ts +++ b/apps/desktop/electron/services/extension-workflow-runner.ts @@ -25,6 +25,7 @@ */ import { + accountLogLabel, createLoopYielder, createLogger, extensionDebugEnabled, @@ -162,7 +163,7 @@ async function runOne(message: QueuedMessage): Promise { if (DEBUG_RUNNER) { logger.debug( - `${message.stage} ${email.id} acct=${getAccountIdForStorage(storage) ?? 'active'} ` + + `${message.stage} ${email.id} acct=${accountLogLabel(getAccountIdForStorage(storage), 'active')} ` + `workflows=${results.size} tags=${plan.changed ? plan.tags : 'unchanged'}` ); } diff --git a/apps/desktop/electron/services/follow-up-checker.ts b/apps/desktop/electron/services/follow-up-checker.ts index 29685897..594c209a 100644 --- a/apps/desktop/electron/services/follow-up-checker.ts +++ b/apps/desktop/electron/services/follow-up-checker.ts @@ -7,7 +7,7 @@ * just the active one, so a reminder on a background account still fires. */ -import { createLogger, type FollowUp, type FollowUpStatus } from '@sarvinbox/core'; +import { accountLogLabel, createLogger, type FollowUp, type FollowUpStatus } from '@sarvinbox/core'; import { getAllAccountIds, getMainWindow, getStorage, getStorageFor } from '../shared'; @@ -59,7 +59,7 @@ export async function checkFollowUpsForAccount( else replied += 1; } } catch (error) { - logger.warn(`[FollowUp] Check failed for account ${accountId}:`, error); + logger.warn(`[FollowUp] Check failed for account ${accountLogLabel(accountId)}:`, error); } return { due, replied }; } diff --git a/apps/desktop/electron/services/gmail-label-api.ts b/apps/desktop/electron/services/gmail-label-api.ts index b00123e4..8be1a8d6 100644 --- a/apps/desktop/electron/services/gmail-label-api.ts +++ b/apps/desktop/electron/services/gmail-label-api.ts @@ -1,4 +1,4 @@ -import { createLogger } from '@sarvinbox/core'; +import { failureCause, labelLogLabel, createLogger } from '@sarvinbox/core'; const logger = createLogger('gmail-label-api'); /** * Gmail label COLOR via the Gmail REST API. Used ONLY for Gmail accounts @@ -112,22 +112,22 @@ export async function ensureGmailLabelColor(token: string, name: string, hex?: s // Gmail API calls when provisioning runs more than once. const cur = existing.color || {}; if (cur.backgroundColor === color.backgroundColor && cur.textColor === color.textColor) return false; - try { await api(token, 'PATCH', `/${existing.id}`, { color }); logger.info(`[GmailLabels] colored "${name}"`); return true; } - catch (e) { logger.warn(`[GmailLabels] color PATCH "${name}" failed:`, (e as Error).message); return false; } + try { await api(token, 'PATCH', `/${existing.id}`, { color }); logger.info(`[GmailLabels] colored ${labelLogLabel(name)}`); return true; } + catch (e) { logger.warn(`[GmailLabels] color PATCH ${labelLogLabel(name)} failed:`, failureCause(e)); return false; } } const base = { name, labelListVisibility: 'labelShow', messageListVisibility: 'show' }; try { await api(token, 'POST', '', color ? { ...base, color } : base); - logger.info(`[GmailLabels] created "${name}"${color ? ' (colored)' : ''}`); + logger.info(`[GmailLabels] created ${labelLogLabel(name)}${color ? ' (colored)' : ''}`); return true; } catch (e) { - logger.warn(`[GmailLabels] create "${name}" with color failed:`, (e as Error).message); - try { await api(token, 'POST', '', base); logger.info(`[GmailLabels] created "${name}" (plain — color rejected)`); return true; } - catch (e2) { logger.warn(`[GmailLabels] create "${name}" plain failed:`, (e2 as Error).message); return false; } + logger.warn(`[GmailLabels] create ${labelLogLabel(name)} with color failed:`, failureCause(e)); + try { await api(token, 'POST', '', base); logger.info(`[GmailLabels] created ${labelLogLabel(name)} (plain — color rejected)`); return true; } + catch (e2) { logger.warn(`[GmailLabels] create ${labelLogLabel(name)} plain failed:`, failureCause(e2)); return false; } } } catch (e) { - logger.warn(`[GmailLabels] ensure "${name}" failed:`, (e as Error).message); + logger.warn(`[GmailLabels] ensure ${labelLogLabel(name)} failed:`, failureCause(e)); return false; } } @@ -141,7 +141,7 @@ export async function renameGmailLabel(token: string, oldName: string, newName: if (!existing) return; await api(token, 'PATCH', `/${existing.id}`, { name: newName }).catch(() => { /* target may already exist */ }); } catch (e) { - logger.warn('[GmailLabels] rename best-effort failed:', (e as Error).message); + logger.warn('[GmailLabels] rename best-effort failed:', failureCause(e)); } } @@ -161,7 +161,7 @@ export async function deleteGmailLabelsUnder(token: string, prefix: string): Pro } return n; } catch (e) { - logger.warn('[GmailLabels] delete-under best-effort failed:', (e as Error).message); + logger.warn('[GmailLabels] delete-under best-effort failed:', failureCause(e)); return 0; } } diff --git a/apps/desktop/electron/services/notification-service.ts b/apps/desktop/electron/services/notification-service.ts index 7b7365cf..bc748dcb 100644 --- a/apps/desktop/electron/services/notification-service.ts +++ b/apps/desktop/electron/services/notification-service.ts @@ -132,7 +132,7 @@ export function notifyNewMail(m: NewMailNotice): void { }; try { if (logger.isLevelEnabled('trace')) { - logger.trace(`[notifications] consider ${m.emailId} mode=${config.mode} cats=${m.categories ? `[${m.categories.join(',')}]` : 'none'} date=${m.date} from=${m.fromAddress}`); + logger.trace(`[notifications] consider ${m.emailId} mode=${config.mode} cats=${m.categories ? m.categories.length : 'none'} date=${m.date} from=${m.fromAddress}`); } if (config.mode === 'off') return drop('mode=off'); if (notified.has(m.emailId)) return drop('already notified'); diff --git a/apps/desktop/electron/services/oauth-service.ts b/apps/desktop/electron/services/oauth-service.ts index 5befaf36..72e19155 100644 --- a/apps/desktop/electron/services/oauth-service.ts +++ b/apps/desktop/electron/services/oauth-service.ts @@ -1184,6 +1184,9 @@ async function fetchUserInfo( ): Promise { const res = await fetch(provider.userInfoEndpoint, { headers: { Authorization: `Bearer ${accessToken}` }, + // Never followed: the access token rides on the request, and a redirect + // is not where the provider said its user-info endpoint is. + redirect: 'error', }); if (!res.ok) { throw new OAuthError(`userinfo failed (${res.status})`, 'USERINFO_FAILED'); diff --git a/apps/desktop/electron/services/outbox-service.ts b/apps/desktop/electron/services/outbox-service.ts index dc5c9ad5..a37e190c 100644 --- a/apps/desktop/electron/services/outbox-service.ts +++ b/apps/desktop/electron/services/outbox-service.ts @@ -15,6 +15,7 @@ */ import { + accountLogLabel, SendQueue, nextDrainDelayMs, type SendFn, @@ -215,7 +216,7 @@ export async function drainOutboxForAccount(accountId: string): Promise { await q.processQueue(); notifyOutboxChanged(); } catch (e) { - logger.error('[Outbox] Per-account drain failed:', accountId, e); + logger.error('[Outbox] Per-account drain failed:', accountLogLabel(accountId), e); } } diff --git a/apps/desktop/electron/services/sender-identity-service.ts b/apps/desktop/electron/services/sender-identity-service.ts index 9063a68c..62a52339 100644 --- a/apps/desktop/electron/services/sender-identity-service.ts +++ b/apps/desktop/electron/services/sender-identity-service.ts @@ -24,6 +24,7 @@ */ import { + failureCause, createLogger, DEFAULT_SENDER_IDENTITY_POLICY, discoverFavicon, @@ -85,7 +86,7 @@ export function setSenderIdentityPolicy(raw: unknown): SenderIdentityPolicy { try { setBlob(POLICY_BLOB_KEY, Buffer.from(JSON.stringify(cachedPolicy), 'utf8')); } catch (e) { - logger.warn(`[SenderIdentity] policy not persisted: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] policy not persisted: ${failureCause(e)}`); } return cachedPolicy; } @@ -388,14 +389,14 @@ export async function senderIdentityTick(svc: SenderIdentityService = getSenderI try { domains.push(...(await storage.getRecentSenderDomains(DOMAINS_PER_ACCOUNT))); } catch (e) { - logger.warn(`[SenderIdentity] could not list sender domains: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] could not list sender domains: ${failureCause(e)}`); } } const refreshed = await svc.refreshStale(domains, REFRESH_PER_TICK); if (refreshed > 0) logger.info(`[SenderIdentity] refreshed ${refreshed} domain(s)`); return refreshed; } catch (e) { - logger.warn(`[SenderIdentity] tick failed: ${(e as Error).message}`); + logger.warn(`[SenderIdentity] tick failed: ${failureCause(e)}`); return 0; } finally { ticking = false; diff --git a/apps/desktop/electron/services/spam-reputation-service.ts b/apps/desktop/electron/services/spam-reputation-service.ts index 7e88b282..56f9604e 100644 --- a/apps/desktop/electron/services/spam-reputation-service.ts +++ b/apps/desktop/electron/services/spam-reputation-service.ts @@ -39,6 +39,8 @@ import { type RdapBootstrap, } from '@sarv-in/mailguard'; import { + failureCause, + folderLogLabel, SPAM_THRESHOLD, addTag, computeFilterActionResult, @@ -486,7 +488,7 @@ async function judgeRows( await target.storage.updateEmail(row.id, { tags: moved.tags, folderId: moved.folderId }); if (moved.changed && target.engine) { target.engine.moveToSpam(row.folderPath, row.uid).catch((err: unknown) => { - logger.warn(`[Reputation] server-side move failed for uid ${row.uid} in ${row.folderPath}: ${(err as Error)?.message ?? err}`); + logger.warn(`[Reputation] server-side move failed for uid ${row.uid} in ${folderLogLabel(row.folderPath)}: ${failureCause(err)}`); }); } summary.filed += 1; diff --git a/apps/desktop/electron/services/spam-verdict-repair.ts b/apps/desktop/electron/services/spam-verdict-repair.ts index be2a06d4..87c6bc25 100644 --- a/apps/desktop/electron/services/spam-verdict-repair.ts +++ b/apps/desktop/electron/services/spam-verdict-repair.ts @@ -36,6 +36,9 @@ * every later launch a single empty SELECT. */ import { + failureCause, + folderLogLabel, + accountLogLabel, bodyStage, createLogger, hasTag, @@ -135,7 +138,7 @@ export async function repairMessage( // move lands, and the queue persists it across a disconnect. if (moved && queue && email.uid > 0) { queue.move(moved.sourcePath, email.uid, moved.destPath).catch((err: unknown) => { - logger.warn(`[SpamRepair] server move failed for uid ${email.uid} in ${moved!.sourcePath}: ${(err as Error)?.message ?? err}`); + logger.warn(`[SpamRepair] server move failed for uid ${email.uid} in ${folderLogLabel(moved!.sourcePath)}: ${failureCause(err)}`); }); } return { rescored: update.spamScore !== undefined, unfiled }; @@ -197,7 +200,7 @@ async function run(): Promise { try { await repairAccount(storage, queue, accountId); } catch (e) { - logger.warn(`[SpamRepair] ${accountId}: repair failed (isolated): ${(e as Error).message}`); + logger.warn(`[SpamRepair] ${accountLogLabel(accountId)}: repair failed (isolated): ${(e as Error).message}`); } } } diff --git a/apps/desktop/electron/services/startup-thread-repair.ts b/apps/desktop/electron/services/startup-thread-repair.ts index 160ad382..c048945f 100644 --- a/apps/desktop/electron/services/startup-thread-repair.ts +++ b/apps/desktop/electron/services/startup-thread-repair.ts @@ -13,7 +13,7 @@ * tick so it's independent of that scheduler's tested behavior. */ -import { createLogger } from '@sarvinbox/core'; +import { accountLogLabel, createLogger } from '@sarvinbox/core'; import { getStorage, getSyncEngine, getAllAccountRuntimes, getCurrentAccountId } from '../shared'; @@ -102,13 +102,13 @@ async function handleAccount(storage: any, accountId: string): Promise { recordThreadRepairPass(accountId, t0); if (r) { const scope = sinceCreatedAt === undefined ? 'full' : 'incremental'; - logger.info(`[ThreadRepair] ${accountId}: ${scope}, ${r.emailsRetargeted} retargeted, ${r.threadsBefore}->${r.threadsAfter} threads, ${r.iterations} iter (${Date.now() - t0}ms)`); + logger.info(`[ThreadRepair] ${accountLogLabel(accountId)}: ${scope}, ${r.emailsRetargeted} retargeted, ${r.threadsBefore}->${r.threadsAfter} threads, ${r.iterations} iter (${Date.now() - t0}ms)`); } } catch (e) { // Leave it OUT of `done` (and unstamped) and clear the throttle so it retries // promptly on the next tick rather than waiting out REPAIR_INTERVAL_MS. lastRepairAt.delete(storage); - logger.warn(`[ThreadRepair] ${accountId} failed (will retry): ${(e as Error).message}`); + logger.warn(`[ThreadRepair] ${accountLogLabel(accountId)} failed (will retry): ${(e as Error).message}`); return; } diff --git a/apps/desktop/electron/services/unified-pipeline-service.ts b/apps/desktop/electron/services/unified-pipeline-service.ts index 22979154..dbfb0799 100644 --- a/apps/desktop/electron/services/unified-pipeline-service.ts +++ b/apps/desktop/electron/services/unified-pipeline-service.ts @@ -12,6 +12,11 @@ */ import { + errorDiagnostic, + failureCause, + categoryLogLabel, + folderLogLabel, + accountLogLabel, BehaviorIntelligence, LogAggregator, MAX_API_RETRIES, @@ -121,7 +126,7 @@ async function restorePersistedAIConfig(persisted: AIProviderConfig): Promise { - logger.warn(`[Pipeline] could not re-check the saved AI provider's sign-in: ${e.message}`); + logger.warn(`[Pipeline] could not re-check the saved AI provider's sign-in: ${failureCause(e)}`); }); } @@ -441,7 +446,8 @@ let aiConfigPushes = 0; function refuseAIConfig(error: AIEndpointRefusedError): void { aiConfig = null; lastAIErrorReason = error.message; - logger.warn(`[Pipeline] AI provider refused — background AI is off until it is fixed: ${error.message}`); + // The reason, not the message: the message describes the address it refused. + logger.warn(`[Pipeline] AI provider refused — background AI is off until it is fixed: ${error.reason}`); emitAiPipelineStatus(); reportAIEndpointRefused(error); } @@ -569,7 +575,7 @@ export async function disablePipelineAIIfProviderRemoved(): Promise { try { saved = oauthSignInOfAIConfig(loadPipelineAIConfigSync()); } catch (error) { - logger.warn(`[Pipeline] could not read the saved AI config: ${(error as Error).message}`); + logger.warn(`[Pipeline] could not read the saved AI config: ${failureCause(error)}`); } const liveGone = !!live && !(await getOAuthAccount(live.provider, live.email)); const savedGone = !!saved && !(await getOAuthAccount(saved.provider, saved.email)); @@ -759,7 +765,7 @@ export function initializeUnifiedPipeline( try { ensureBundledAgentPrompts((repos as any).prompts); } catch (err) { - logger.warn('[Pipeline] Failed to seed prompt templates:', err); + logger.warn('[Pipeline] Failed to seed prompt templates:', errorDiagnostic(err)); } // Create UnifiedPipeline @@ -808,7 +814,7 @@ export function initializeUnifiedPipeline( getPromptTemplate: (id: string) => { try { const promptRepo = (pRepos() as any)?.prompts; - return readBundledAgentPrompt(promptRepo, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', error)); + return readBundledAgentPrompt(promptRepo, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', errorDiagnostic(error))); } catch { return null; } }, @@ -887,7 +893,7 @@ export function initializeUnifiedPipeline( if (m > 0) logger.info(`[Pipeline] Built ${m} sender memories`); } } catch (e) { - logger.warn('[Pipeline] deferred initial learning failed:', (e as Error).message); + logger.warn('[Pipeline] deferred initial learning failed:', failureCause(e)); } }, 3000); initialLearnTimer.unref?.(); @@ -926,7 +932,7 @@ export function initializeUnifiedPipeline( const m = repos.agent.buildAllSenderMemories(email); if (m > 0) logger.info(`[Pipeline] Built ${m} sender memories`); } - } catch (e) { logger.error('[Pipeline] Backfill check error:', e); clearInterval(backfillCheck); } + } catch (e) { logger.error('[Pipeline] Backfill check error:', errorDiagnostic(e)); clearInterval(backfillCheck); } }, 10_000); } } @@ -988,7 +994,7 @@ export async function runPipeline1(emailId: string, storage: any = getStorage()) try { storage.getRepositories()?.agent?.markExtractionDone(emailId); } catch (error) { - logger.error(`[Pipeline] P1 error for ${emailId}:`, error); + logger.error(`[Pipeline] P1 error for ${emailId}:`, errorDiagnostic(error)); } } @@ -1044,7 +1050,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi priorityReasoning = score.reasoning; recommendedAction = score.recommendedAction || null; } catch (err) { - logger.error(`[Pipeline] Scoring error for ${emailId}:`, err); + logger.error(`[Pipeline] Scoring error for ${emailId}:`, errorDiagnostic(err)); } finally { activeProcessingStorage = prevProcessingStorage; } @@ -1132,7 +1138,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // disconnected engine / restart / burst can never strand it unlabeled. } } catch (err) { - logger.error(`[Pipeline] Categorization error for ${emailId}:`, err); + logger.error(`[Pipeline] Categorization error for ${emailId}:`, errorDiagnostic(err)); // Auth/credit terminal errors pause categorization globally + raise the // Fix banner. A per-email 4xx ('client', not paused) is a doomed request // for THIS message only — accept it (mark done, no categories) so we @@ -1292,7 +1298,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi // 4. Auto-draft reply when pipeline proposes "reply" action if (proposed && (recommendedAction === 'reply' || recommendedAction === 'reply_all') && aiConfig) { autoDraftReply(emailId, storage).catch(err => - logger.error(`[Pipeline] Auto-draft failed for ${emailId}:`, err) + logger.error(`[Pipeline] Auto-draft failed for ${emailId}:`, errorDiagnostic(err)) ); } @@ -1316,7 +1322,7 @@ async function runPipeline2(emailId: string, storage: any = getStorage()): Promi }); } } catch (error) { - logger.error(`[Pipeline] P2 error for ${emailId}:`, error); + logger.error(`[Pipeline] P2 error for ${emailId}:`, errorDiagnostic(error)); } } @@ -1403,7 +1409,7 @@ function lateAutoDraftStop( try { reason = autoDraftSkipReason(storage, email); } catch (err) { - logger.warn(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — thread gates could not be checked:`, err); + logger.warn(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — thread gates could not be checked:`, errorDiagnostic(err)); return 'gates-unreadable'; } if (reason) logger.info(`[Pipeline] Drop auto-draft for ${email.id} before ${stage} — ${reason} (changed while drafting)`); @@ -1425,7 +1431,7 @@ async function settleLateAutoDraftStop( try { await agentRepo.updateDecisionStatus(decision.id, 'rejected', 'dismissed', USER_HAS_DRAFT_FEEDBACK); } catch (err) { - logger.warn(`[Pipeline] Could not resolve decision ${decision.id} as '${USER_HAS_DRAFT_FEEDBACK}':`, err); + logger.warn(`[Pipeline] Could not resolve decision ${decision.id} as '${USER_HAS_DRAFT_FEEDBACK}':`, errorDiagnostic(err)); } } @@ -1462,7 +1468,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( try { skip = autoDraftSkipReason(storage, email); } catch (err) { - logger.warn(`[Pipeline] Skip auto-draft for ${emailId} — thread gates could not be checked:`, err); + logger.warn(`[Pipeline] Skip auto-draft for ${emailId} — thread gates could not be checked:`, errorDiagnostic(err)); return; } if (skip === 'not-active-account') { @@ -1649,7 +1655,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( } } } catch (err) { - logger.warn('[Pipeline] Relationship gate check failed, continuing:', err); + logger.warn('[Pipeline] Relationship gate check failed, continuing:', errorDiagnostic(err)); } // The AI's `should_auto_draft` decision already weighed reply-worthiness, @@ -1724,7 +1730,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( getPromptTemplate: (id: 'agent_plan' | 'agent_draft') => { try { const r = (storage as any).getRepositories?.()?.prompts; - return readBundledAgentPrompt(r, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', error)); + return readBundledAgentPrompt(r, id, error => logger.warn('[Pipeline] Failed to upgrade this account\'s prompt defaults:', errorDiagnostic(error))); } catch { return null; } }, getNotes: (e: string) => agentRepo.getNotesForPrompt(e), @@ -1902,14 +1908,14 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( try { draftKeyRecorded = agentRepo.recordDecisionDraftMessageId(decision.id, draftMessageId); } catch (err) { - logger.warn(`[Pipeline] Could not record the draft Message-ID for decision ${decision.id}:`, err); + logger.warn(`[Pipeline] Could not record the draft Message-ID for decision ${decision.id}:`, errorDiagnostic(err)); } const forgetDraftKey = (): void => { if (!draftKeyRecorded) return; try { agentRepo.clearDecisionDraftMessageId(decision.id, draftMessageId); } catch (err) { - logger.warn(`[Pipeline] Could not clear the draft Message-ID for decision ${decision.id}:`, err); + logger.warn(`[Pipeline] Could not clear the draft Message-ID for decision ${decision.id}:`, errorDiagnostic(err)); } }; @@ -1946,7 +1952,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( 'draft saved to Drafts folder', ); } catch (err) { - logger.warn(`[Pipeline] Could not mark decision ${decision.id} as auto:`, err); + logger.warn(`[Pipeline] Could not mark decision ${decision.id} as auto:`, errorDiagnostic(err)); } // Log in the user_action_log timeline (source='agent_auto') so the // Activity Log tab shows the draft alongside auto-read / auto-archive @@ -1959,11 +1965,13 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( }); } else { forgetDraftKey(); - logger.warn(`[Pipeline] IMAP draft save failed for ${emailId}: ${result.error}`); + // Our own words only (what precedes the first colon): the rest of a + // save error can quote the server's answer or the encryption failure. + logger.warn(`[Pipeline] IMAP draft save failed for ${emailId}: ${String(result.error ?? 'no result').split(':')[0]}`); } } catch (err) { forgetDraftKey(); - logger.error(`[Pipeline] IMAP draft save error for ${emailId}:`, err); + logger.error(`[Pipeline] IMAP draft save error for ${emailId}:`, errorDiagnostic(err)); } // Notify renderer that draft is ready @@ -1976,7 +1984,7 @@ export async function autoDraftReply(emailId: string, storage: any = getStorage( }); } } catch (error) { - logger.error(`[Pipeline] Auto-draft error for ${emailId}:`, error); + logger.error(`[Pipeline] Auto-draft error for ${emailId}:`, errorDiagnostic(error)); } } @@ -2131,7 +2139,7 @@ async function tryAutoSendReply(params: { try { await appendSentCopy(result.rawMessage, result.messageId, sendOptions); } catch (err) { - logger.warn(`[Pipeline] Sent-folder append for auto-sent ${emailId} failed (non-fatal):`, (err as Error)?.message || err); + logger.warn(`[Pipeline] Sent-folder append for auto-sent ${emailId} failed (non-fatal):`, failureCause(err)); } } @@ -2146,7 +2154,7 @@ async function tryAutoSendReply(params: { REPLY_SENT_FEEDBACK, ); } catch (err) { - logger.warn(`[Pipeline] Could not mark decision ${decision.id} as sent:`, err); + logger.warn(`[Pipeline] Could not mark decision ${decision.id} as sent:`, errorDiagnostic(err)); } // Same activity-log surface as every other agent action (learning + @@ -2174,7 +2182,7 @@ async function tryAutoSendReply(params: { } return true; } catch (err) { - logger.error(`[Pipeline] Auto-send error for ${emailId} — falling back to Drafts:`, err); + logger.error(`[Pipeline] Auto-send error for ${emailId} — falling back to Drafts:`, errorDiagnostic(err)); return false; } } @@ -2213,7 +2221,7 @@ async function resolveGmailToken(accountId: string | null): Promise a.provider === 'gmail' && a.email?.toLowerCase() === email); @@ -2222,13 +2230,13 @@ async function resolveGmailToken(accountId: string | null): Promise { - logger.warn(`[Pipeline] resolveGmailToken: token fetch failed for ${grant.email}:`, e?.message || e); + logger.warn(`[Pipeline] resolveGmailToken: token fetch failed for ${grant.email}:`, failureCause(e)); return null; }); if (traceEnabled()) logger.trace(`[Pipeline] resolveGmailToken: token=${token ? 'yes' : 'no'} (${grant.email})`); return token; } catch (e) { - logger.warn('[Pipeline] resolveGmailToken error:', (e as Error).message); + logger.warn('[Pipeline] resolveGmailToken error:', failureCause(e)); return null; } } @@ -2297,7 +2305,7 @@ async function applyEmailLabels( if (stale.length) { if (canApply && !await canApply()) return 'superseded'; try { await queue.removeGmailLabels(folderPath, email.uid, stale); } - catch (e) { logger.warn('[Pipeline] stale Gmail label cleanup failed:', (e as Error).message); } + catch (e) { logger.warn('[Pipeline] stale Gmail label cleanup failed:', failureCause(e)); } } } @@ -2369,7 +2377,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu // label is re-applied later (next categorization / the backfill action). const engine: any = getSyncEngineForStorage(storage); if (!engine) { - logger.warn(`[Pipeline] mirror skipped acct=${acct} uid=${email.uid}: no engine for this account's storage (won't apply to a wrong account)`); + logger.warn(`[Pipeline] mirror skipped acct=${accountLogLabel(acct)} uid=${email.uid}: no engine for this account's storage (won't apply to a wrong account)`); return; } if (!engine.isConnected?.() || !engine.operationQueue) { @@ -2379,7 +2387,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu const folder = await storage.getFolder(email.folderId); if (!folder?.path) { - logger.info(`[Pipeline] mirror skipped acct=${acct} uid=${email.uid}: folder ${email.folderId} has no path`); + logger.info(`[Pipeline] mirror skipped acct=${accountLogLabel(acct)} uid=${email.uid}: folder ${email.folderId} has no path`); return; } @@ -2393,7 +2401,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu // ACTIVE account, so a background Gmail account's labels used to be created // and coloured in the active account's mailbox instead of its own. const token = isGmail ? await resolveGmailToken(accountId) : null; - if (traceEnabled()) logger.trace(`[Pipeline] mirror acct=${acct} uid=${email.uid} folder="${folder.path}" isGmail=${isGmail} token=${token ? 'yes' : 'no'} cats=[${cats.map((c) => c.slug).join(',')}]`); + if (traceEnabled()) logger.trace(`[Pipeline] mirror acct=${accountLogLabel(acct)} uid=${email.uid} folder=${folderLogLabel(folder.path)} isGmail=${isGmail} token=${token ? 'yes' : 'no'} cats=[${cats.map((c) => categoryLogLabel(c.slug, defs.some((d: any) => d.slug === c.slug && d.isSystem))).join(',')}]`); const result = await applyEmailLabels(engine, email, folder.path, cats, isGmail, token, bySlug, canApply); // Automatic mirrors mark label_status → 'done' only on a CONFIRMED apply. A merely-'queued' op // (background account mid-sync) is NOT yet on the server — if it later @@ -2403,7 +2411,7 @@ export async function mirrorCategoryLabels(storage: any, email: any, categorySlu try { (storage as any).getRepositories?.()?.agent?.markLabelDone?.(email.id); } catch { /* non-fatal */ } } } catch (e) { - logger.warn(`[Pipeline] mirror acct=${acct} uid=${email?.uid} best-effort failed:`, (e as Error).message); + logger.warn(`[Pipeline] mirror acct=${accountLogLabel(acct)} uid=${email?.uid} best-effort failed:`, failureCause(e)); } }); } @@ -2445,7 +2453,7 @@ export async function backfillCategoryLabels(limit = 50): Promise<{ accounts: nu labeled++; } } catch (e) { - logger.warn('[Pipeline] backfill (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] backfill (one account) failed:', failureCause(e)); } } logger.info(`[Pipeline] category-label backfill: ${labeled} mail(s) across ${accounts} account(s)`); @@ -2505,7 +2513,7 @@ async function provisionAccountLabels( } return { handled: true, created }; } catch (e) { - logger.warn('[Pipeline] provision (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] provision (one account) failed:', failureCause(e)); return { handled: false, created: 0 }; } } @@ -2614,7 +2622,7 @@ export async function renameCategoryLabelEverywhere(oldName: string, newName: st await queue.renameCategoryLabel({ slug: '', name: oldName }, { slug: '', name: newName }, categoryLabelConfig.folderMode); } } catch (e) { - logger.warn('[Pipeline] rename label (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] rename label (one account) failed:', failureCause(e)); } } } @@ -2654,7 +2662,7 @@ export async function removeAllCategoryLabels(): Promise<{ accounts: number; rem removed += await queue.removeSarvInboxLabels(categoryLabelConfig.folderMode); } } catch (e) { - logger.warn('[Pipeline] remove labels (one account) failed:', (e as Error).message); + logger.warn('[Pipeline] remove labels (one account) failed:', failureCause(e)); } } logger.info(`[Pipeline] removed ${removed} Sarv Inbox label(s) across ${accounts} account(s)`); @@ -2708,7 +2716,7 @@ async function executeAgentAction(emailId: string, action: UserActionType, _valu // Failures are logged, never swallowed to console (CLAUDE.md: always the // shared logger). A dropped line here is a divergence nobody can see. const onFail = (what: string) => (err: unknown) => - logger.error(`[Pipeline] agent ${what} did not reach IMAP for ${emailId}:`, err); + logger.error(`[Pipeline] agent ${what} did not reach IMAP for ${emailId}:`, errorDiagnostic(err)); if (action === 'read') syncEngine.markAsRead(folder.path, email.uid).catch(onFail('mark-read')); else if (action === 'star') syncEngine.markAsStarred(folder.path, email.uid, true).catch(onFail('star')); else if (action === 'archive') (syncEngine as any).operationQueue?.archive(folder.path, email.uid).catch(onFail('archive')); @@ -2775,7 +2783,7 @@ async function triggerCategorizeFor(emailId: string, hintAccountId?: string, sou const threadId = email.threadId; if (!threadId) return; - logger.info(`[Pipeline:Event] ${source} → ${emailId} thread=${threadId} acct=${getAccountIdForStorage(storage) ?? 'active'}`); + logger.info(`[Pipeline:Event] ${source} → ${emailId} thread=${threadId} acct=${accountLogLabel(getAccountIdForStorage(storage), 'active')}`); processEmail(emailId, threadId, storage); } @@ -2878,7 +2886,7 @@ function startPollingTrigger(): void { stillStuck.map((r: { id: string; reason: string }) => `${r.id}(${r.reason})`).join(', ')); } } catch (e) { - logger.warn('[Pipeline:Poll] stuck-row heal failed:', (e as Error).message); + logger.warn('[Pipeline:Poll] stuck-row heal failed:', failureCause(e)); } // Per-account snapshot for the log line — body-FREE. This used to call @@ -2957,7 +2965,7 @@ function startPollingTrigger(): void { } catch (e) { // Isolate one account's failure so it never skips the accounts after it // in this tick (the loop must keep fanning out across all accounts). - logger.warn('[Pipeline:Poll] account tick failed (isolated):', (e as Error).message); + logger.warn('[Pipeline:Poll] account tick failed (isolated):', failureCause(e)); } } @@ -3067,7 +3075,7 @@ function registerPipelineIPC(): void { try { await clearPipelineAIConfig(); } catch (e) { - logger.warn(`[Pipeline] could not clear the saved AI config: ${(e as Error).message}`); + logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`); } return { success: true }; }); @@ -3089,7 +3097,7 @@ function registerPipelineIPC(): void { logger.warn(`[Pipeline] AI config refused: its ${signIn.provider} sign-in is no longer on this device`); dropLiveAIConfig(); lastAIErrorReason = reason; - void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${e.message}`)); + void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`)); emitAiPipelineStatus(); // The renderer ignores a push's answer, and a provider still listed there // with no sign-in behind it would otherwise show no sign of a problem. @@ -3105,10 +3113,10 @@ function registerPipelineIPC(): void { if (isAIEndpointRefusedError(error)) { refuseAIConfig(error); // Nor is a refused provider the one to bring back after a restart. - void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${e.message}`)); + void clearPipelineAIConfig().catch((e: Error) => logger.warn(`[Pipeline] could not clear the saved AI config: ${failureCause(e)}`)); return { success: false, error: error.message }; } - logger.error('[Pipeline] AI config could not be prepared:', error); + logger.error('[Pipeline] AI config could not be prepared:', errorDiagnostic(error)); return { success: false, error: (error as Error).message }; } if (push !== aiConfigPushes) return overtaken; diff --git a/apps/desktop/electron/services/update-service.ts b/apps/desktop/electron/services/update-service.ts index 6ac2909b..71639f74 100644 --- a/apps/desktop/electron/services/update-service.ts +++ b/apps/desktop/electron/services/update-service.ts @@ -27,6 +27,7 @@ import { app, Notification } from 'electron'; import { autoUpdater, type Logger as UpdaterLogger } from 'electron-updater'; import { getMainWindow } from '../shared'; +import { withoutHomeDir } from '../utils/log-path'; import { restoreAndFocusWindow } from '../utils/window-focus'; import { verifyUpdate } from './update-manifest'; @@ -66,9 +67,13 @@ const logger = createLogger('update-service'); * calls it when it exists, and it is per-request noise. */ const electronUpdaterLog = createLogger('electron-updater'); -/** Keeps an Error's stack; electron-updater mostly logs plain strings. */ -const describeUpdaterMessage = (message: unknown): string => - message instanceof Error ? (message.stack ?? message.message) : String(message); +/** + * Keeps an Error's stack; electron-updater mostly logs plain strings. Its + * lines name the update cache and the installer by absolute path ("downloaded + * to /Users//Library/Caches/…"), so the home folder is written as `~`. + */ +export const describeUpdaterMessage = (message: unknown): string => + withoutHomeDir(message instanceof Error ? (message.stack ?? message.message) : String(message)); const updaterLogger: UpdaterLogger = { info: (message) => electronUpdaterLog.info(describeUpdaterMessage(message)), warn: (message) => electronUpdaterLog.warn(describeUpdaterMessage(message)), diff --git a/apps/desktop/electron/services/vault-credentials.ts b/apps/desktop/electron/services/vault-credentials.ts index 3e38e20f..277d7492 100644 --- a/apps/desktop/electron/services/vault-credentials.ts +++ b/apps/desktop/electron/services/vault-credentials.ts @@ -30,6 +30,7 @@ * `assertOAuthMailHost`, and an entry holding only a token is never returned. */ import { + accountLogLabel, accountIdFor, createLogger, limitTransport, @@ -139,7 +140,7 @@ export function vaultIdCandidates(accountId: string | undefined | null, username const acct = registryAccount(accountId); if (acct) ids.push(accountIdFor(acct.email, acct.imapConfig?.host)); } catch (error) { - logger.warn(`[Vault] account registry unreadable while resolving ids for ${accountId}: ${(error as Error).message}`); + logger.warn(`[Vault] account registry unreadable while resolving ids for ${accountLogLabel(accountId)}: ${(error as Error).message}`); } } ids.push(accountIdFor(username, host), accountIdFor(username)); @@ -258,7 +259,7 @@ async function savedTransport(id: string, kind: VaultCredentialKind, entry: Vaul allowPlaintext: typeof entry.allowPlaintext === 'boolean' ? entry.allowPlaintext : legacy.allowPlaintext, }; await bindAccountSecretTransport(id, kind, bound); - logger.info(`[Vault] bound how the saved ${kind} password for ${id} is sent: self-signed ${bound.allowInsecureTLS ? 'allowed' : 'refused'}, unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); + logger.info(`[Vault] bound how the saved ${kind} password for ${accountLogLabel(id)} is sent: self-signed ${bound.allowInsecureTLS ? 'allowed' : 'refused'}, unencrypted ${bound.allowPlaintext ? 'allowed' : 'refused'}`); return bound; } @@ -302,7 +303,7 @@ export async function resolveVaultPassword( continue; } await bindAccountSecretHost(id, kind, wanted); - logger.info(`[Vault] bound the saved ${kind} password for ${id} to ${wanted} (${decision.because})`); + logger.info(`[Vault] bound the saved ${kind} password for ${accountLogLabel(id)} to ${wanted} (${decision.because})`); } const transport = await savedTransport(id, kind, entry, wanted); if (!transport) continue; diff --git a/apps/desktop/electron/utils/file-logger.ts b/apps/desktop/electron/utils/file-logger.ts index 73cced74..c7172c59 100644 --- a/apps/desktop/electron/utils/file-logger.ts +++ b/apps/desktop/electron/utils/file-logger.ts @@ -5,9 +5,11 @@ * dir (next to sarvinbox.db), capped at 20 MB — once past the cap the oldest * half is dropped so it never grows unbounded. Enabled in BOTH dev and packaged * builds so a shipped release has a log to attach to bug reports; safe to ship - * because every line is run through redactSecrets() first (no passwords/tokens), - * and in a release run through redactEmailAddresses() too (CASA L-7: account - * and sender addresses are mailbox data). Dev keeps the addresses — the + * because every line is run through redactSecrets() first (no passwords/tokens) + * and has the home folder written as `~` (an absolute path names the user), and + * in a release run through redactEmailAddresses() and redactAccountIds() too + * (CASA L-7: account and sender addresses are mailbox data, and an account id + * spells out its owner's address). Dev keeps the addresses and ids — the * developer debugs from the dev app.log. The file (and its rotated sibling) is * readable by the owner only (0600). * @@ -18,10 +20,11 @@ */ import { chmodSync, existsSync, lstatSync, mkdirSync, renameSync, statSync, unlinkSync } from 'fs'; +import { homedir } from 'os'; import { dirname, join } from 'path'; import { inspect } from 'util'; -import { isLogLevel, redactEmailAddresses, redactSecrets, toOneLine } from '@sarvinbox/core'; +import { isLogLevel, redactAccountIds, redactEmailAddresses, redactHomeDir, redactSecrets, toOneLine } from '@sarvinbox/core'; import { app } from 'electron'; import pino from 'pino'; @@ -74,8 +77,10 @@ const LEVEL_BY_METHOD: Record = { let active = false; let logPath = ''; let bytesWritten = 0; -// Release runs: also redact email addresses from every line (set at init). +// Release runs: also redact email addresses and account ids from every line (set at init). let redactAddresses = false; +// The user's home folder, written as `~` in every line (read once at init). +let home: string | undefined; // pino's async file destination (sonic-boom): buffered, NON-blocking writes on // a background flush, with a reliable flushSync on exit. Replaces the old // synchronous appendFileSync, which stalled the main-process event loop on every @@ -110,11 +115,11 @@ function render(arg: unknown): string { return inspect(arg, { depth: 4, breakLength: Infinity }); } -/** The redaction every line gets before it is written: secrets always, email - * addresses too in a release run. */ +/** The redaction every line gets before it is written: secrets and the home + * folder always, email addresses and account ids too in a release run. */ function scrub(text: string): string { - const safe = redactSecrets(text); - return redactAddresses ? redactEmailAddresses(safe) : safe; + const safe = redactHomeDir(redactSecrets(text), home); + return redactAddresses ? redactAccountIds(redactEmailAddresses(safe)) : safe; } /** @@ -184,7 +189,9 @@ function write(method: string, args: unknown[]): void { // fall back to the console method for raw console.* calls. const prefix = LOGGER_PREFIX.exec(raw); const level = prefix?.[1] ?? LEVEL_BY_METHOD[method] ?? method.toUpperCase(); - const name = prefix?.[2]; + // The name is scrubbed like the text: a backfill's names its database + // file, and a legacy file name is built from the account's address. + const name = prefix?.[2] ? scrub(prefix[2]) : undefined; const message = scrub(raw.replace(LOGGER_PREFIX, '')); const line = `[${timestamp()}] [${level}] ${name ? `[${name}] ` : ''}${message}\n`; stream.write(line); @@ -235,9 +242,9 @@ export function appendExternalLog(source: string, level: unknown, name: unknown, export interface FileLoggerOptions { /** - * Redact email addresses from every line. main.ts passes `!isDev`: a - * release's app.log must not name the user's accounts or correspondents, - * while the dev log keeps them for debugging. Decided by `isDevBuild()`, not + * Redact email addresses and account ids from every line. main.ts passes + * `!isDev`: a release's app.log must not name the user's accounts or + * correspondents, while the dev log keeps them for debugging. Decided by `isDevBuild()`, not * `app.isPackaged`, which misreports in dev (see the header). */ redactAddresses?: boolean; @@ -251,6 +258,7 @@ export function initFileLogger(options: FileLoggerOptions = {}): string | null { if (active) return logPath; redactAddresses = options.redactAddresses === true; + try { home = homedir(); } catch { home = undefined; } logPath = join(app.getPath('userData'), 'app.log'); try { mkdirSync(dirname(logPath), { recursive: true }); } catch { /* dir exists */ } bytesWritten = existsSync(logPath) ? statSync(logPath).size : 0; @@ -282,7 +290,8 @@ export function initFileLogger(options: FileLoggerOptions = {}): string | null { process.on('exit', flushFileLogger); } catch { /* ignore */ } - console.log(`[file-logger] writing local logs to ${logPath} (cap ${MAX_BYTES / (1024 * 1024)} MB)`); + // Where the file is, without the absolute path: the home folder names the user. + console.log(`[file-logger] writing local logs to /app.log (cap ${MAX_BYTES / (1024 * 1024)} MB)`); // Flush the first line immediately so app.log proves itself on startup rather // than depending on the 1s timer / a later burst. flushFileLogger(); diff --git a/apps/desktop/electron/utils/log-path.ts b/apps/desktop/electron/utils/log-path.ts new file mode 100644 index 00000000..1142170e --- /dev/null +++ b/apps/desktop/electron/utils/log-path.ts @@ -0,0 +1,35 @@ +import { homedir } from 'os'; + +import { pathForLog, redactHomeDir } from '@sarvinbox/core'; +import { app } from 'electron'; + +function home(): string | undefined { + try { + return homedir(); + } catch { + return undefined; + } +} + +function userData(): string | undefined { + try { + return app.getPath('userData'); + } catch { + return undefined; + } +} + +/** + * A path for a main-process log line: `/…`, `~/…` or the file name + * (core's `pathForLog`, rooted at this app's data folder and the user's home). + * Use it wherever a line would otherwise print an absolute path, which names + * the user through their home folder. + */ +export function logPath(path: unknown): string { + return pathForLog(path, { userData: userData(), home: home() }); +} + +/** `text` with the user's home folder written as `~` (core's `redactHomeDir`). */ +export function withoutHomeDir(text: string): string { + return redactHomeDir(text, home()); +} diff --git a/apps/desktop/electron/v8-flags.ts b/apps/desktop/electron/v8-flags.ts new file mode 100644 index 00000000..2b89f438 --- /dev/null +++ b/apps/desktop/electron/v8-flags.ts @@ -0,0 +1,24 @@ +/** + * The V8 flags the app runs with. + * + * `--js-flags` is not only main's: Chromium hands it on to every renderer it starts, + * the extension sandboxes included. So this heap cap is also how much memory an + * extension's code can take before it runs out and is stopped. + * + * One source for it, because the sandbox-escape harness must run extension code under + * the same cap the app ships. Without it, the harness's out-of-memory probe filled the + * default ~3.7 GB heap instead of 2 GB. On a 7 GB macOS CI runner that pushed the + * machine into swap, and the next sandbox start overran its load timeout about one + * run in six. + */ + +/** Old-space heap limit, in MB, for main and every renderer. */ +export const V8_MAX_OLD_SPACE_MB = 2048; + +/** + * The `--js-flags` value: the heap cap, plus anything a caller adds. `extra` must begin + * with a space. + */ +export function appJsFlags(extra = ''): string { + return `--max-old-space-size=${V8_MAX_OLD_SPACE_MB}${extra}`; +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index cef87900..92c4e2af 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -58,7 +58,7 @@ "dompurify": "^3.4.17", "electron-updater": "^6.8.9", "email-addresses": "^5.0.0", - "fast-xml-parser": "^5.5.6", + "fast-xml-parser": "^5.12.0", "fflate": "^0.8.3", "html-to-text": "^10.0.1", "ical.js": "^2.2.1", diff --git a/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx b/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx index b93222bf..62673056 100644 --- a/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx +++ b/apps/desktop/src/components/aibox/AIBoxCategoryView.tsx @@ -1,4 +1,5 @@ import type { EmailRecord } from '@sarvinbox/core'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; import { Loader2 } from 'lucide-react'; import { useState, useEffect } from 'react'; @@ -69,7 +70,7 @@ export function AIBoxCategoryView({ setEmails(result.data); } } catch (error) { - console.error('Failed to load AI category emails:', error); + console.error('Failed to load AI category emails:', errorDiagnostic(error)); } finally { setLoadingAICategoryEmails(false); } diff --git a/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts b/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts index 92609d21..9c066468 100644 --- a/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts +++ b/apps/desktop/src/components/email-detail/hooks/useFirstEmailSplit.ts @@ -24,6 +24,7 @@ * persisted failure gets its own automatic retry when it is due. */ import type { EmailRecord } from '@sarvinbox/core'; +import { failureCause } from '@sarvinbox/core/error-diagnostic'; import { FIRST_SPLIT_BACKOFF_CAP_SECONDS, firstMemberKeyOf, @@ -35,6 +36,7 @@ import { type FirstSplitRow, type FirstSplitState, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -159,7 +161,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail bridge.get(accountId, threadId).then( (result) => { if (!result.success || !result.data) { - if (live) log.warn(`get acct=${accountId} thread=${threadId} failed: ${result.error ?? 'no data'}`); + if (live) log.warn(`get acct=${accountLogLabel(accountId)} thread=${threadId} failed: ${result.error ? 'error' : 'no data'}`); land(null); return; } @@ -170,7 +172,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail // it caches belongs to this email. Once per email, not per read. if (live && warnedRef.current !== identity) { warnedRef.current = identity; - log.warn(`acct=${accountId} thread=${threadId} main's first member is not the one on screen — no AI split for it`); + log.warn(`acct=${accountLogLabel(accountId)} thread=${threadId} main's first member is not the one on screen — no AI split for it`); } land(null); return; @@ -178,7 +180,7 @@ export function useFirstEmailSplit(input: FirstEmailSplitInput, deps: FirstEmail land(result.data); }, (error: unknown) => { - if (live) log.warn(`get acct=${accountId} thread=${threadId} threw: ${(error as Error)?.message ?? error}`); + if (live) log.warn(`get acct=${accountLogLabel(accountId)} thread=${threadId} threw: ${failureCause(error)}`); land(null); }, ); diff --git a/apps/desktop/src/hooks/useKeyboardShortcuts.ts b/apps/desktop/src/hooks/useKeyboardShortcuts.ts index 5cb59935..429576f1 100644 --- a/apps/desktop/src/hooks/useKeyboardShortcuts.ts +++ b/apps/desktop/src/hooks/useKeyboardShortcuts.ts @@ -1,5 +1,6 @@ import type { EmailRecord } from '@sarvinbox/core'; import { conversationFoldersOf, latestConversationMember } from '@sarvinbox/core/conversation-membership'; +import { createLogger } from '@sarvinbox/core/logger'; import { useEffect, useRef } from 'react'; import type { AppSection } from '../components/AppSidebar'; @@ -11,6 +12,7 @@ import { type GotoTarget, } from '../config/keyboard-shortcuts'; import { useEmailStore } from '../store/email-store'; +import { isTypingTarget } from '../utils/frame-key-forwarding'; import { conversationStarToggle } from '../utils/thread-utils'; interface UseKeyboardShortcutsOptions { @@ -20,6 +22,8 @@ interface UseKeyboardShortcutsOptions { allowListNavigation?: boolean; } +const log = createLogger('Shortcuts'); + // Next/prev-email navigation always opens a different thread and thus triggers // a thread load + IMAP body fetch. OS key-repeat (holding the arrow) is // swallowed for these so a held key can't flood the connection pool; discrete @@ -42,14 +46,6 @@ function isKeyboardShortcutsEnabled(): boolean { return true; } -function isTypingTarget(el: EventTarget | null): boolean { - if (!el || !(el instanceof HTMLElement)) return false; - const tag = el.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true; - if (el.isContentEditable) return true; - return false; -} - function getActiveEmailId(): string | null { const state = useEmailStore.getState(); return state.selectedEmailId || state.highlightedEmailId; @@ -147,10 +143,10 @@ export function useKeyboardShortcuts({ setActiveSection, focusSearch, enabled = waitingForGotoRef.current = true; if (gotoTimerRef.current) clearTimeout(gotoTimerRef.current); gotoTimerRef.current = setTimeout(() => { - console.log('[Shortcuts] Go-to mode timed out'); + log.debug('Go-to mode timed out'); waitingForGotoRef.current = false; }, GOTO_TIMEOUT_MS); - console.log('[Shortcuts] Go-to mode activated — press target key within 1s'); + log.debug('Go-to mode activated — press target key within 1s'); e.preventDefault(); return; } @@ -165,7 +161,7 @@ export function useKeyboardShortcuts({ setActiveSection, focusSearch, enabled = const gotoRecord = getEffectiveGotoRecord(); const target: GotoTarget | undefined = gotoRecord[e.key]; - console.log('[Shortcuts] Go-to key:', e.key, '→ target:', target || '(no match)'); + log.debug(`Go-to key resolved: ${target ? 'matched' : 'no match'}`); if (target) { e.preventDefault(); handleGoto(target); diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx index 9ebffe64..4ae57fb0 100644 --- a/apps/desktop/src/main.tsx +++ b/apps/desktop/src/main.tsx @@ -16,6 +16,7 @@ import { AttachmentTransferProvider } from './components/attachment-viewer/Attac import { SentryErrorBoundary } from './components/SentryErrorBoundary'; import { initSentryRenderer } from './sentry'; import { useEmailStore } from './store/email-store'; +import { installFrameKeyForwarding } from './utils/frame-key-forwarding'; import './index.css'; // The chat view's own stylesheet, then the bridge that repoints its `--sec-*` // tokens at this app's theme. Order matters: the bridge must win over the @@ -31,6 +32,10 @@ initSentryRenderer(); // render, or the app shows one frame of the default light theme and then flips. initAppearance(); +// Keyboard shortcuts must survive a click inside a mail body's sandboxed frame +// (which takes keyboard focus away from this document). See the module header. +installFrameKeyForwarding(); + createRoot(document.getElementById('root')!).render( diff --git a/apps/desktop/src/services/first-split/job.ts b/apps/desktop/src/services/first-split/job.ts index 7040a24f..5e6f8e45 100644 --- a/apps/desktop/src/services/first-split/job.ts +++ b/apps/desktop/src/services/first-split/job.ts @@ -23,10 +23,12 @@ * item, for a switch flipped mid-drain. Refs are deduped (per account * and thread) into one queue, capped, and drained serially. */ +import { failureCause } from '@sarvinbox/core/error-diagnostic'; import { firstSplitStateFor, type FirstSplitGetResult, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { aiEligibilityFor, firstEmailFacts } from '../../components/email-detail/ai-view-compose'; @@ -103,7 +105,7 @@ export async function processCandidate(ref: FirstSplitRef, deps: FirstSplitJobDe const bridge = deps.bridge ?? defaultFirstSplitBridge; const answer = await bridge.get(ref.accountId, ref.threadId, { withSource: true }); if (!answer.success || !answer.data) { - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} get failed`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} get failed`); return 'error'; } const got: FirstSplitGetResult = answer.data; @@ -172,14 +174,14 @@ export function createFirstSplitJob(deps: FirstSplitJobDeps = {}): FirstSplitJob try { result = await processCandidate(ref, deps); } catch (error) { - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} threw: ${(error as Error)?.message ?? error}`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} threw: ${failureCause(error)}`); result = 'error'; } finally { known.delete(`${ref.accountId}|${ref.threadId}`); } tally[result] += 1; processed += 1; - log.trace(`thread acct=${ref.accountId} thread=${ref.threadId} -> ${result}`); + log.trace(`thread acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} -> ${result}`); } // Only drained with at least one ref, so at least one count is non-zero. const counts = (Object.keys(tally) as JobItemResult[]) diff --git a/apps/desktop/src/services/first-split/store.ts b/apps/desktop/src/services/first-split/store.ts index f0ad4984..9739550d 100644 --- a/apps/desktop/src/services/first-split/store.ts +++ b/apps/desktop/src/services/first-split/store.ts @@ -39,6 +39,7 @@ import { type FirstSplitSaveRequest, type FirstSplitSaveResult, } from '@sarvinbox/core/first-split'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { createSingleFlight } from '@sarvinbox/core/single-flight'; @@ -212,7 +213,8 @@ async function run( if (!got) { const answer = await bridge.get(ref.accountId, ref.threadId, { withSource: true }); if (!answer.success || !answer.data) { - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} get failed: ${answer.error ?? 'no data'}`); + // Whether main said why, not what it said: its error text can quote the stored record. + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} get failed: ${answer.error ? 'error' : 'no data'}`); return { state: 'error', error: answer.error ?? 'no data' }; } got = answer.data; @@ -221,7 +223,7 @@ async function run( if (!current || !source || !(source.rawBody ?? '').trim()) return { state: 'unknown' }; // Main hands back its own first member; a record that is not it cannot be split under this key. if (firstMemberKeyOf(source) !== current.firstKey) { - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} source is not the first member — not run`); + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} source is not the first member — not run`); return { state: 'unknown' }; } if (!force && isUsableSplit(row, current)) return { state: 'usable', current, row: row! }; @@ -271,7 +273,7 @@ async function splitAndSave( hub.publish({ running: false, status: null }); } const seconds = ((Date.now() - started) / 1000).toFixed(1); - const line = `split acct=${ref.accountId} thread=${ref.threadId} trigger=${options.trigger} ${countsOf(outcome)}`; + const line = `split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} trigger=${options.trigger} ${countsOf(outcome)}`; if (outcome.status === 'provider') { log.warn(`${line} status=provider (nothing saved) ${seconds}s: ${outcome.reason ?? ''}`); @@ -288,7 +290,7 @@ async function splitAndSave( }; const saved = await bridge.save(ref.accountId, request); if (!saved.success || !saved.data) { - log.warn(`${line} status=${outcome.status} save failed ${seconds}s: ${saved.error ?? 'no data'}`); + log.warn(`${line} status=${outcome.status} save failed ${seconds}s: ${saved.error ? 'error' : 'no data'}`); return { state: 'error', error: saved.error ?? 'no data' }; } const result = saved.data.applied ? `saved=${saved.data.status ?? outcome.status}` : `not-saved=${saved.data.reason}`; @@ -314,7 +316,7 @@ export function runFirstSplit( const message = error instanceof Error ? error.message : String(error); // By class, code and status: the message of a split that threw can quote // the email it was splitting, or a provider's response body. - log.warn(`split acct=${ref.accountId} thread=${ref.threadId} threw`, errorDiagnostic(error)); + log.warn(`split acct=${accountLogLabel(ref.accountId)} thread=${ref.threadId} threw`, errorDiagnostic(error)); return { state: 'error', error: message }; } }); diff --git a/apps/desktop/src/store/slices/connection-slice.ts b/apps/desktop/src/store/slices/connection-slice.ts index 242555d6..aedb1cf5 100644 --- a/apps/desktop/src/store/slices/connection-slice.ts +++ b/apps/desktop/src/store/slices/connection-slice.ts @@ -1,4 +1,5 @@ import type { SMTPConfig } from '@sarvinbox/core'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { createSingleFlight } from '@sarvinbox/core/single-flight'; @@ -355,7 +356,7 @@ const connectionSlice = ( const pending = connectInFlight.pending(acctId); if (pending) { - console.log(`[Store] connect() already in flight for ${acctId} — joining it`); + console.log(`[Store] connect() already in flight for ${accountLogLabel(acctId)} — joining it`); return pending; } diff --git a/apps/desktop/src/store/slices/email-actions-slice.ts b/apps/desktop/src/store/slices/email-actions-slice.ts index ee646857..503d2bf1 100644 --- a/apps/desktop/src/store/slices/email-actions-slice.ts +++ b/apps/desktop/src/store/slices/email-actions-slice.ts @@ -5,6 +5,7 @@ // declared in vite.config.ts, vitest.config.ts and tsconfig.json. import { conversationFoldersOf, isDraftRow } from '@sarvinbox/core/conversation-membership'; import { classifyFolder, isStarredFolder } from '@sarvinbox/core/folder-mapping'; +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { addTag, removeTag, hasTag } from '../../utils/tags'; @@ -430,7 +431,7 @@ async function dispatchBulkByAccount(grouped: Map, queuedIds: ids.filter((id) => result.data!.queuedIds?.includes(id) && !failed.has(id)), }; } catch (error) { - console.warn('[Store] bulkAction failed for account', acct ?? '(active)', error); + console.warn('[Store] bulkAction failed for account', accountLogLabel(acct, '(active)'), error); return { processedIds: [], failedIds: ids, queuedIds: [] }; } })); diff --git a/apps/desktop/src/store/slices/emails-slice.ts b/apps/desktop/src/store/slices/emails-slice.ts index ec75fc91..8ebe620e 100644 --- a/apps/desktop/src/store/slices/emails-slice.ts +++ b/apps/desktop/src/store/slices/emails-slice.ts @@ -5,6 +5,8 @@ import { isDraftRow, isExcludedFolderCopy, } from '@sarvinbox/core/conversation-membership'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; +import { accountLogLabel, folderLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import { clearCategoryBadgeCache } from '../../components/email-list/CategoryBadges'; @@ -458,7 +460,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ clearCategoryBadgeCache(); const selectedFolder = get().folders.find(f => f.id === folderId); - console.log(`[View] Selected folder: ${selectedFolder?.path || selectedFolder?.name || folderId} (inboxType=${get().inboxType})`); + console.log(`[View] Selected folder: ${folderLogLabel(selectedFolder?.path || selectedFolder?.name || folderId)} (inboxType=${get().inboxType})`); // NOTE: sectionData is intentionally NOT cleared here. It only ever // holds INBOX section data and is only rendered in the INBOX sectioned // view, so keeping it cached lets a return to INBOX show the previous @@ -490,9 +492,9 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ if (folder && !get().syncing && get().connectionStatus !== 'disconnected') { const { syncingFolders } = get(); if (syncingFolders.has(folder.path)) { - console.log(`[Store] Skipping sync for ${folder.path} - this folder already syncing`); + console.log(`[Store] Skipping sync for ${folderLogLabel(folder.path)} - this folder already syncing`); } else { - console.log(`[Store] Starting background sync for folder: ${folder.path}`); + console.log(`[Store] Starting background sync for folder: ${folderLogLabel(folder.path)}`); // syncSingleFolder now owns the post-sync view-refresh routing // (AI-category → loadAICategoryEmails, sectioned INBOX → // loadAllSections, flat → mergeNewEmails, virtual-all/starred @@ -501,7 +503,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // callers of syncSingleFolder (ensureConnectionAndSync's // periodic poll, etc.) missed the section/AI-category refresh. get().syncSingleFolder(folder.path).catch((err) => { - console.error(`[Store] Sync failed for ${folder.path}:`, err); + console.error(`[Store] Sync failed for ${folderLogLabel(folder.path)}:`, errorDiagnostic(err)); }); } } @@ -545,7 +547,8 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ const folderName = selectedFolderId ? folders.find(f => f.id === selectedFolderId)?.path : null; // `AI:category`, never the slug: a custom category's slug is made from the // name the user typed. Built-in views (virtual folders, snoozed) are ours. - const view = viewingAICategory ? 'AI:category' : selectedVirtualFolder || (viewingSnoozed ? 'snoozed' : folderName || 'unknown'); + // A folder the user named is written as its label (folderLogLabel). + const view = viewingAICategory ? 'AI:category' : selectedVirtualFolder || (viewingSnoozed ? 'snoozed' : folderName ? folderLogLabel(folderName) : 'unknown'); // `search=set`, never the query: it is what the user typed, and this line // repeats on every email opened while a search is active. log.info(`[View] selectEmail id=${emailId ? emailId.substring(0, 12) + '...' : 'null'}, view=${view}${searchQuery ? ', search=set' : ''}, pool=${get().emails.length} emails`); @@ -722,7 +725,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // (`maxMessages: localTotal + PAGE_SIZE` grew every scroll). The backfill // scheduler also runs continuously, so most scrolls are already covered — // this just nudges it — and it yields to any in-flight foreground sync. - console.log(`[Store] loadMoreEmails: local exhausted (${localTotal}), server has ${serverTotal} — nudging backfill for ${selectedFolder.path}`); + console.log(`[Store] loadMoreEmails: local exhausted (${localTotal}), server has ${serverTotal} — nudging backfill for ${folderLogLabel(selectedFolder.path)}`); const res = await window.electronAPI.imap.backfillChunk(selectedFolder.path); const inserted = res?.success ? (res.data?.inserted ?? 0) : 0; @@ -1403,19 +1406,19 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ if (targets.length === 0) return; bgSyncRunning = true; - console.log('[TierB] cycle start — targets:', targets.map((a) => `${a.email}@${a.imapConfig?.host}`)); + console.log('[TierB] cycle start — targets:', targets.map((a) => accountLogLabel(a.id))); try { // Serial: one account at a time to avoid a connection storm (up to 10 // accounts). Each is isolated so one failure never stops the rest. for (const acct of targets) { try { const res = await window.electronAPI.accounts.backgroundSync({ accountId: acct.id, config: acct.imapConfig }); - console.log('[TierB] backgroundSync result for', acct.email, '@', acct.imapConfig?.host, '→', res); + console.log('[TierB] backgroundSync result for', accountLogLabel(acct.id), '→', res); if (res?.success && res.data) { set({ accountUnread: { ...get().accountUnread, [acct.id]: res.data.unread } }); } } catch (e) { - console.warn('[TierB] backgroundSync failed for', acct.id, (e as Error)?.message); + console.warn('[TierB] backgroundSync failed for', accountLogLabel(acct.id), (e as Error)?.message); } } // If the merged view is open, refresh it so newly-synced mail appears. @@ -1611,7 +1614,7 @@ export const createEmailsSlice: SliceCreator = (set, get) => ({ // (5/10/25/50; default 25). Clicking the count opens the full paginated page. const section = get().inboxSections.find((s) => s.id === sectionId); const pageSize = section?.maxItems && section.maxItems > 0 ? section.maxItems : 25; - console.log(`[View] loadSectionEmails section=${sectionId}, filter=${filter}, folderPath=${folderPath || 'all'}, pageSize=${pageSize}`); + console.log(`[View] loadSectionEmails section=${sectionId}, filter=${filter}, folderPath=${folderPath ? folderLogLabel(folderPath) : 'all'}, pageSize=${pageSize}`); // Mark section loading const newLoading = new Set(get().sectionLoading); diff --git a/apps/desktop/src/store/slices/sync-slice.ts b/apps/desktop/src/store/slices/sync-slice.ts index 1073a9c9..265e8c8d 100644 --- a/apps/desktop/src/store/slices/sync-slice.ts +++ b/apps/desktop/src/store/slices/sync-slice.ts @@ -1,6 +1,8 @@ import type { RealtimeEvent } from '@sarvinbox/core'; import { sentFolderPathsOf } from '@sarvinbox/core/conversation-membership'; +import { errorDiagnostic } from '@sarvinbox/core/error-diagnostic'; import { isSentMailFolder } from '@sarvinbox/core/folder-mapping'; +import { folderLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; import pLimit from 'p-limit'; @@ -178,7 +180,7 @@ export async function refreshVisibleViewForFolder( // AI-categorized view (Needs Response, Reminders, etc.). Never the // slug: a custom category's slug is made from the name the user typed, // and this branch only runs with one set. - log.info(`[Store] refreshView: re-fetching AI category (aiCategory=set) after ${folderPath} sync`); + log.info(`[Store] refreshView: re-fetching AI category (aiCategory=set) after ${folderLogLabel(folderPath)} sync`); await state.loadAICategoryEmails?.(state.viewingAICategory); } else if ( isCurrentFolder && @@ -189,7 +191,7 @@ export async function refreshVisibleViewForFolder( // SECTIONED INBOX. Visible data lives in `sectionData`, not // `emails` — a plain mergeNewEmails would update the wrong // store slot and look like a no-op to the user. - console.log(`[Store] refreshView: reloading sections for ${folderPath}`); + console.log(`[Store] refreshView: reloading sections for ${folderLogLabel(folderPath)}`); await state.loadAllSections?.(folderPath); } else if (isCurrentFolder) { // Flat folder view — diff against `emails` and prepend new rows. @@ -203,7 +205,7 @@ export async function refreshVisibleViewForFolder( // view not matching the folder): leave the list alone, only the // sidebar badge updates via loadFolders elsewhere. } catch (err) { - console.warn(`[Store] refreshVisibleViewForFolder failed for ${folderPath}:`, err); + console.warn(`[Store] refreshVisibleViewForFolder failed for ${folderLogLabel(folderPath)}:`, errorDiagnostic(err)); } } @@ -720,11 +722,11 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ syncSingleFolder: async (folderPath) => { // Only allow one sync operation at a time — avoids connection pool exhaustion if (get().syncing || get().syncingFolders.size > 0) { - console.log(`[Store] syncSingleFolder: Skipping ${folderPath} — another sync in progress`); + console.log(`[Store] syncSingleFolder: Skipping ${folderLogLabel(folderPath)} — another sync in progress`); return; } - console.log(`[Store] syncSingleFolder: Starting sync for ${folderPath}`); + console.log(`[Store] syncSingleFolder: Starting sync for ${folderLogLabel(folderPath)}`); const newSyncingFolders = new Map(get().syncingFolders); newSyncingFolders.set(folderPath, Date.now()); @@ -740,7 +742,8 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ skipUnchanged: false, }); - console.log(`[Store] syncSingleFolder: ${folderPath} sync result:`, result.success ? 'success' : result.error); + // Not the error text: a server's message can quote the folder's name. + console.log(`[Store] syncSingleFolder: ${folderLogLabel(folderPath)} sync result:`, result.success ? 'success' : 'failed'); if (result.success) { get().noteSyncOk(); @@ -751,14 +754,14 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ get().noteSyncFailure(result.error); } } catch (error) { - console.error(`[Store] syncSingleFolder: Failed to sync ${folderPath}:`, error); + console.error(`[Store] syncSingleFolder: Failed to sync ${folderLogLabel(folderPath)}:`, errorDiagnostic(error)); get().noteSyncFailure(error); } finally { const currentSyncingFolders = get().syncingFolders; const updatedSyncingFolders = new Map(currentSyncingFolders); updatedSyncingFolders.delete(folderPath); set({ syncingFolders: updatedSyncingFolders }); - console.log(`[Store] syncSingleFolder: ${folderPath} sync complete`); + console.log(`[Store] syncSingleFolder: ${folderLogLabel(folderPath)} sync complete`); } }, @@ -843,7 +846,7 @@ export const createSyncSlice: SliceCreator = (set, get) => ({ // Remove any existing listener first to prevent accumulation window.electronAPI.imap.removeRealtimeEventListener(); - console.log('[Store] Setting up IDLE event listener for folder:', folderPath); + console.log('[Store] Setting up IDLE event listener for folder:', folderLogLabel(folderPath)); // No logging in this callback: it fires once per message, so a flag // reconcile would emit hundreds of console writes on the UI thread. // The coalescer logs one aggregate line per flush instead. diff --git a/apps/desktop/src/utils/account-scoped-cache.ts b/apps/desktop/src/utils/account-scoped-cache.ts index 1fb180f3..d2cfd95a 100644 --- a/apps/desktop/src/utils/account-scoped-cache.ts +++ b/apps/desktop/src/utils/account-scoped-cache.ts @@ -24,6 +24,7 @@ // * OPTIMISTIC WRITES THAT CAN FAIL. A write shows immediately, survives a load // that races it, and is rolled back if the main process refuses it. +import { accountLogLabel } from '@sarvinbox/core/log-labels'; import { createLogger } from '@sarvinbox/core/logger'; const log = createLogger('AccountScopedCache'); @@ -148,7 +149,8 @@ export function createAccountScopedCache(options: AccountScopedCacheOptions accountId || activeAccount || UNKNOWN_ACTIVE; const argFor = (key: string): string | undefined => (key === UNKNOWN_ACTIVE ? undefined : key); - const label = (key: string) => (key === UNKNOWN_ACTIVE ? 'the active account' : key); + // An account id spells out the address it was built from: written as its label. + const label = (key: string) => (key === UNKNOWN_ACTIVE ? 'the active account' : accountLogLabel(key)); const entryFor = (key: string): Entry => { let entry = entries.get(key); diff --git a/apps/desktop/src/utils/frame-key-forwarding.ts b/apps/desktop/src/utils/frame-key-forwarding.ts new file mode 100644 index 00000000..6ca32292 --- /dev/null +++ b/apps/desktop/src/utils/frame-key-forwarding.ts @@ -0,0 +1,119 @@ +/** + * Keyboard shortcuts keep working after a click inside a mail body. + * + * A mail body renders in a sandboxed `