Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Changing a whole conversation leaves your own mail alone.** When the agent
changes every email in a conversation, it never touches your drafts, and a
move to a folder leaves your own sent replies in Sent.
- **See what the AI did to each email.** An email the AI changed (marked read
or unread, starred, archived, moved, labelled, snoozed, reported as spam, or
replied to with a draft or a sent reply) now shows a small AI mark before its
time in the list. Point at it to see what the AI did, when, and whether it
happened automatically or you approved it. Undo takes the mark away again.
AI → Dashboard has a new "What the AI did" panel that counts these actions by
kind, and how many emails the AI has sorted into categories. Sorting alone
gets no mark, since the AI sorts nearly every email.

### Changed
- **Inbox Agent asks again before changing mail in conversations where
Expand All @@ -94,6 +102,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
always ask, and it never sends mail or deletes it permanently. The mode
cannot be changed while the agent is working on a request: stop the request
first.
- **Stop an attachment download from the attachment itself.** While an
attachment downloads or is scanned, its chip in the message shows a spinner
with a stop button in place of a progress line under it. The downloads panel
still shows the full progress.

### Removed
- **The unread and uncategorized mail review cards.** This includes **Mark
Expand Down
8 changes: 8 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,14 @@ Established shared helpers (extend this list as you add more):
an extension archive (allowlisted paths, plain files and the expected folders,
never links). The installer and the build-time seed both unpack with it.

- `recordAiActions(storage, ids, kind, { auto })` / `forgetAiActions(storage, ids, kind)` —
`apps/desktop/electron/services/ai-action-record.ts`, over `parseAiActions` /
`appendAiAction` / `describeAiAction` in `packages/core/src/utils/ai-actions.ts`
(renderer: `@sarvinbox/core/ai-actions`). The one way to say what the AI did
to an email (`emails.ai_actions`, the list's AI mark): stamps the row, tells the
open list, never throws. Background actions are stamped by `logUserAction`
(source `agent_auto`); Inbox Agent change sets stamp where they apply and undo.
Any new AI path that changes mail calls it, and takes it back on Undo.
- `errorDiagnostic(error)` — `packages/core/src/utils/error-diagnostic.ts`. What a
caught failure WAS (`{ name, code?, status? }`) and nothing of what it was
working on. Use it at any `catch` whose record outlives the request (a saved
Expand Down
26 changes: 25 additions & 1 deletion apps/desktop/electron/ipc/agent-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
*/

import type { UserActionType, ActionSource } from '@sarvinbox/core';
import { accountLogLabel, createLogger, setEmailReadFlag } from '@sarvinbox/core';
import { accountLogLabel, aiActionKindForLoggedAction, createLogger, setEmailReadFlag } from '@sarvinbox/core';
import { ipcMain } from 'electron';

import { openAccountStorages, requireNamedOrActiveStorage, requireTargetAccountId } from '../services/account-target';
import { resolveAccountIdentity } from '../services/accounts-registry';
import { saveAgentConfig, loadAgentConfig } from '../services/agent-config-store';
import { forgetAiActions, recordAiActions } from '../services/ai-action-record';
import { refreshContactClassifications } from '../services/contact-classification-service';
import { buildThreadMessages } from '../services/thread-context';
import { getIntelligence, getUnifiedPipeline, setPipelineUserProfile, getPipelineAIConfig } from '../services/unified-pipeline-service';
Expand Down Expand Up @@ -137,6 +138,14 @@ export async function logUserAction(
createdAt: Math.floor(Date.now() / 1000),
});

// What the background AI did, on the email's own row for the list's AI
// icon. Only 'agent_auto': the Inbox Agent records its own changes where
// it applies them (it knows approved from automatic, and undoes them).
if (options.source === 'agent_auto') {
const kind = aiActionKindForLoggedAction(actionType, options.actionValue);
if (kind) recordAiActions(storage, [emailId], kind, { auto: true });
}

// The timeline retains every source for activity/undo. Engagement must
// describe the human's choices, not feed an agent's own decisions back
// into categorization as if the user had read or discarded that mail.
Expand Down Expand Up @@ -252,6 +261,15 @@ export function registerAgentHandlers(): void {
}
});

