diff --git a/CHANGELOG.md b/CHANGELOG.md index 591e5617..96774ff2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index 1627419a..9c9ac800 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/apps/desktop/electron/ipc/agent-handlers.ts b/apps/desktop/electron/ipc/agent-handlers.ts index 47363c24..be529f0f 100644 --- a/apps/desktop/electron/ipc/agent-handlers.ts +++ b/apps/desktop/electron/ipc/agent-handlers.ts @@ -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'; @@ -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. @@ -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(); @@ -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 }; } diff --git a/apps/desktop/electron/ipc/inbox-assistant-handlers.ts b/apps/desktop/electron/ipc/inbox-assistant-handlers.ts index b5c18e51..de2a621e 100644 --- a/apps/desktop/electron/ipc/inbox-assistant-handlers.ts +++ b/apps/desktop/electron/ipc/inbox-assistant-handlers.ts @@ -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'; @@ -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 }); + }, }, }); diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts index 35e1df68..ce58e161 100644 --- a/apps/desktop/electron/preload.ts +++ b/apps/desktop/electron/preload.ts @@ -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'; @@ -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) => @@ -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) => @@ -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 }>; @@ -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; emails: number; categorized: number }; error?: string }>; getPendingDecisions: () => Promise<{ success: boolean; data?: any[]; error?: string }>; resolveDecision: (decisionId: string, status: string, actualAction?: string, feedback?: string) => diff --git a/apps/desktop/electron/services/ai-action-record.ts b/apps/desktop/electron/services/ai-action-record.ts new file mode 100644 index 00000000..ba2ce82b --- /dev/null +++ b/apps/desktop/electron/services/ai-action-record.ts @@ -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) }); + } +} diff --git a/apps/desktop/electron/services/inbox-assistant-change-sets.ts b/apps/desktop/electron/services/inbox-assistant-change-sets.ts index c833cd3a..96dc34aa 100644 --- a/apps/desktop/electron/services/inbox-assistant-change-sets.ts +++ b/apps/desktop/electron/services/inbox-assistant-change-sets.ts @@ -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 { @@ -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; revertSpamVerdict(accountId: string, rows: InboxAgentSpamRevert[]): Promise; + /** 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; + /** Take an undone change back off those rows. Must not throw. */ + forgetAiActions?(accountId: string, emailIds: string[], kind: AiActionKind): Promise | 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, changed: (entry: HeldItem) => boolean): Map { + const byAccount = new Map(); + 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 & Partial; @@ -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; @@ -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 ?? []) { diff --git a/apps/desktop/src/components/agent/AgentDashboard.tsx b/apps/desktop/src/components/agent/AgentDashboard.tsx index 27ff2cf3..8200bfb1 100644 --- a/apps/desktop/src/components/agent/AgentDashboard.tsx +++ b/apps/desktop/src/components/agent/AgentDashboard.tsx @@ -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 { success: boolean; data?: T; error?: string } @@ -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 { @@ -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. */} + {loading ? : loadError ? load(true)} /> : isFirstRun ? diff --git a/apps/desktop/src/components/agent/AiActionCounts.tsx b/apps/desktop/src/components/agent/AiActionCounts.tsx new file mode 100644 index 00000000..3979da17 --- /dev/null +++ b/apps/desktop/src/components/agent/AiActionCounts.tsx @@ -0,0 +1,67 @@ +import { AI_ACTION_KINDS, describeAiAction, type AiActionKind } from '@sarvinbox/core/ai-actions'; +import { Sparkles } from 'lucide-react'; +import { useEffect, useState } from 'react'; + +import { Tooltip } from '../Tooltip'; + +export interface AiActionCountsData { + byKind: Record; + /** Emails the AI changed at least once. */ + emails: number; + /** Emails the AI has categorized (counted, never shown as an icon). */ + categorized: number; +} + +/** The kinds with a count, largest first; the order of AI_ACTION_KINDS breaks ties. */ +export function aiActionCountRows(data: AiActionCountsData): Array<{ kind: AiActionKind; count: number }> { + return AI_ACTION_KINDS + .map((kind, order) => ({ kind, count: data.byKind[kind] ?? 0, order })) + .filter(row => row.count > 0) + .sort((a, b) => b.count - a.count || a.order - b.order) + .map(({ kind, count }) => ({ kind, count })); +} + +/** The AI section's tally of what the AI did to mail in this account, from each email's own record. */ +export function AiActionCountsView({ data }: { data: AiActionCountsData }) { + const rows = aiActionCountRows(data); + const total = rows.reduce((sum, row) => sum + row.count, 0); + return ( +
+
+
+ {rows.length === 0 + ?

The AI has not changed any email yet. Emails it changes get a

+ : ( +
    + {rows.map(row => ( +
  • + {describeAiAction(row.kind)} + {row.count.toLocaleString()} +
  • + ))} +
+ )} + +