// The AI section's counts of what the AI did (emails.ai_actions).
ipcMain.handle('agent:getAiActionCounts', async () => {
try {
return { success: true, data: getAgentRepo().getAiActionCounts() };
} catch (error) {
return { success: false, error: (error as Error).message };
}
});

ipcMain.handle('agent:getActionStats', async (_event, since?: number) => {
try {
const agentRepo = getAgentRepo();
Expand Down Expand Up @@ -630,6 +648,12 @@ export function registerAgentHandlers(): void {
}, storage);
}

// The undone action no longer describes the email.
if (action.source === 'agent_auto' || action.source === 'agent_approved') {
const kind = aiActionKindForLoggedAction(action.actionType, action.actionValue);
if (kind) forgetAiActions(storage, [action.emailId], kind);
}

logger.info(`[Agent] Undo: reversed ${action.actionType} on ${action.emailId}`);
return { success: true, data: { undone: action.actionType, emailId: action.emailId } };
} catch (error) { return { success: false, error: (error as Error).message }; }
Expand Down
8 changes: 8 additions & 0 deletions apps/desktop/electron/ipc/inbox-assistant-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ipcMain, type IpcMainInvokeEvent } from 'electron';
import type { InboxAssistantActivity, InboxAssistantAIUsage } from '../../src/types/inbox-assistant';
import { requireAccountStorage, resolveNamedOrActiveAccountTarget } from '../services/account-target';
import { readRegistryAccounts, resolveAccountIdentity } from '../services/accounts-registry';
import { forgetAiActions, recordAiActions } from '../services/ai-action-record';
import { readAssistantAttachment } from '../services/assistant-attachment-reader';
import { changeAssistantReadFlags, changeAssistantStarFlags } from '../services/assistant-mail-actions';
import { changeAssistantMailLocation } from '../services/assistant-mail-moves';
Expand Down Expand Up @@ -195,6 +196,13 @@ const service = new InboxAssistantService({
const target = await agentTarget(accountId);
return revertAgentSpamVerdicts(target, verdictDepsOf(target.storage, target.engine), rows);
},
// The list's AI icon (emails.ai_actions): approved or automatic, and gone again on Undo.
recordAiActions: async (accountId, emailIds, kind, auto) => {
recordAiActions((await namedAccountTarget(accountId)).storage, emailIds, kind, { auto, accountId });
},
forgetAiActions: async (accountId, emailIds, kind) => {
forgetAiActions((await namedAccountTarget(accountId)).storage, emailIds, kind, { accountId });
},
},
});

Expand Down
21 changes: 20 additions & 1 deletion apps/desktop/electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// preload script. Safe/no-op when Sentry has no DSN configured.
import '@sentry/electron/preload';

import type { AntivirusSetupStatus, IMAPConfig, SyncEngineOptions, SyncStatus, RealtimeEvent, SMTPConfig, SendEmailOptions, FilterRule, FilterRuleInput, FilterCondition, Label, LabelInput, EmailRecord, ViewFilter , SpamUserVerdict, AvailablePanel, PanelResponse, AccountFollowUp, DraftResult, FirstSplitClearAllResult, FirstSplitGetResult, FirstSplitSaveRequest, FirstSplitSaveResult, SarvCatalogResult } from '@sarvinbox/core';
import type { AiAction, AiActionKind, AntivirusSetupStatus, IMAPConfig, SyncEngineOptions, SyncStatus, RealtimeEvent, SMTPConfig, SendEmailOptions, FilterRule, FilterRuleInput, FilterCondition, Label, LabelInput, EmailRecord, ViewFilter , SpamUserVerdict, AvailablePanel, PanelResponse, AccountFollowUp, DraftResult, FirstSplitClearAllResult, FirstSplitGetResult, FirstSplitSaveRequest, FirstSplitSaveResult, SarvCatalogResult } from '@sarvinbox/core';
import { contextBridge, ipcRenderer, webFrame } from 'electron';