Categorized {data.categorized.toLocaleString()} {data.categorized === 1 ? 'email' : 'emails'}

+
+
+ ); +} + +/** Loads the counts for the active account; `refreshKey` changing loads them again. Nothing while loading or on failure. */ +export function AiActionCounts({ refreshKey }: { refreshKey: number }) { + const [data, setData] = useState(null); + useEffect(() => { + let live = true; + const load = window.electronAPI?.agent?.getAiActionCounts; + if (!load) return; + load().then(result => { if (live && result?.success && result.data) setData(result.data); }, () => { /* The section stays as it was. */ }); + return () => { live = false; }; + }, [refreshKey]); + return data ? : null; +} diff --git a/apps/desktop/src/components/attachment-viewer/AttachmentChips.tsx b/apps/desktop/src/components/attachment-viewer/AttachmentChips.tsx index dfc9ad5d..b9d43817 100644 --- a/apps/desktop/src/components/attachment-viewer/AttachmentChips.tsx +++ b/apps/desktop/src/components/attachment-viewer/AttachmentChips.tsx @@ -1,10 +1,10 @@ -import { Download, Loader2, Paperclip } from 'lucide-react'; +import { Download, Paperclip } from 'lucide-react'; import { useState } from 'react'; import { getFileIcon, getFileType } from '../email-detail/utils'; import { Tooltip } from '../Tooltip'; -import { AttachmentDownloadStatus } from './AttachmentDownloadStatus'; +import { AttachmentDownloadStatus, AttachmentStopButton } from './AttachmentDownloadStatus'; import { AttachmentViewer, type ViewerAttachment } from './AttachmentViewer'; import { useAttachmentActions } from './useAttachmentActions'; @@ -93,6 +93,8 @@ export function AttachmentChips({
{attachments.map((attachment, index) => { const busy = isBusy(emailId, attachment.name, accountId); + const status = getStatus(emailId, attachment.name, accountId); + const cancel = () => { void cancelDownload(emailId, attachment.name, accountId); }; return (
{busy ? ( - + ) : ( getFileIcon(attachment.name) )} @@ -132,7 +134,7 @@ export function AttachmentChips({
{!busy && getFileType(attachment.name)}
- { void cancelDownload(emailId, attachment.name, accountId); }} /> +
); diff --git a/apps/desktop/src/components/attachment-viewer/AttachmentDownloadStatus.tsx b/apps/desktop/src/components/attachment-viewer/AttachmentDownloadStatus.tsx index c9989be5..be94e5a1 100644 --- a/apps/desktop/src/components/attachment-viewer/AttachmentDownloadStatus.tsx +++ b/apps/desktop/src/components/attachment-viewer/AttachmentDownloadStatus.tsx @@ -1,7 +1,9 @@ -import { X } from 'lucide-react'; +import { Loader2, Square, X } from 'lucide-react'; +import { useContext } from 'react'; import { Tooltip } from '../Tooltip'; +import { AttachmentActionsContext } from './attachment-actions-context'; import type { AttachmentDownloadState } from './useAttachmentActions'; /** An accepted missing-setup warning is never represented as a clean scan. */ @@ -9,18 +11,85 @@ export function UnscannedAttachmentNotice() { return

Not scanned for viruses.

; } -/** The same trusted progress, cancellation and blocked-attachment message everywhere. */ +/** + * Whether the app-wide Attachments panel (AttachmentTransferProvider) is + * showing this attachment's progress. It is mounted around the whole app; an + * isolated embed without it has no other place to show progress. + */ +export function useAttachmentTransferPanel(): boolean { + return useContext(AttachmentActionsContext) !== undefined; +} + +type Action = 'preview' | 'open' | 'download'; + +function actionOf(status: AttachmentDownloadState): Action { + return status.operation === 'preview' ? 'preview' : status.operation === 'open' ? 'open' : 'download'; +} + +/** + * The busy spinner of an attachment chip, as the control that stops it. + * + * A stop square sits inside the spinning ring, so the way to stop is where the + * eye already is, rather than in a status line under the chip that repeats what + * the Attachments panel shows. A transfer that cannot be cancelled (a system + * open) keeps a plain spinner: a stop button that does nothing is worse than + * none. + */ +export function AttachmentStopButton({ + status, + filename, + onCancel, + className = '', + iconClassName = 'h-3.5 w-3.5', +}: { + status?: AttachmentDownloadState; + filename: string; + onCancel: () => void; + className?: string; + iconClassName?: string; +}) { + if (!status?.phase) return null; + if (!status.canCancel) return