import type { DefaultAppsAPI } from '../src/types/default-apps';
Expand Down Expand Up @@ -444,6 +444,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.on('emails:tags-updated', handler);
return () => ipcRenderer.removeListener('emails:tags-updated', handler);
},
// What the AI did to an email changed (emails.ai_actions): redraw its row's AI icon.
onAiActionsUpdated: (
callback: (update: { emailId: string; accountId: string | null; aiActions: AiAction[] }) => void
) => {
const handler = (
_event: unknown,
update: { emailId: string; accountId: string | null; aiActions: AiAction[] }
) => callback(update);
ipcRenderer.on('emails:ai-actions-updated', handler);
return () => ipcRenderer.removeListener('emails:ai-actions-updated', handler);
},
markStarred: (emailId: string, starred: boolean, accountId?: string) =>
ipcRenderer.invoke('emails:markStarred', emailId, starred, accountId),
markImportant: (emailId: string, important: boolean, accountId?: string) =>
Expand Down Expand Up @@ -1061,6 +1072,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('agent:getActionsByEmail', emailId),
getActionStats: (since?: number) =>
ipcRenderer.invoke('agent:getActionStats', since),
getAiActionCounts: () =>
ipcRenderer.invoke('agent:getAiActionCounts'),
// Agent decisions
getPendingDecisions: () => ipcRenderer.invoke('agent:getPendingDecisions'),
resolveDecision: (decisionId: string, status: string, actualAction?: string, feedback?: string) =>
Expand Down Expand Up @@ -1502,6 +1515,9 @@ export interface ElectronAPI {
onTagsUpdated: (
callback: (update: { emailId: string; accountId: string | null; tags: string }) => void
) => () => void;
onAiActionsUpdated: (
callback: (update: { emailId: string; accountId: string | null; aiActions: AiAction[] }) => void
) => () => void;
markStarred: (emailId: string, starred: boolean, accountId?: string) => Promise<{ success: boolean; error?: string }>;
markImportant: (emailId: string, important: boolean, accountId?: string) => Promise<{ success: boolean; error?: string }>;
moveToFolder: (emailId: string, folderId: string, accountId?: string) => Promise<{ success: boolean; error?: string }>;
Expand Down Expand Up @@ -1965,6 +1981,9 @@ export interface ElectronAPI {
Promise<{ success: boolean; data?: any[]; error?: string }>;
getActionStats: (since?: number) =>
Promise<{ success: boolean; data?: any; error?: string }>;
/** What the AI did in the active account: by kind, emails it touched, and emails it categorized. */
getAiActionCounts: () =>
Promise<{ success: boolean; data?: { byKind: Record<AiActionKind, number>; emails: number; categorized: number }; error?: string }>;
getPendingDecisions: () =>
Promise<{ success: boolean; data?: any[]; error?: string }>;
resolveDecision: (decisionId: string, status: string, actualAction?: string, feedback?: string) =>
Expand Down
64 changes: 64 additions & 0 deletions apps/desktop/electron/services/ai-action-record.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { createLogger, errorDiagnostic, parseAiActions, type AiAction, type AiActionKind } from '@sarvinbox/core';

import { getAccountIdForStorage, getMainWindow } from '../shared';

const logger = createLogger('ai-action-record');

/** The account database methods this needs (AgentRepository in storage-node). */
export interface AiActionStore {
recordAiActions(emailIds: readonly string[], action: AiAction): string[];
forgetAiActions(emailIds: readonly string[], kind: AiActionKind): string[];
getAiActionsRaw(emailId: string): string | null;
}

/** An account's AgentRepository, from the storage object the caller already holds. */
export function aiActionStoreOf(storage: unknown): AiActionStore | undefined {
try {
return (storage as { getRepositories?: () => { agent?: AiActionStore } }).getRepositories?.().agent;
} catch { return undefined; }
}

/** Tell the open list which rows now carry a different AI record. */
function announce(store: AiActionStore, ids: readonly string[], accountId: string | null): void {
const window = getMainWindow();
if (!window || window.isDestroyed()) return;
for (const emailId of ids) {
window.webContents.send('emails:ai-actions-updated', { emailId, accountId, aiActions: parseAiActions(store.getAiActionsRaw(emailId)) });
}
}

function accountOf(storage: unknown, accountId?: string | null): string | null {
if (accountId) return accountId;
try { return getAccountIdForStorage(storage as never) ?? null; } catch { return null; }
}

/**
* Stamp what the AI just did on each email's own row and redraw those rows.
*
* Never throws: the change itself already happened, and a mail action must not
* fail because its record could not be written. A failure is logged as its
* class only (no ids, no mail).
*/
export function recordAiActions(storage: unknown, emailIds: readonly string[], kind: AiActionKind, options: { auto: boolean; accountId?: string | null; nowMs?: number }): void {
if (!emailIds.length) return;
const store = aiActionStoreOf(storage);
if (!store) return;
try {
const written = store.recordAiActions(emailIds, { kind, at: Math.floor((options.nowMs ?? Date.now()) / 1000), auto: options.auto });
announce(store, written, accountOf(storage, options.accountId));
} catch (error) {
logger.warn('[AIActions] could not record an AI action', { kind, count: emailIds.length, ...errorDiagnostic(error) });
}
}

/** Take an undone AI action back off each email's row. Never throws, as above. */
export function forgetAiActions(storage: unknown, emailIds: readonly string[], kind: AiActionKind, options: { accountId?: string | null } = {}): void {
if (!emailIds.length) return;
const store = aiActionStoreOf(storage);
if (!store) return;
try {
announce(store, store.forgetAiActions(emailIds, kind), accountOf(storage, options.accountId));
} catch (error) {
logger.warn('[AIActions] could not remove an undone AI action', { kind, count: emailIds.length, ...errorDiagnostic(error) });
}
}
38 changes: 37 additions & 1 deletion apps/desktop/electron/services/inbox-assistant-change-sets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';

import { classifyFolder, existingCategoryClassification, hasTag, parseAttachmentNames, type ContactRecord, type EmailRecord, type FolderRecord } from '@sarvinbox/core';
import { classifyFolder, existingCategoryClassification, hasTag, parseAttachmentNames, type AiActionKind, type ContactRecord, type EmailRecord, type FolderRecord } from '@sarvinbox/core';

import type { InboxAssistantActionMode } from '../../src/types/inbox-assistant';
import type {
Expand Down Expand Up @@ -74,6 +74,33 @@ export interface InboxAgentMailActions {
/** The user's spam verdict, as Report spam / Not spam record it. */
spamVerdict(accountId: string, emailIds: string[], verdict: 'spam' | 'ham'): Promise<AssistantReadReceipt>;
revertSpamVerdict(accountId: string, rows: InboxAgentSpamRevert[]): Promise<AssistantReadReceipt>;
/** Stamp what the agent did on each changed email's own row (emails.ai_actions). Must not throw. */
recordAiActions?(accountId: string, emailIds: string[], kind: AiActionKind, auto: boolean): Promise<void> | void;
/** Take an undone change back off those rows. Must not throw. */
forgetAiActions?(accountId: string, emailIds: string[], kind: AiActionKind): Promise<void> | void;
}

/** What a set's action is, as the email's AI record names it. */
export function aiActionKindOfChange(action: InboxAgentChangeAction, category?: string): AiActionKind {
switch (action) {
case 'mark_read': return 'read';
case 'mark_unread': return 'unread';
case 'add_category': return category === 'important' ? 'important' : 'category';
case 'remove_category': return 'category';
case 'add_label': return 'label';
case 'remove_label': return 'unlabel';
default: return action;
}
}

/** The changed rows of an outcome, per account. */
function changedByAccount(entries: Iterable<HeldItem>, changed: (entry: HeldItem) => boolean): Map<string, string[]> {
const byAccount = new Map<string, string[]>();
for (const entry of entries) {
if (!changed(entry)) continue;
byAccount.set(entry.item.accountId, [...(byAccount.get(entry.item.accountId) ?? []), entry.item.emailId]);
}
return byAccount;
}

type EmailState = Pick<EmailRecord, 'tags' | 'folderId'> & Partial<EmailRecord>;
Expand Down Expand Up @@ -600,6 +627,11 @@ export async function applyChangeSet(held: HeldChangeSet, options: {
if (MOVES.has(set.action) && entry.after?.folderId === entry.before.folderId && entry.after.tags === entry.before.tags) entry.item.status = 'unchanged';
}
}
// The emails now say what the agent did, and whether the user approved it.
const kind = aiActionKindOfChange(set.action, set.category);
for (const [accountId, ids] of changedByAccount(outcome.keys(), entry => entry.item.status === 'applied' || entry.item.status === 'queued')) {
try { await options.actions.recordAiActions?.(accountId, ids, kind, options.auto === true); } catch { /* The change stands without its record. */ }
}
if (options.auto) set.autoApplied = true;
else held.userApproved = true;
if ([...held.items.values()].some(entry => isChanged(entry.item))) set.undoBy = options.nowMs + INBOX_AGENT_CHANGE_LIMITS.undoMs;
Expand Down Expand Up @@ -676,6 +708,10 @@ export async function undoChangeSet(held: HeldChangeSet, options: {
if (result === 'failed') entry.item.detail = 'Could not be undone. Try Undo again.';
else { entry.item.status = 'undone'; delete entry.item.detail; }
}
const kind = aiActionKindOfChange(set.action, set.category);
for (const [accountId, ids] of changedByAccount(outcome.keys(), entry => entry.item.status === 'undone')) {
try { await options.actions.forgetAiActions?.(accountId, ids, kind); } catch { /* The emails are back; the record may linger. */ }
}
}
// A label this set created goes again once none of its emails keeps it.
for (const accountId of held.createdLabelIn ?? []) {
Expand Down
7 changes: 7 additions & 0 deletions apps/desktop/src/components/agent/AgentDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useState, useEffect, useCallback, useRef } from 'react';

import { Tooltip } from '../Tooltip';

import { AiActionCounts } from './AiActionCounts';

// ========== IPC shapes (mirror agent-handlers.ts return statements) ==========

interface IpcResult<T> { success: boolean; data?: T; error?: string }
Expand Down Expand Up @@ -168,9 +170,11 @@ export function AgentDashboard({ onNavigateToEmail, onNavigateToContacts, onRefr
const [loadError, setLoadError] = useState(false);
const [agentMode, setAgentMode] = useState<'off' | 'suggest' | 'auto'>(readAgentMode);
const mountedRef = useRef(true);
const [countsKey, setCountsKey] = useState(0);

const load = useCallback(async (initial: boolean) => {
if (initial) setLoading(true); else setRefreshing(true);
setCountsKey(key => key + 1);
setAgentMode(readAgentMode());
const api = agentIpc();
try {
Expand Down Expand Up @@ -273,6 +277,9 @@ export function AgentDashboard({ onNavigateToEmail, onNavigateToContacts, onRefr
refreshing={refreshing || loading}
onRefresh={() => { void load(false); onRefresh?.(); }}
/>
{/* Outside the agent's own states: the Inbox Agent changes mail too,
whether or not the background agent is on. */}
<AiActionCounts refreshKey={countsKey} />
{loading ? <DashboardSkeleton />
: loadError ? <ErrorState onRetry={() => load(true)} />
: isFirstRun ? <FirstRunState agentMode={agentMode} />
Expand Down
Loading
Loading