Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(connectors): add the agent connector foundation and email drafts (#2331)

Chad Piha7575730a1768
diff --git a/CLAUDE.md b/CLAUDE.md
index c0d9469a0..a4247e9e2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -166,6 +166,13 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **windowConfig.js**: Centralized window configuration
- **windowManager.js**: Window creation and lifecycle management
- **cliBridge.js**: Loopback HTTP server on ports 8200–8219, bearer-token auth (token at `~/.openwhispr/cli-bridge.json`), 127.0.0.1-only. Used by the unified CLI to talk to a running desktop app. `POST /v1/transcribe` takes a file **path** (never audio) and runs the user's downloaded local model through `IPCHandlers.transcribeLocalFile`, approving the path with `approveAudioPath` first; `GET /v1/transcribe/models` lists local models with download state and the app's default (`localTranscriptionModels.js`, read from the `.env` pre-warm values).
+- **connectors/**: Agent connectors
+ - `connectorManager.js` owns every outside action: `prepare` → ApprovalCard → `commit` for anything other people see, `runDirect` for private drafts. The model can never reach `commit`
+ - `pendingActions.js`: pending → committing → sent/failed/unknown; actions are bound to the connection (account, workspace, `generation`) they were prepared on and to the OpenWhispr account that prepared them (another account's commit is withdrawn as `account_changed`)
+ - `connector_actions` (SQLite) is the durable receipt: destination labels, states and links only, never content. Each row is stamped with the account bound to the credential the action ran under (`accountScopeBinding`, read before and after the policy wait; with no account, `prepare` and `runDirect` refuse as `receipt_unavailable`; a `commit` under a changed or missing account is withdrawn as `not_sent`/`account_changed`), so Recent actions lists only that account's rows and account deletion removes them. Interrupted rows are reconciled on launch (committing → unknown; rows with no account are deleted), expired pending actions are recorded as `expired`, a direct run the connector stopped (`not_sent`) is `cancelled`, and a direct run that throws or returns a malformed result is `unknown` (it may have happened), never `failed`. Every connector result is whitelisted and type-checked per state before it is recorded or reaches the renderer. A cancel (Esc) reaches a direct run until its side effect through `runtime.signal`, checked right before the compose window opens
+ - Policy fails closed (`connectorPolicy.js`'s `connectorPolicyState` classifies the snapshot; `connectorIpc.js`'s `createConnectorPolicyResolver` enforces the 1.5s deadline): only a successful, well-formed snapshot allows; unresolvable, any error code, or >1.5s with no verdict already held for the account (`workspacePolicyManager.peekPolicy`) → unavailable; org switch `features.connectorsEnabled`, and `agentEnabled: false` turns connectors off too
+ - `emailConnector.js` opens Gmail/Outlook/mailto compose windows (`emailCompose.js`, shared ESM); a body that won't fit the compose URL (2,000 chars; 6,000 for Gmail on macOS/Linux, since Windows caps opened URLs near 2,081) goes to the clipboard after the OS accepts the link (on Linux a `mailto` is refused first when `xdg-mime` reports no default — empty output with exit 0, or exit 4 on KDE 5 — except under Flatpak, where the portal picks the handler), then the subject too if it's still too long; a recipient list that alone doesn't fit is refused. `email_draft` opens at most 3 drafts per turn, and only one of them may use the clipboard (`ToolExecutionContext.claimTurnSlot`; a draft that didn't open gives its slots back, and the compose preview is built before any slot is claimed). Subject and body go through `toWellFormed()`, the renderer NFC-normalises addresses (`bareEmailAddress`), and a recipient with a non-ASCII domain is shown with its punycode form (`recipientLabel`) to the model, in the tool step and in receipts. Automatic picks Gmail whenever a Google calendar is connected; otherwise it picks Outlook work vs Outlook.com from the Microsoft account's tenant id (`tid`, consumer tenant `9188040d-…`), falling back to the email domain for accounts connected before it was stored
+ - `contactSearch.js` (`find_contact`) searches the meetings nearest to now on selected calendars (`SELECTED_CALENDAR_EVENT_FILTER`; for Google only primary calendars, since a colleague's shared calendar isn't the user's meetings, which also leaves out the user's own secondary Google calendars; shared Microsoft or Apple-mirrored calendars still count; `calendar_events` only spans the sync window; cancelled and declined meetings don't count) plus the `contacts` table, most recently synced first, behind the same org policy check as the actions. Excluded: the user's calendar accounts and their Microsoft addresses (`/me` `mail`, `userPrincipalName` and `proxyAddresses`, stored in `microsoft_calendar_tokens.own_addresses` by `fetchCalendars`, which also purges them from `contacts`), `self` attendees, an Apple organizer who is the current user, any address flagged `resource` in any stored event (rows with unreadable attendee JSON are skipped) (rooms, flagged by all three calendar managers) and `*.calendar.google.com` addresses; the calendar managers also keep the user and rooms out of `contacts` and purge those addresses when they see them again. Sources are many-to-many (`contact_sources`: `google:<account>`, `microsoft:<account>`, `apple`, `manual`): disconnecting an account removes its source rows and deletes only contacts no other source still has; the lookup reads contacts with a `manual` or connected-account source (rows from before sources existed are left out; note-participant autocomplete still reads every row). Picking an existing contact in a note never adds `manual`, so it can't make a synced contact permanent
- **postMigrationDetector.js**: Detects users returning from the pre-Gizmo bundle ID via a `.bundle-migrated` sentinel in userData; consumed by `ipcHandlers.js` to drive the `PostMigrationOnboarding` modal
### React Components (src/components/)
@@ -176,6 +183,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **PostMigrationOnboarding.tsx**: One-time modal for users returning from the pre-Gizmo bundle ID; reuses `PermissionsSection` to walk through re-granting Microphone, Accessibility, and System Audio. Triggered by `postMigrationDetector.js` (see Helper Modules)
- **SettingsPage.tsx**: Comprehensive settings interface
- **WhisperModelPicker.tsx**: Model selection and download UI
+- **ConnectorsSection.tsx**: Integrations → Connectors: the "Draft emails in" picker (Automatic shows what it resolved to), a paid-plan upsell, "turned off by your organization" for a resolved org block and "not available right now" while the policy is loading, failed or requires a newer app, and Recent actions (refetched when main's account scope changes)
- **ui/**: Reusable UI components (buttons, cards, inputs, etc.)
- **ui/RichTextEditor.tsx**: Tiptap note editor. Note bodies (`content`, `enhanced_content`) are stored as Markdown via tiptap-markdown (`html: false`)
- `RichTextEditorExtensions.ts` holds the extension list (`RichTextEditor` adds the mention extension in front of it); order matters: at equal priority, later extensions' keymaps and clipboard props run first
@@ -360,6 +368,7 @@ Settings stored in localStorage with these keys:
- `hotkey`: Custom hotkey configuration
- `hasCompletedOnboarding`: Onboarding completion flag
- `customDictionary`: JSON array of words/phrases for improved transcription accuracy
+- `emailDraftTarget`: Where email drafts open (`auto`, `gmail`, `outlookWork`, `outlookPersonal`, `mailto`); an unknown value reads as `auto`
Secret env vars (12 total: 7 BYOK API keys + 5 enterprise cloud creds — see `SECRET_KEYS` in `environment.js`) are encrypted at rest via Electron `safeStorage` and stored as per-key files under `userData/secure-keys/`. They are loaded into `process.env` at startup by `EnvironmentManager.init()`. Renderer reads them via IPC (`get-*-key`) and writes via debounced IPC (`save-*-key`). On Linux without a keyring, secrets fall back to plaintext.
@@ -694,6 +703,7 @@ A dedicated global hotkey that starts a dictation whose transcript is sent strai
4. Standalone commands (no text selected) run through the chat pipeline (`src/components/dictation/AssistantPanel.tsx`): chat tools (notes search/create/update, calendar, web search, clipboard, `get_snippet` — triggers listed in the tool description, body fetched on demand — and `update_dictionary` / `update_snippets`, which write through the settings store so the change syncs like a UI edit), RAG memory, and the custom dictionary plus snippet triggers injected into the system prompt. Conversations persist in the `agent_conversations` table and are browsable from the ControlPanel chat
5. Response delivery: a capture with `status: "editable"` (a focused writable non-terminal field with no selection) plus auto-paste banks a `deliverySessionId`; the completed answer is pasted via `paste-at-captured-target`, which revalidates the target and fails closed to the panel + clipboard on any change (`assistantResponseDelivery.ts`, `pasteAtCapturedTarget` in `selectionManager.js`). A follow-up spoken while the panel is already open stays panel-first. Cancelled or empty responses never paste and never touch the clipboard
6. Selection edits are unchanged: highlighted text goes through the `dictationAgent` scope and is safely replaced in place — it never opens the panel
+7. Connector tools (`email_draft`, `find_contact`; paid, policy-gated) run through `src/helpers/connectors`. Only typed chat (`ChatView`) and this panel opt in (`allowConnectors`); note chat, container chat and the onboarding demo don't get them. An approval card, any `email_draft` (its compose window takes focus) and any `find_contact` (a lookup is almost always followed by a question for the user) hold the turn in the panel (`onHoldDelivery`) instead of pasting at the caret. A held answer is still auto-copied, except after an `email_draft` that reserved the clipboard for overflow text (`onHoldDelivery({ preserveClipboard: true })`, sticky for the turn) and on a caret turn whose delivery restores the clipboard (Keep Transcription in Clipboard off)
**Storage & IPC**:
diff --git a/main.js b/main.js
index 4f92ee7d6..0c6048dee 100644
--- a/main.js
+++ b/main.js
@@ -330,6 +330,7 @@ let windowManager = null;
let hotkeyManager = null;
let databaseManager = null;
let clipboardManager = null;
+let connectorManager = null;
let whisperManager = null;
let parakeetManager = null;
let diarizationManager = null;
@@ -468,6 +469,20 @@ function initializeCoreManagers() {
});
if (bootAccountId) databaseManager.setActiveAccountId(bootAccountId);
clipboardManager = new ClipboardManager();
+ const { createConnectorManager } = require("./src/helpers/connectors/connectorManager");
+ const { createPendingActions } = require("./src/helpers/connectors/pendingActions");
+ const { createActionLog } = require("./src/helpers/connectors/actionLog");
+ connectorManager = createConnectorManager({
+ connectors: [
+ require("./src/helpers/connectors/emailConnector").createEmailConnector({
+ openExternal: (url) => require("./src/helpers/externalUrlOpener").openExternalUrl(url),
+ writeClipboard: (text, webContents) => clipboardManager.writeClipboard(text, webContents),
+ }),
+ ],
+ pendingActions: createPendingActions(),
+ actionLog: createActionLog(databaseManager),
+ logger: debugLogger,
+ });
whisperManager = new WhisperManager();
if (process.platform !== "darwin") {
whisperCudaManager = new WhisperCudaManager();
@@ -577,6 +592,7 @@ function initializeCoreManagers() {
googleCalendarManager,
microsoftCalendarManager,
appleCalendarManager,
+ connectorManager,
meetingDetectionEngine,
audioTapManager,
linuxPortalAudioManager,
diff --git a/preload.js b/preload.js
index ebe0d9746..b4e1c2967 100644
--- a/preload.js
+++ b/preload.js
@@ -1263,6 +1263,16 @@ contextBridge.exposeInMainWorld("electronAPI", {
gcalSyncEvents: () => ipcRenderer.invoke("gcal-sync-events"),
gcalGetUpcomingEvents: (windowMinutes) =>
ipcRenderer.invoke("gcal-get-upcoming-events", windowMinutes),
+ connectorStatus: () => ipcRenderer.invoke("connector-status"),
+ connectorPrepare: (connectorId, action, args) =>
+ ipcRenderer.invoke("connector-prepare", connectorId, action, args),
+ connectorCommit: (actionId, edits) => ipcRenderer.invoke("connector-commit", actionId, edits),
+ connectorCancel: (actionId, reason) => ipcRenderer.invoke("connector-cancel", actionId, reason),
+ connectorRunDirect: (connectorId, action, args, runId) =>
+ ipcRenderer.invoke("connector-run-direct", connectorId, action, args, runId),
+ connectorRecentActions: (connectorId, limit) =>
+ ipcRenderer.invoke("connector-recent-actions", connectorId, limit),
+ connectorFindContacts: (query) => ipcRenderer.invoke("connector-find-contacts", query),
calendarGetAvailability: (request) => ipcRenderer.invoke("calendar-get-availability", request),
gcalGetEvent: (eventId) => ipcRenderer.invoke("gcal-get-event", eventId),
diff --git a/resources/macos-calendar-listener.swift b/resources/macos-calendar-listener.swift
index afab584b6..9b25565d0 100644
--- a/resources/macos-calendar-listener.swift
+++ b/resources/macos-calendar-listener.swift
@@ -78,10 +78,12 @@ struct AttendeeOut: Encodable {
let name: String?
let status: String
let isSelf: Bool
+ let isResource: Bool
enum CodingKeys: String, CodingKey {
case email, name, status
case isSelf = "self"
+ case isResource = "resource"
}
}
@@ -95,6 +97,7 @@ struct EventOut: Encodable {
let status: String
let availability: String
let organizer_email: String?
+ let organizer_self: Bool
let url: String?
let location: String?
let notes_urls: [String]
@@ -208,7 +211,8 @@ func mapEvent(_ event: EKEvent) -> EventOut? {
email: mailtoEmail(participant.url),
name: participant.name,
status: participantStatus(participant.participantStatus),
- isSelf: participant.isCurrentUser
+ isSelf: participant.isCurrentUser,
+ isResource: participant.participantType == .room || participant.participantType == .resource
)
}
@@ -222,6 +226,7 @@ func mapEvent(_ event: EKEvent) -> EventOut? {
status: eventStatus(event.status),
availability: eventAvailability(event.availability),
organizer_email: mailtoEmail(event.organizer?.url),
+ organizer_self: event.organizer?.isCurrentUser ?? false,
url: event.url?.absoluteString,
location: event.location,
notes_urls: extractURLs(from: event.notes),
diff --git a/src/components/ConnectorsSection.tsx b/src/components/ConnectorsSection.tsx
new file mode 100644
index 000000000..1e77513a2
--- /dev/null
+++ b/src/components/ConnectorsSection.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useState, useSyncExternalStore, type ReactElement } from "react";
+import { useTranslation } from "react-i18next";
+import { Mail } from "./icons";
+import { Button } from "./ui/button";
+import { SectionLabel, SettingsPanel, SettingsPanelRow } from "./ui/SettingsSection";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
+import { useSettingsStore } from "../stores/settingsStore";
+import { usePolicyStore } from "../stores/policyStore";
+import { isConnectorsAllowed, isConnectorsBlockedByOrg } from "../stores/policyRules";
+import { getUsageState, subscribeUsage } from "../lib/usageStore";
+import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
+import type { ConnectorActionRecord } from "../types/connectors";
+import { hasConnectorPlan } from "../utils/connectorEligibility";
+import { normalizeDbDate } from "../utils/dateFormatting";
+import {
+ EMAIL_DRAFT_TARGET_SETTINGS,
+ resolveEmailDraftTarget,
+ type EmailDraftTargetSetting,
+} from "../utils/emailDraftTarget";
+
+function formatWhen(createdAt: string, locale: string): string {
+ const date = normalizeDbDate(createdAt);
+ return Number.isNaN(date.getTime())
+ ? createdAt
+ : date.toLocaleString(locale, { dateStyle: "short", timeStyle: "short" });
+}
+
+interface ConnectorsSectionProps {
+ onUpgrade: () => void;
+}
+
+export function ConnectorsSection({ onUpgrade }: ConnectorsSectionProps): ReactElement {
+ const { t, i18n } = useTranslation();
+ const blockedByOrg = usePolicyStore(isConnectorsBlockedByOrg);
+ // False while the policy loads, after a failed fetch, or when the org requires
+ // a newer app: chat has no connector tools then, so the card mustn't offer them.
+ const connectorsAllowed = usePolicyStore(isConnectorsAllowed);
+ const isSignedIn = useSettingsStore((state) => state.isSignedIn);
+ const emailDraftTarget = useSettingsStore((state) => state.emailDraftTarget);
+ const setEmailDraftTarget = useSettingsStore((state) => state.setEmailDraftTarget);
+ const gcalConnected = useSettingsStore((state) => state.gcalConnected);
+ const mcalAccounts = useSettingsStore((state) => state.mcalAccounts);
+ // The same plan check that decides whether the chat gets the connector tools.
+ const usage = useSyncExternalStore(subscribeUsage, getUsageState);
+ const isSubscribedFlag = useSyncExternalStore(subscribeIsSubscribed, readIsSubscribed);
+ const isPaid = isSignedIn && hasConnectorPlan(usage, isSubscribedFlag);
+ const showActions = isPaid && connectorsAllowed;
+ const [recent, setRecent] = useState<ConnectorActionRecord[]>([]);
+ const [accountScopeChanges, setAccountScopeChanges] = useState(0);
+
+ // Main lists the receipts of its active account scope, which settles after
+ // the renderer's own sign-in state; refetch once it has moved.
+ useEffect(
+ () =>
+ window.electronAPI?.onActiveAccountScopeChanged?.(() =>
+ setAccountScopeChanges((count) => count + 1)
+ ),
+ []
+ );
+
+ useEffect(() => {
+ setRecent([]);
+ if (!showActions) return undefined;
+ let active = true;
+ void window.electronAPI
+ ?.connectorRecentActions?.("email", 10)
+ .then((rows) => {
+ if (active) setRecent(rows ?? []);
+ })
+ .catch(() => {
+ if (active) setRecent([]);
+ });
+ return () => {
+ active = false;
+ };
+ }, [showActions, accountScopeChanges]);
+
+ const automaticTarget = resolveEmailDraftTarget({
+ emailDraftTarget: "auto",
+ gcalConnected,
+ mcalAccounts,
+ });
+ const optionLabel = (option: EmailDraftTargetSetting): string =>
+ option === "auto"
+ ? t("connectors.email.autoResolved", {
+ target: t(`connectors.email.targets.${automaticTarget}`),
+ })
+ : t(`connectors.email.targets.${option}`);
+
+ const description = blockedByOrg
+ ? t("connectors.policyOff")
+ : !isPaid
+ ? t("connectors.email.proRequired")
+ : connectorsAllowed
+ ? t("connectors.email.description")
+ : t("connectors.email.unavailable");
+
+ return (
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <div className="flex items-center gap-3">
+ <div className="w-9 h-9 rounded-lg bg-primary/5 dark:bg-primary/10 flex items-center justify-center shrink-0">
+ <Mail className="h-4 w-4 text-primary/80" strokeWidth={2} aria-hidden="true" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-xs font-semibold text-foreground">{t("connectors.email.title")}</p>
+ <p className="text-xs text-muted-foreground/70 mt-0.5 leading-relaxed">{description}</p>
+ </div>
+ {showActions && (
+ <Select
+ value={emailDraftTarget}
+ onValueChange={(value) => setEmailDraftTarget(value as EmailDraftTargetSetting)}
+ >
+ <SelectTrigger
+ className="h-7 w-48 shrink-0 text-xs rounded-lg px-2.5 [&>svg]:h-3 [&>svg]:w-3"
+ aria-label={t("connectors.email.targetLabel")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {EMAIL_DRAFT_TARGET_SETTINGS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {optionLabel(option)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ {!isPaid && !blockedByOrg && (
+ <Button size="sm" className="shrink-0" onClick={onUpgrade}>
+ {t("integrations.api.viewPlans")}
+ </Button>
+ )}
+ </div>
+
+ {showActions && recent.length > 0 && (
+ <div className="mt-3">
+ <SectionLabel>{t("connectors.recent.title")}</SectionLabel>
+ <ul className="space-y-1">
+ {recent.map((row) => (
+ <li
+ key={row.id}
+ className="flex items-center justify-between gap-2 text-xs text-muted-foreground"
+ >
+ <span className="truncate" dir="auto">
+ {row.destinationLabel
+ ? t(`connectors.recent.actions.${row.connector}_${row.action}`, {
+ destination: row.destinationLabel,
+ })
+ : // A run interrupted by a quit never learned its destination.
+ t(`connectors.recent.unlabeledActions.${row.connector}_${row.action}`)}
+ </span>
+ <span className="shrink-0">
+ {formatWhen(row.createdAt, i18n.language)} ·{" "}
+ {t(`connectors.recent.states.${row.state}`)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </SettingsPanelRow>
+ </SettingsPanel>
+ );
+}
diff --git a/src/components/IntegrationsView.tsx b/src/components/IntegrationsView.tsx
index fd573fa24..1cbe7c1d0 100644
--- a/src/components/IntegrationsView.tsx
+++ b/src/components/IntegrationsView.tsx
@@ -6,7 +6,7 @@ import { PAGE_CONTENT_WIDTH_CLASS } from "./ui/pageWidth";
import { cn } from "./lib/utils";
import { BIDI_VALUE_TOKEN, BidiInterpolatedText } from "./ui/BidiInterpolatedText";
import { Badge } from "./ui/badge";
-import { SettingsPanel, SettingsPanelRow, SettingsRow } from "./ui/SettingsSection";
+import { SectionLabel, SettingsPanel, SettingsPanelRow, SettingsRow } from "./ui/SettingsSection";
import { Toggle } from "./ui/toggle";
import {
AlertDialog,
@@ -20,10 +20,11 @@ import {
import { useSettingsStore } from "../stores/settingsStore";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
-import type { CalendarAccount } from "../types/calendar";
+import type { CalendarAccount, MicrosoftCalendarAccount } from "../types/calendar";
import ApiKeysSection from "./ApiKeysSection";
import CliIntegrationCard from "./CliIntegrationCard";
import McpIntegrationCard from "./McpIntegrationCard";
+import { ConnectorsSection } from "./ConnectorsSection";
import googleCalendarIcon from "../assets/icons/google-calendar.svg";
import microsoftCalendarIcon from "../assets/icons/microsoft-calendar.svg";
import appleCalendarIcon from "../assets/icons/apple-calendar.svg";
@@ -35,14 +36,6 @@ interface IntegrationsViewProps {
onUpgrade: () => void;
}
-function SectionLabel({ children }: { children: React.ReactNode }) {
- return (
- <div className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 mb-2 ps-1">
- {children}
- </div>
- );
-}
-
interface ProviderRowProps {
icon: string;
i18nKey: string;
@@ -224,7 +217,7 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
const current = useSettingsStore.getState().mcalAccounts;
setMcalAccounts([
...current.filter((a) => a.email !== result.email),
- { email: result.email },
+ { email: result.email, tenantId: result.tenantId },
]);
} else if (!result?.error?.includes("access_denied")) {
setOauthErrorKey("integrations.microsoftCalendar");
@@ -336,7 +329,7 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
useEffect(() => {
const unsub = window.electronAPI?.onMcalConnectionChanged?.(
- (data: { accounts?: Array<{ email: string }> }) => {
+ (data: { accounts?: MicrosoftCalendarAccount[] }) => {
if (data.accounts) setMcalAccounts(data.accounts);
}
);
@@ -362,6 +355,11 @@ export default function IntegrationsView({ isPaid, onUpgrade }: IntegrationsView
<div className={cn(PAGE_CONTENT_WIDTH_CLASS, "px-6 py-6 space-y-5")}>
<p className="text-xs text-muted-foreground/70">{t("integrations.description")}</p>
+ <div>
+ <SectionLabel>{t("integrations.sections.connectors")}</SectionLabel>
+ <ConnectorsSection onUpgrade={onUpgrade} />
+ </div>
+
<div>
<SectionLabel>{t("integrations.sections.calendar")}</SectionLabel>
<SettingsPanel>
diff --git a/src/components/chat/ApprovalCard.tsx b/src/components/chat/ApprovalCard.tsx
new file mode 100644
index 000000000..a986de5f1
--- /dev/null
+++ b/src/components/chat/ApprovalCard.tsx
@@ -0,0 +1,144 @@
+import { useState, type ReactElement } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "../ui/button";
+import {
+ approveAction,
+ cancelApproval,
+ updateApprovalDraft,
+ type ApprovalEntry,
+} from "../../stores/connectorApprovalStore";
+
+// The draft lives in the store, so edit mode only changes how it is shown:
+// Send always commits exactly what the card displays.
+export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElement {
+ const { t } = useTranslation();
+ const { preview, draft } = entry;
+ const [editing, setEditing] = useState(false);
+ const destination = preview.destinationLabel;
+
+ return (
+ <div
+ data-approval-card={entry.toolCallId}
+ data-state={entry.state}
+ className="my-1.5 rounded-lg border border-border/70 bg-surface-2/60 p-3 text-[13px]"
+ >
+ <p className="font-medium text-foreground">
+ {t(`connectors.approval.headers.${preview.verbKey}`, {
+ destination,
+ defaultValue: t("connectors.approval.headers.default", { destination }),
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {preview.workspaceLabel
+ ? t("connectors.approval.identityWithWorkspace", {
+ account: preview.accountLabel,
+ workspace: preview.workspaceLabel,
+ })
+ : t("connectors.approval.identity", { account: preview.accountLabel })}
+ </p>
+
+ {editing ? (
+ <div className="mt-2 space-y-2">
+ {draft.title !== undefined && (
+ <input
+ aria-label={t("connectors.approval.titleLabel")}
+ className="w-full rounded-md border border-border/70 bg-background px-2 py-1"
+ dir="auto"
+ value={draft.title}
+ onChange={(event) =>
+ updateApprovalDraft(entry.toolCallId, { title: event.target.value })
+ }
+ />
+ )}
+ <textarea
+ aria-label={t("connectors.approval.bodyLabel")}
+ className="min-h-24 w-full rounded-md border border-border/70 bg-background px-2 py-1"
+ dir="auto"
+ value={draft.body}
+ onChange={(event) =>
+ updateApprovalDraft(entry.toolCallId, { body: event.target.value })
+ }
+ />
+ </div>
+ ) : (
+ <div className="mt-2">
+ {draft.title !== undefined && <p className="font-medium">{draft.title}</p>}
+ <p className="whitespace-pre-wrap" dir="auto">
+ {draft.body}
+ </p>
+ </div>
+ )}
+
+ {preview.notes?.map((note) => (
+ <p key={note.key} className="mt-1 text-xs text-muted-foreground">
+ {t(note.key, note.values)}
+ </p>
+ ))}
+
+ {entry.state === "pending" && (
+ <div className="mt-2 flex gap-2">
+ <Button
+ size="sm"
+ onClick={() => {
+ // A frozen textarea would look editable while the draft sends.
+ setEditing(false);
+ void approveAction(entry.toolCallId);
+ }}
+ >
+ {t("connectors.approval.send")}
+ </Button>
+ <Button size="sm" variant="outline" onClick={() => setEditing((value) => !value)}>
+ {editing ? t("connectors.approval.doneEditing") : t("connectors.approval.edit")}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => cancelApproval(entry.toolCallId)}>
+ {t("connectors.approval.cancel")}
+ </Button>
+ </div>
+ )}
+ {entry.state === "committing" && (
+ <p role="status" className="mt-2 text-xs text-muted-foreground">
+ {t("connectors.approval.sending")}
+ </p>
+ )}
+ {entry.state === "sent" && (
+ <p className="mt-2 text-xs text-foreground">
+ {t("connectors.approval.sent", { destination })}
+ {entry.url && (
+ <Button
+ size="sm"
+ variant="link"
+ onClick={() => void window.electronAPI?.openExternal?.(entry.url as string)}
+ >
+ {t("connectors.approval.open")}
+ </Button>
+ )}
+ </p>
+ )}
+ {entry.state === "failed" && (
+ <p className="mt-2 text-xs text-destructive">
+ {t("connectors.approval.failed", { message: entry.message ?? "" })}
+ </p>
+ )}
+ {entry.state === "unknown" && (
+ <p className="mt-2 text-xs text-foreground">
+ {t("connectors.approval.unknown", { destination })}
+ {entry.url && (
+ <Button
+ size="sm"
+ variant="link"
+ onClick={() => void window.electronAPI?.openExternal?.(entry.url as string)}
+ >
+ {t("connectors.approval.open")}
+ </Button>
+ )}
+ </p>
+ )}
+ {entry.state === "cancelled" && (
+ <p className="mt-2 text-xs text-muted-foreground">{t("connectors.approval.cancelled")}</p>
+ )}
+ {entry.state === "not_sent" && (
+ <p className="mt-2 text-xs text-muted-foreground">{t("connectors.approval.notSent")}</p>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/chat/ChatMessage.tsx b/src/components/chat/ChatMessage.tsx
index 9378cd31f..686adf007 100644
--- a/src/components/chat/ChatMessage.tsx
+++ b/src/components/chat/ChatMessage.tsx
@@ -6,6 +6,8 @@ import { MarkdownRenderer } from "../ui/MarkdownRenderer";
import type { ToolCallInfo } from "./types";
import { extractNoteCards } from "./noteCards";
import { toolIcons } from "./toolIcons";
+import { ApprovalCard } from "./ApprovalCard";
+import { useConnectorApprovalStore } from "../../stores/connectorApprovalStore";
interface ChatMessageProps {
role: "user" | "assistant";
@@ -120,6 +122,13 @@ function ToolCallStep({ toolCall }: { toolCall: ToolCallInfo }) {
);
}
+// Subscribes to its own approval entry only, so editing one card doesn't
+// re-render every message in the thread.
+function ToolCallItem({ toolCall }: { toolCall: ToolCallInfo }) {
+ const approval = useConnectorApprovalStore((state) => state.entries[toolCall.id]);
+ return approval ? <ApprovalCard entry={approval} /> : <ToolCallStep toolCall={toolCall} />;
+}
+
function NoteCard({
noteId,
title,
@@ -226,7 +235,7 @@ export function ChatMessage({
)}
>
{toolCalls.map((tc) => (
- <ToolCallStep key={tc.id} toolCall={tc} />
+ <ToolCallItem key={tc.id} toolCall={tc} />
))}
</div>
)}
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index b3e31b465..95924b5ca 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -35,6 +35,7 @@ export default function ChatView() {
const [isNewChat, setIsNewChat] = useState(true);
const [refreshKey, setRefreshKey] = useState(0);
const [showSearch, setShowSearch] = useState(false);
+ const [submissionInFlight, setSubmissionInFlight] = useState(false);
const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
const persistence = useChatPersistence({
@@ -48,26 +49,32 @@ export default function ChatView() {
const streaming = useChatStreaming({
messages: persistence.messages,
setMessages: persistence.setMessages,
+ allowConnectors: true,
onStreamComplete: (_id, content, toolCalls) => {
persistence.saveAssistantMessage(content, toolCalls);
},
});
+ // useChatStreaming returns a fresh object every render; cancelStream is
+ // stable, so the callbacks below depend on it rather than on `streaming`.
+ const { cancelStream } = streaming;
const handleSelectConversation = useCallback(
async (id: number) => {
if (id === activeConversationId) return;
+ cancelStream();
setActiveConversationId(id);
setIsNewChat(false);
await persistence.loadConversation(id);
},
- [activeConversationId, persistence]
+ [activeConversationId, cancelStream, persistence]
);
const handleNewChat = useCallback(() => {
+ cancelStream();
setActiveConversationId(null);
setIsNewChat(true);
persistence.handleNewChat();
- }, [persistence]);
+ }, [cancelStream, persistence]);
const createConversation = useCallback(
async (text: string) => {
@@ -83,6 +90,7 @@ export default function ChatView() {
streaming,
createConversation,
onBeforeSend: markChatStarted,
+ onSendingChange: setSubmissionInFlight,
});
const handleArchive = useCallback(
@@ -172,7 +180,15 @@ export default function ChatView() {
<div className="px-3 pb-3 pt-1">
<ChatInput
className={PAGE_CONTENT_WIDTH_CLASS}
- agentState={streaming.agentState}
+ // New chat and switching cancel the stream at once, but the
+ // cancelled send can hold the submission lock until an
+ // in-flight tool returns; a message sent before then would
+ // be dropped, so the input stays busy until it lets go.
+ agentState={
+ submissionInFlight && streaming.agentState === "idle"
+ ? "thinking"
+ : streaming.agentState
+ }
partialTranscript=""
onTextSubmit={handleTextSubmit}
onCancel={streaming.cancelStream}
diff --git a/src/components/chat/toolExecutionScope.ts b/src/components/chat/toolExecutionScope.ts
new file mode 100644
index 000000000..63ff8512d
--- /dev/null
+++ b/src/components/chat/toolExecutionScope.ts
@@ -0,0 +1,49 @@
+import type { HoldDeliveryOptions, ToolExecutionContext } from "../../services/tools/ToolRegistry";
+
+export interface ToolExecutionScope {
+ createContext: (toolCallId: string) => ToolExecutionContext;
+ abort: () => void;
+}
+
+interface ToolExecutionHandlers {
+ onApprovalRequested?: () => void;
+ onHoldDelivery?: (options?: HoldDeliveryOptions) => void;
+}
+
+/**
+ * One scope per chat send. Its signal is the single thing every
+ * conversation-ending path (Esc, new chat, unmount) aborts, so tools waiting
+ * on the user (approval cards) are released no matter how the turn ended.
+ * Notices from a tool that finishes after that are dropped, so a late result
+ * cannot reopen a panel the user dismissed.
+ */
+export function createToolExecutionScope(handlers: ToolExecutionHandlers = {}): ToolExecutionScope {
+ const controller = new AbortController();
+ const turnSlots = new Map<string, number>();
+ const notify =
+ <Args extends unknown[]>(handler?: (...args: Args) => void) =>
+ (...args: Args): void => {
+ if (!controller.signal.aborted) handler?.(...args);
+ };
+ const claimTurnSlot = (key: string, limit: number): boolean => {
+ const used = turnSlots.get(key) ?? 0;
+ if (used >= limit) return false;
+ turnSlots.set(key, used + 1);
+ return true;
+ };
+ const releaseTurnSlot = (key: string): void => {
+ const used = turnSlots.get(key) ?? 0;
+ if (used > 0) turnSlots.set(key, used - 1);
+ };
+ return {
+ createContext: (toolCallId) => ({
+ toolCallId,
+ signal: controller.signal,
+ onApprovalRequested: notify(handlers.onApprovalRequested),
+ onHoldDelivery: notify(handlers.onHoldDelivery),
+ claimTurnSlot,
+ releaseTurnSlot,
+ }),
+ abort: () => controller.abort(),
+ };
+}
diff --git a/src/components/chat/toolIcons.ts b/src/components/chat/toolIcons.ts
index e15d9c10f..e70eb56b3 100644
--- a/src/components/chat/toolIcons.ts
+++ b/src/components/chat/toolIcons.ts
@@ -9,6 +9,8 @@ import {
FilePlus,
FilePen,
Zap,
+ Mail,
+ Users,
} from "../icons";
export const toolIcons: Record<string, typeof Search> = {
@@ -23,4 +25,6 @@ export const toolIcons: Record<string, typeof Search> = {
get_snippet: Zap,
update_snippets: Zap,
update_dictionary: BookOpen,
+ email_draft: Mail,
+ find_contact: Users,
};
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
index eb1b91e3b..7311a4416 100644
--- a/src/components/chat/useChatStreaming.ts
+++ b/src/components/chat/useChatStreaming.ts
@@ -8,10 +8,15 @@ import { resolveChatStreamingInference } from "../../helpers/dictationAgentInfer
import logger from "../../utils/logger";
import {
isAgentAllowed,
+ isConnectorsAllowed,
isLlmSelectionAllowed,
isWebSearchAllowed,
} from "../../stores/policyRules";
import { usePolicyStore } from "../../stores/policyStore";
+import { getUsageState } from "../../lib/usageStore";
+import { readIsSubscribed } from "../../lib/subscriptionFlag";
+import { hasConnectorPlan } from "../../utils/connectorEligibility";
+import { resolveEmailDraftTarget } from "../../utils/emailDraftTarget";
import {
appendDictionarySuffix,
appendPlainTextResponseSuffix,
@@ -20,7 +25,12 @@ import {
} from "../../config/prompts";
import { getDictionaryHintWords } from "../../utils/snippets";
import { createToolRegistry } from "../../services/tools";
-import type { ToolRegistry } from "../../services/tools/ToolRegistry";
+import {
+ executeTool,
+ type HoldDeliveryOptions,
+ type ToolRegistry,
+} from "../../services/tools/ToolRegistry";
+import { createToolExecutionScope, type ToolExecutionScope } from "./toolExecutionScope";
import { getAgentToolActivityRemainingMs } from "../../helpers/agentToolPresentation";
import type { Message, AgentState, ChatImageAttachment, ToolCallInfo } from "./types";
import type { ContainerScope } from "../../types/chat";
@@ -83,6 +93,11 @@ interface UseChatStreamingOptions {
noteContext?: string;
/** Optional container scope applied to RAG and the search_notes tool (container overview chat). */
searchScope?: ContainerScope;
+ /**
+ * Offer connector tools (email drafts, contact lookup) when the plan and
+ * policy allow them. Off unless a surface opts in: they act outside the app.
+ */
+ allowConnectors?: boolean;
onStreamComplete?: (assistantId: string, content: string, toolCalls?: ToolCallInfo[]) => void;
/** Fires exactly once when displayable assistant content or tool activity becomes available. */
onResponseContent?: () => void;
@@ -103,6 +118,10 @@ export interface SendToAIOptions {
content: string;
toolCalls?: ToolCallInfo[];
}) => void | Promise<void>;
+ /** Fires when a tool shows an approval card, so a hidden panel can open. */
+ onApprovalRequested?: () => void;
+ /** Fires when this turn's answer must not be pasted at the caret (see ToolExecutionContext). */
+ onHoldDelivery?: (options?: HoldDeliveryOptions) => void;
}
export interface ChatStreaming {
@@ -135,6 +154,7 @@ export function useChatStreaming({
inferenceScope = "chatIntelligence",
noteContext: externalNoteContext,
searchScope,
+ allowConnectors = false,
onStreamComplete,
onResponseContent,
}: UseChatStreamingOptions): ChatStreaming {
@@ -204,11 +224,14 @@ export function useChatStreaming({
// before routing through cancelStream, so it never stamps this — which is
// how sendToAI tells a user's cancel from an unmount mid-stream.
const explicitCancelGenerationRef = useRef(0);
+ const toolScopeRef = useRef<ToolExecutionScope | null>(null);
const cancelStream = useCallback(() => {
sendGenerationRef.current += 1;
if (mountedRef.current) {
explicitCancelGenerationRef.current = sendGenerationRef.current;
}
+ toolScopeRef.current?.abort();
+ toolScopeRef.current = null;
ReasoningService.cancelActiveStream();
setAgentState("idle");
clearToolActivity();
@@ -232,404 +255,444 @@ export function useChatStreaming({
async (userText: string, allMessages: Message[], options?: SendToAIOptions) => {
const sendGeneration = ++sendGenerationRef.current;
const cancelled = () => sendGeneration !== sendGenerationRef.current;
- clearToolActivity();
- let responseAnnounced = false;
- const announceResponse = () => {
- if (responseAnnounced) return;
- responseAnnounced = true;
- if (!options?.suppressResponseContent) onResponseContent?.();
- };
- const settings = getSettings();
- const { config: llmConfig, attachScreenContext } = resolveChatStreamingInference(settings, {
- inferenceScope,
- hasScreenContext: !!options?.attachment,
- isProviderImageWired: providerSupportsImages,
+ // This send supersedes any still running, so that turn's tools are
+ // released now rather than when (or if) they settle.
+ toolScopeRef.current?.abort();
+ const toolScope = createToolExecutionScope({
+ onApprovalRequested: options?.onApprovalRequested,
+ onHoldDelivery: options?.onHoldDelivery,
});
- const requestedAttachment = attachScreenContext ? (options?.attachment ?? null) : null;
- const llmMode = llmConfig.mode || "openwhispr";
- const policyState = usePolicyStore.getState();
- const policyProvider =
- llmMode === "openwhispr"
- ? "openwhispr"
- : llmMode === "local"
- ? "local"
- : llmConfig.provider;
- if (
- !isAgentAllowed(policyState) ||
- !isLlmSelectionAllowed(policyState, { mode: llmMode, provider: policyProvider })
- ) {
- // The user message is already appended; answer it instead of dead-ending silently.
- const restriction = !isAgentAllowed(policyState)
- ? t("common.policyAgentRestricted")
- : t("common.policyAiProcessingRestricted");
- announceResponse();
- setMessages((prev) => [
- ...prev,
- { id: crypto.randomUUID(), role: "assistant", content: restriction, isStreaming: false },
- ]);
- return;
+ toolScopeRef.current = toolScope;
+ clearToolActivity();
+
+ // Every exit, thrown errors included, releases tools still waiting on
+ // this turn (an approval card would otherwise sit out its TTL). A newer
+ // send may already own toolScopeRef.
+ try {
+ await runSend();
+ } finally {
+ toolScope.abort();
+ if (toolScopeRef.current === toolScope) toolScopeRef.current = null;
}
- setAgentState("thinking");
- const isCloudAgent = llmMode === "openwhispr" && settings.isSignedIn;
- const isLanAgent = llmMode === "self-hosted" && !!llmConfig.remoteUrl;
- const isCustomAgent = llmMode === "providers" && llmConfig.provider === "custom";
- const isLocalProvider =
- !isEnterpriseProvider(llmConfig.provider) &&
- ![
- "openai",
- "groq",
- "custom",
- "anthropic",
- "gemini",
- "tinfoil",
- "openrouter",
- "corti",
- ].includes(llmConfig.provider);
- const localModelCanUseTool =
- isLocalProvider && estimateModelSizeB(llmConfig.model) >= LOCAL_TOOL_MIN_PARAMS_B;
- const supportsTools = isCloudAgent || !isLocalProvider || localModelCanUseTool;
-
- const scope = searchScopeRef.current;
- let registry: ToolRegistry | null = null;
- if (supportsTools) {
- const scopeKey = scope ? `${scope.spaceId}:${scope.folderId ?? ""}` : "";
- // The calendar tool reads the shared provider-deduped events table,
- // so any connected provider enables it.
- const calendarConnected =
- settings.gcalConnected || settings.mcalConnected || settings.appleCalendarConnected;
- const webSearchEnabled = isWebSearchAllowed(usePolicyStore.getState());
- // Triggers ride in the tool description, so a snippet edit rebuilds the registry.
- const snippetKey = settings.snippets.map((s) => s.trigger).join("|");
- const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}-${webSearchEnabled}-${snippetKey}`;
- if (toolRegistryRef.current?.key === cacheKey) {
- registry = toolRegistryRef.current.registry;
- } else {
- registry = createToolRegistry({
- isSignedIn: settings.isSignedIn,
- calendarConnected,
- cloudBackupEnabled: settings.cloudBackupEnabled,
- searchScope: scope,
- webSearchEnabled,
- vocabulary: {
- getDictionary: () => getSettings().customDictionary,
- updateDictionary: (changes) =>
- useSettingsStore.getState().updateCustomDictionary(changes),
- getSnippets: () => getSettings().snippets,
- setSnippets: (snippets) => useSettingsStore.getState().setSnippets(snippets),
+ async function runSend(): Promise<void> {
+ let responseAnnounced = false;
+ const announceResponse = () => {
+ if (responseAnnounced) return;
+ responseAnnounced = true;
+ if (!options?.suppressResponseContent) onResponseContent?.();
+ };
+ const settings = getSettings();
+ const { config: llmConfig, attachScreenContext } = resolveChatStreamingInference(settings, {
+ inferenceScope,
+ hasScreenContext: !!options?.attachment,
+ isProviderImageWired: providerSupportsImages,
+ });
+ const requestedAttachment = attachScreenContext ? (options?.attachment ?? null) : null;
+ const llmMode = llmConfig.mode || "openwhispr";
+ const policyState = usePolicyStore.getState();
+ const policyProvider =
+ llmMode === "openwhispr"
+ ? "openwhispr"
+ : llmMode === "local"
+ ? "local"
+ : llmConfig.provider;
+ if (
+ !isAgentAllowed(policyState) ||
+ !isLlmSelectionAllowed(policyState, { mode: llmMode, provider: policyProvider })
+ ) {
+ // The user message is already appended; answer it instead of dead-ending silently.
+ const restriction = !isAgentAllowed(policyState)
+ ? t("common.policyAgentRestricted")
+ : t("common.policyAiProcessingRestricted");
+ announceResponse();
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ content: restriction,
+ isStreaming: false,
},
- });
- toolRegistryRef.current = { key: cacheKey, registry };
+ ]);
+ return;
}
- }
- const ragContext = await buildRAGContext(userText, scope);
- if (cancelled() || !mountedRef.current) return;
- const combinedContext = [noteContextRef.current, ragContext].filter(Boolean).join("\n\n");
- // The user's dictionary rides on every conversation so replies use their
- // jargon — same suffix the dictation prompts carry.
- let systemPrompt = appendDictionarySuffix(
- getAgentSystemPrompt(
- registry?.getAll().map((t) => t.name),
- combinedContext || undefined
- ),
- getDictionaryHintWords(settings),
- settings.uiLanguage
- );
-
- const history: HistoryMessage[] = allMessages
- .slice(-20)
- .map((m) => ({ role: m.role, content: m.content }));
-
- const selectedContext = options?.selectedContext;
- if (selectedContext) {
- transformLastUserMessage(history, (message) =>
- typeof message.content === "string"
- ? { ...message, content: buildAgentRequestText(message.content, selectedContext) }
- : null
- );
- }
-
- // A screenshot the resolver kept rides with the command it came with:
- // BYOK models get it as an image part, the cloud agent as a dedicated
- // field the server vision-routes (older servers strip the unknown field,
- // which degrades to a plain command). A dropped one costs nothing but the
- // image — the command still runs.
- const attachment = requestedAttachment && !isCloudAgent ? requestedAttachment : null;
- const cloudScreenContext =
- requestedAttachment && isCloudAgent
- ? { data: requestedAttachment.image, mediaType: requestedAttachment.mediaType }
- : null;
- if (attachment) {
- // The screenshot needs its grounding instruction, exactly like the
- // dictation path pairs the suffix with an attached image. Restore it
- // for cloud context once openwhispr-api#157 vision-routes that field.
- systemPrompt = appendScreenContextSuffix(systemPrompt, settings.uiLanguage);
- }
- if (options?.plainTextResponse) {
- systemPrompt = appendPlainTextResponseSuffix(systemPrompt);
- }
- if (attachment) {
- transformLastUserMessage(history, (message) => ({
- role: "user",
- content: [
- { type: "text", text: message.content as string },
- { type: "image", image: attachment.image, mediaType: attachment.mediaType },
- ],
- }));
- }
+ setAgentState("thinking");
+ const isCloudAgent = llmMode === "openwhispr" && settings.isSignedIn;
+ const isLanAgent = llmMode === "self-hosted" && !!llmConfig.remoteUrl;
+ const isCustomAgent = llmMode === "providers" && llmConfig.provider === "custom";
+ const isLocalProvider =
+ !isEnterpriseProvider(llmConfig.provider) &&
+ ![
+ "openai",
+ "groq",
+ "custom",
+ "anthropic",
+ "gemini",
+ "tinfoil",
+ "openrouter",
+ "corti",
+ ].includes(llmConfig.provider);
+ const localModelCanUseTool =
+ isLocalProvider && estimateModelSizeB(llmConfig.model) >= LOCAL_TOOL_MIN_PARAMS_B;
+ const supportsTools = isCloudAgent || !isLocalProvider || localModelCanUseTool;
+
+ const scope = searchScopeRef.current;
+ let registry: ToolRegistry | null = null;
+ if (supportsTools) {
+ const scopeKey = scope ? `${scope.spaceId}:${scope.folderId ?? ""}` : "";
+ // The calendar tool reads the shared provider-deduped events table,
+ // so any connected provider enables it.
+ const calendarConnected =
+ settings.gcalConnected || settings.mcalConnected || settings.appleCalendarConnected;
+ const webSearchEnabled = isWebSearchAllowed(usePolicyStore.getState());
+ const connectors =
+ allowConnectors &&
+ settings.isSignedIn &&
+ hasConnectorPlan(getUsageState(), readIsSubscribed()) &&
+ isConnectorsAllowed(usePolicyStore.getState())
+ ? { emailDraftTarget: resolveEmailDraftTarget(settings) }
+ : undefined;
+ // Triggers ride in the tool description, so a snippet edit rebuilds the registry.
+ const snippetKey = settings.snippets.map((s) => s.trigger).join("|");
+ const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}-${webSearchEnabled}-${snippetKey}-${connectors?.emailDraftTarget ?? "no-connectors"}`;
+ if (toolRegistryRef.current?.key === cacheKey) {
+ registry = toolRegistryRef.current.registry;
+ } else {
+ registry = createToolRegistry({
+ isSignedIn: settings.isSignedIn,
+ calendarConnected,
+ cloudBackupEnabled: settings.cloudBackupEnabled,
+ searchScope: scope,
+ webSearchEnabled,
+ vocabulary: {
+ getDictionary: () => getSettings().customDictionary,
+ updateDictionary: (changes) =>
+ useSettingsStore.getState().updateCustomDictionary(changes),
+ getSnippets: () => getSettings().snippets,
+ setSnippets: (snippets) => useSettingsStore.getState().setSnippets(snippets),
+ },
+ connectors,
+ });
+ toolRegistryRef.current = { key: cacheKey, registry };
+ }
+ }
- const llmMessages = [{ role: "system", content: systemPrompt }, ...history];
-
- const assistantId = crypto.randomUUID();
- setMessages((prev) => [
- ...prev,
- { id: assistantId, role: "assistant", content: "", isStreaming: true },
- ]);
- setAgentState("streaming");
-
- // Chat re-parses the whole answer through react-markdown on every
- // content write, so one write per streamed token made parse cost scale
- // with token count. Buffer and flush at most once per interval.
- let fullContent = "";
- let contentFlushTimer: ReturnType<typeof setTimeout> | null = null;
- const cancelContentFlush = () => {
- if (contentFlushTimer === null) return;
- clearTimeout(contentFlushTimer);
- contentFlushTimer = null;
- };
- const flushContentNow = () => {
- cancelContentFlush();
- setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ const ragContext = await buildRAGContext(userText, scope);
+ if (cancelled() || !mountedRef.current) return;
+ const combinedContext = [noteContextRef.current, ragContext].filter(Boolean).join("\n\n");
+ // The user's dictionary rides on every conversation so replies use their
+ // jargon — same suffix the dictation prompts carry.
+ let systemPrompt = appendDictionarySuffix(
+ getAgentSystemPrompt(
+ registry?.getAll().map((t) => t.name),
+ combinedContext || undefined
+ ),
+ getDictionaryHintWords(settings),
+ settings.uiLanguage
);
- };
- const scheduleContentFlush = () => {
- if (contentFlushTimer !== null) return;
- contentFlushTimer = setTimeout(flushContentNow, STREAM_FLUSH_INTERVAL_MS);
- };
- try {
- let stream: AsyncGenerator<AgentStreamChunk>;
-
- if (isCloudAgent) {
- const executeToolCall = registry
- ? async (name: string, argsJson: string) => {
- const tool = registry.get(name);
- if (!tool)
- return {
- data: `Unknown tool: ${name}`,
- displayText: t("agentMode.tools.unknownTool", { name }),
- };
- let args: Record<string, unknown>;
- try {
- args = JSON.parse(argsJson);
- } catch {
- return {
- data: `Invalid tool arguments for ${name}`,
- displayText: t("agentMode.tools.invalidArgs", { name }),
- };
- }
- const result = await tool.execute(args);
- const data = result.success
- ? typeof result.data === "string"
- ? result.data
- : JSON.stringify(result.data)
- : result.displayText;
- const metadata =
- result.success && result.data && typeof result.data === "object"
- ? (result.data as Record<string, unknown> | Array<Record<string, unknown>>)
- : undefined;
- return { data, displayText: result.displayText, metadata };
- }
- : undefined;
-
- stream = ReasoningService.processTextStreamingCloud(llmMessages, {
- systemPrompt,
- tools: registry?.getAll().map((t) => ({
- name: t.name,
- description: t.description,
- parameters: t.parameters,
- })),
- executeToolCall,
- ...(cloudScreenContext ? { screenContext: cloudScreenContext } : {}),
- });
- } else {
- const aiTools = registry?.toAISDKFormat();
- stream = ReasoningService.processTextStreamingAI(
- llmMessages,
- llmConfig.model,
- llmConfig.provider,
- {
- systemPrompt,
- // Policy and managed enforcement judge the scope that actually
- // answers: the panel's Chat fallback as Chat, and the vision
- // override as the agent scope whose image lane it is.
- inferenceScope:
- llmConfig.scope === "dictationAgentVision" ? "dictationAgent" : llmConfig.scope,
- lanUrl: isLanAgent ? llmConfig.remoteUrl : undefined,
- baseUrl: isCustomAgent ? llmConfig.cloudBaseUrl || undefined : undefined,
- customApiKey:
- isCustomAgent || isLanAgent ? llmConfig.customApiKey || undefined : undefined,
- disableThinking: llmConfig.disableThinking,
- },
- aiTools
+ const history: HistoryMessage[] = allMessages
+ .slice(-20)
+ .map((m) => ({ role: m.role, content: m.content }));
+
+ const selectedContext = options?.selectedContext;
+ if (selectedContext) {
+ transformLastUserMessage(history, (message) =>
+ typeof message.content === "string"
+ ? { ...message, content: buildAgentRequestText(message.content, selectedContext) }
+ : null
);
}
- for await (const chunk of stream) {
- if (!mountedRef.current) {
- ReasoningService.cancelActiveStream();
- break;
+ // A screenshot the resolver kept rides with the command it came with:
+ // BYOK models get it as an image part, the cloud agent as a dedicated
+ // field the server vision-routes (older servers strip the unknown field,
+ // which degrades to a plain command). A dropped one costs nothing but the
+ // image — the command still runs.
+ const attachment = requestedAttachment && !isCloudAgent ? requestedAttachment : null;
+ const cloudScreenContext =
+ requestedAttachment && isCloudAgent
+ ? { data: requestedAttachment.image, mediaType: requestedAttachment.mediaType }
+ : null;
+ if (attachment) {
+ // The screenshot needs its grounding instruction, exactly like the
+ // dictation path pairs the suffix with an attached image. Restore it
+ // for cloud context once openwhispr-api#157 vision-routes that field.
+ systemPrompt = appendScreenContextSuffix(systemPrompt, settings.uiLanguage);
+ }
+ if (options?.plainTextResponse) {
+ systemPrompt = appendPlainTextResponseSuffix(systemPrompt);
+ }
+ if (attachment) {
+ transformLastUserMessage(history, (message) => ({
+ role: "user",
+ content: [
+ { type: "text", text: message.content as string },
+ { type: "image", image: attachment.image, mediaType: attachment.mediaType },
+ ],
+ }));
+ }
+
+ const llmMessages = [{ role: "system", content: systemPrompt }, ...history];
+
+ const assistantId = crypto.randomUUID();
+ setMessages((prev) => [
+ ...prev,
+ { id: assistantId, role: "assistant", content: "", isStreaming: true },
+ ]);
+ setAgentState("streaming");
+
+ // Chat re-parses the whole answer through react-markdown on every
+ // content write, so one write per streamed token made parse cost scale
+ // with token count. Buffer and flush at most once per interval.
+ let fullContent = "";
+ let contentFlushTimer: ReturnType<typeof setTimeout> | null = null;
+ const cancelContentFlush = () => {
+ if (contentFlushTimer === null) return;
+ clearTimeout(contentFlushTimer);
+ contentFlushTimer = null;
+ };
+ const flushContentNow = () => {
+ cancelContentFlush();
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ );
+ };
+ const scheduleContentFlush = () => {
+ if (contentFlushTimer !== null) return;
+ contentFlushTimer = setTimeout(flushContentNow, STREAM_FLUSH_INTERVAL_MS);
+ };
+
+ try {
+ let stream: AsyncGenerator<AgentStreamChunk>;
+ // Each call's own step text on the AI SDK path, whose tool results
+ // carry only the model-facing output (the cloud path yields it).
+ const toolDisplayTexts = new Map<string, string>();
+
+ if (isCloudAgent) {
+ const executeToolCall = registry
+ ? async (name: string, argsJson: string, toolCallId: string) => {
+ const tool = registry.get(name);
+ if (!tool)
+ return {
+ data: `Unknown tool: ${name}`,
+ displayText: t("agentMode.tools.unknownTool", { name }),
+ };
+ let args: Record<string, unknown>;
+ try {
+ args = JSON.parse(argsJson);
+ } catch {
+ return {
+ data: `Invalid tool arguments for ${name}`,
+ displayText: t("agentMode.tools.invalidArgs", { name }),
+ };
+ }
+ const result = await executeTool(tool, args, toolScope.createContext(toolCallId));
+ const data = result.success
+ ? typeof result.data === "string"
+ ? result.data
+ : JSON.stringify(result.data)
+ : result.displayText;
+ const metadata =
+ result.success && result.data && typeof result.data === "object"
+ ? (result.data as Record<string, unknown> | Array<Record<string, unknown>>)
+ : undefined;
+ return { data, displayText: result.displayText, metadata };
+ }
+ : undefined;
+
+ stream = ReasoningService.processTextStreamingCloud(llmMessages, {
+ systemPrompt,
+ tools: registry?.getAll().map((t) => ({
+ name: t.name,
+ description: t.description,
+ parameters: t.parameters,
+ })),
+ executeToolCall,
+ ...(cloudScreenContext ? { screenContext: cloudScreenContext } : {}),
+ });
+ } else {
+ const aiTools = registry?.toAISDKFormat(toolScope.createContext, (id, text) =>
+ toolDisplayTexts.set(id, text)
+ );
+ stream = ReasoningService.processTextStreamingAI(
+ llmMessages,
+ llmConfig.model,
+ llmConfig.provider,
+ {
+ systemPrompt,
+ // Policy and managed enforcement judge the scope that actually
+ // answers: the panel's Chat fallback as Chat, and the vision
+ // override as the agent scope whose image lane it is.
+ inferenceScope:
+ llmConfig.scope === "dictationAgentVision" ? "dictationAgent" : llmConfig.scope,
+ lanUrl: isLanAgent ? llmConfig.remoteUrl : undefined,
+ baseUrl: isCustomAgent ? llmConfig.cloudBaseUrl || undefined : undefined,
+ customApiKey:
+ isCustomAgent || isLanAgent ? llmConfig.customApiKey || undefined : undefined,
+ disableThinking: llmConfig.disableThinking,
+ },
+ aiTools
+ );
}
- if (chunk.type === "content") {
- if (chunk.text) announceResponse();
- fullContent += chunk.text;
- scheduleContentFlush();
- } else if (chunk.type === "tool_calls") {
- // Text that arrived before a tool step must be on screen before the
- // step appears, not an interval after it.
- flushContentNow();
- if (chunk.calls.length > 0) announceResponse();
- for (const call of chunk.calls) {
- setAgentState("tool-executing");
- beginToolActivity(
- call.name,
- t(`agentMode.tools.${call.name}Status`, { defaultValue: `Using ${call.name}...` })
- );
+
+ for await (const chunk of stream) {
+ if (!mountedRef.current) {
+ ReasoningService.cancelActiveStream();
+ break;
+ }
+ if (chunk.type === "content") {
+ if (chunk.text) announceResponse();
+ fullContent += chunk.text;
+ scheduleContentFlush();
+ } else if (chunk.type === "tool_calls") {
+ // Text that arrived before a tool step must be on screen before the
+ // step appears, not an interval after it.
+ flushContentNow();
+ if (chunk.calls.length > 0) announceResponse();
+ for (const call of chunk.calls) {
+ setAgentState("tool-executing");
+ beginToolActivity(
+ call.name,
+ t(`agentMode.tools.${call.name}Status`, { defaultValue: `Using ${call.name}...` })
+ );
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantId
+ ? {
+ ...m,
+ toolCalls: [
+ ...(m.toolCalls || []),
+ {
+ id: call.id,
+ name: call.name,
+ arguments: call.arguments,
+ status: "executing" as const,
+ },
+ ],
+ }
+ : m
+ )
+ );
+ }
+ } else if (chunk.type === "tool_result") {
setMessages((prev) =>
prev.map((m) =>
- m.id === assistantId
+ m.id === assistantId && m.toolCalls
? {
...m,
- toolCalls: [
- ...(m.toolCalls || []),
- {
- id: call.id,
- name: call.name,
- arguments: call.arguments,
- status: "executing" as const,
- },
- ],
+ toolCalls: m.toolCalls.map((tc) =>
+ tc.id === chunk.callId
+ ? {
+ ...tc,
+ status: "completed" as const,
+ result: toolDisplayTexts.get(chunk.callId) ?? chunk.displayText,
+ ...(chunk.metadata ? { metadata: chunk.metadata } : {}),
+ }
+ : tc
+ ),
}
: m
)
);
+ setAgentState("streaming");
+ completeToolActivity();
}
- } else if (chunk.type === "tool_result") {
+ }
+
+ if (cancelled() || !mountedRef.current) {
+ flushContentNow();
setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId && m.toolCalls
- ? {
- ...m,
- toolCalls: m.toolCalls.map((tc) =>
- tc.id === chunk.callId
- ? {
- ...tc,
- status: "completed" as const,
- result: chunk.displayText,
- ...(chunk.metadata ? { metadata: chunk.metadata } : {}),
- }
- : tc
- ),
- }
- : m
+ prev.map((message) =>
+ message.id === assistantId ? { ...message, isStreaming: false } : message
)
);
- setAgentState("streaming");
- completeToolActivity();
+ // An unmount mid-stream (page navigation) keeps the partial reply in
+ // history so the saved conversation matches what the user last saw;
+ // an explicit cancel drops it. The unmount cleanup cancels too, so
+ // cancelled() alone cannot tell the two apart. Neither path may run
+ // the per-request delivery hook.
+ const explicitlyCancelled = explicitCancelGenerationRef.current > sendGeneration;
+ if (!explicitlyCancelled && fullContent.trim().length > 0) {
+ const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
+ onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);
+ }
+ return;
}
- }
- if (cancelled() || !mountedRef.current) {
flushContentNow();
- setMessages((prev) =>
- prev.map((message) =>
- message.id === assistantId ? { ...message, isStreaming: false } : message
- )
- );
- // An unmount mid-stream (page navigation) keeps the partial reply in
- // history so the saved conversation matches what the user last saw;
- // an explicit cancel drops it. The unmount cleanup cancels too, so
- // cancelled() alone cannot tell the two apart. Neither path may run
- // the per-request delivery hook.
- const explicitlyCancelled = explicitCancelGenerationRef.current > sendGeneration;
- if (!explicitlyCancelled && fullContent.trim().length > 0) {
- const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
- onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);
+ const hasDeliverableContent = fullContent.trim().length > 0;
+ if (!responseAnnounced && !cancelled()) {
+ // The stream ended without a visible token or tool call (think-only
+ // local model, empty completion). Show that as a reply so every
+ // listener — the assistant panel's thinking state included — sees a
+ // terminal outcome.
+ fullContent = t("agentMode.chat.emptyResponse");
+ announceResponse();
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ );
}
- return;
- }
- flushContentNow();
- const hasDeliverableContent = fullContent.trim().length > 0;
- if (!responseAnnounced && !cancelled()) {
- // The stream ended without a visible token or tool call (think-only
- // local model, empty completion). Show that as a reply so every
- // listener — the assistant panel's thinking state included — sees a
- // terminal outcome.
- fullContent = t("agentMode.chat.emptyResponse");
- announceResponse();
setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ prev.map((m) => (m.id === assistantId ? { ...m, isStreaming: false } : m))
);
- }
- setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, isStreaming: false } : m))
- );
-
- const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
- onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);
- if (hasDeliverableContent) {
- await options?.onComplete?.({
- assistantId,
- content: fullContent,
- toolCalls: finalMsg?.toolCalls,
- });
- }
- } catch (error) {
- if (cancelled()) {
- flushContentNow();
- setMessages((prev) =>
- prev.map((message) =>
- message.id === assistantId ? { ...message, isStreaming: false } : message
- )
- );
- } else {
- cancelContentFlush();
- logger.error(
- "Assistant request failed",
- {
- scope: llmConfig.scope,
- mode: llmMode,
- provider: llmConfig.provider,
- model: llmConfig.model,
- attachScreenContext,
- error: (error as Error).message,
- },
- "reasoning"
- );
- announceResponse();
- setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId
- ? {
- ...m,
- content: `${t("agentMode.chat.errorPrefix")}: ${(error as Error).message}`,
- isStreaming: false,
- }
- : m
- )
- );
+ const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
+ onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);
+ if (hasDeliverableContent) {
+ await options?.onComplete?.({
+ assistantId,
+ content: fullContent,
+ toolCalls: finalMsg?.toolCalls,
+ });
+ }
+ } catch (error) {
+ if (cancelled()) {
+ flushContentNow();
+ setMessages((prev) =>
+ prev.map((message) =>
+ message.id === assistantId ? { ...message, isStreaming: false } : message
+ )
+ );
+ } else {
+ cancelContentFlush();
+ logger.error(
+ "Assistant request failed",
+ {
+ scope: llmConfig.scope,
+ mode: llmMode,
+ provider: llmConfig.provider,
+ model: llmConfig.model,
+ attachScreenContext,
+ error: (error as Error).message,
+ },
+ "reasoning"
+ );
+ announceResponse();
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantId
+ ? {
+ ...m,
+ content: `${t("agentMode.chat.errorPrefix")}: ${(error as Error).message}`,
+ isStreaming: false,
+ }
+ : m
+ )
+ );
+ }
}
- }
- setAgentState("idle");
- completeToolActivity();
+ setAgentState("idle");
+ completeToolActivity();
+ }
},
[
inferenceScope,
+ allowConnectors,
t,
setMessages,
onStreamComplete,
diff --git a/src/components/dictation/AssistantPanel.tsx b/src/components/dictation/AssistantPanel.tsx
index d31c1521f..9a3f1ee52 100644
--- a/src/components/dictation/AssistantPanel.tsx
+++ b/src/components/dictation/AssistantPanel.tsx
@@ -42,6 +42,9 @@ import {
deliverAssistantResponse,
type AssistantResponseDelivery,
} from "../../helpers/assistantResponseDelivery";
+import { buildAssistantCommandSendOptions } from "./assistantCommandOptions";
+import { ApprovalCard } from "../chat/ApprovalCard";
+import { useConnectorApprovalStore } from "../../stores/connectorApprovalStore";
export interface AssistantCommand {
id: number;
@@ -117,6 +120,7 @@ export function AssistantPanel({
setMessages,
// Spoken commands answer on the Voice Assistant scope, not the Chat one.
inferenceScope: "dictationAgent",
+ allowConnectors: true,
onStreamComplete: (_assistantId, content, toolCalls) => {
void persistence.saveAssistantMessage(content, toolCalls);
},
@@ -195,28 +199,19 @@ export function AssistantPanel({
}
consumedCommandIdRef.current = pendingCommand.id;
const commandId = pendingCommand.id;
- const delivery = pendingCommand.delivery;
- const targetsCapturedInput = delivery?.mode === "paste";
- // A caret in a markdown-friendly app still keeps the compact pill.
- const plainTextResponse = delivery?.mode === "paste" && delivery.plainText;
- let responseDelivered = false;
+ const { options: sendOptions, wasDelivered } = buildAssistantCommandSendOptions(
+ pendingCommand,
+ {
+ onResponseContent,
+ deliver: deliverAssistantResponse,
+ confirmCopied: (content) => confirmCopied(content, AUTO_COPY_FEEDBACK_MS),
+ }
+ );
if (pendingCommand.selectedContext) {
setSelectedContext(null);
onSelectionContextChange(null);
}
- void sendMessage(pendingCommand.text, {
- attachment: pendingCommand.attachment ?? undefined,
- selectedContext: pendingCommand.selectedContext ?? undefined,
- suppressResponseContent: targetsCapturedInput,
- plainTextResponse,
- onComplete: delivery
- ? async ({ content }) => {
- const result = await deliverAssistantResponse(delivery, content);
- responseDelivered = result.pasted;
- if (result.copied) confirmCopied(content, AUTO_COPY_FEEDBACK_MS);
- }
- : undefined,
- })
+ void sendMessage(pendingCommand.text, sendOptions)
.then((sent) => {
if (sent) {
onCommandConsumed(commandId);
@@ -244,7 +239,7 @@ export function AssistantPanel({
},
]);
})
- .finally(() => onCommandSettled(commandId, { showPanel: !responseDelivered }));
+ .finally(() => onCommandSettled(commandId, { showPanel: !wasDelivered() }));
}, [
historyReady,
submissionInFlight,
@@ -253,13 +248,21 @@ export function AssistantPanel({
onCommandDiscarded,
onCommandSettled,
onSelectionContextChange,
+ onResponseContent,
confirmCopied,
sendMessage,
setMessages,
t,
]);
- const isToolExecuting = Boolean(streaming.activeToolName);
+ const approvalEntries = useConnectorApprovalStore((state) => state.entries);
+ const panelApprovals = (latestAssistantMessage?.toolCalls ?? [])
+ .map((toolCall) => approvalEntries[toolCall.id])
+ .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
+ const approvalAwaitingUser = panelApprovals.some(
+ (entry) => entry.state === "pending" || entry.state === "committing"
+ );
+ const isToolExecuting = Boolean(streaming.activeToolName) && !approvalAwaitingUser;
const isBusy = resolveAssistantPanelBusy({
agentState: streaming.agentState,
activeToolName: streaming.activeToolName,
@@ -519,6 +522,9 @@ export function AssistantPanel({
)}
</div>
) : null}
+ {panelApprovals.map((entry) => (
+ <ApprovalCard key={entry.toolCallId} entry={entry} />
+ ))}
{thinking && (
<div role="status">
<span className="sr-only">{t("agentMode.input.thinking")}</span>
diff --git a/src/components/dictation/assistantCommandOptions.ts b/src/components/dictation/assistantCommandOptions.ts
new file mode 100644
index 000000000..280fefcae
--- /dev/null
+++ b/src/components/dictation/assistantCommandOptions.ts
@@ -0,0 +1,70 @@
+import type { SendToAIOptions } from "../chat/useChatStreaming";
+import type { ChatImageAttachment } from "../chat/types";
+import type { AgentSelectionContext } from "../../utils/agentSelectionContext";
+import type { AssistantResponseDelivery } from "../../helpers/assistantResponseDelivery";
+import type { HoldDeliveryOptions } from "../../services/tools/ToolRegistry";
+
+interface CommandInput {
+ attachment: ChatImageAttachment | null;
+ selectedContext: AgentSelectionContext | null;
+ delivery: AssistantResponseDelivery | null;
+}
+
+interface CommandHandlers {
+ onResponseContent: () => void;
+ deliver: (
+ delivery: AssistantResponseDelivery,
+ content: string
+ ) => Promise<{ pasted: boolean; copied: boolean }>;
+ confirmCopied: (content: string) => void;
+}
+
+const PANEL_DELIVERY: AssistantResponseDelivery = { mode: "clipboard" };
+
+/**
+ * Send options for one voice command. Two tool events hold the turn in the
+ * panel instead of pasting it at the caret: an approval card must be visible,
+ * and a tool can ask for the hold (it opened a compose window that took focus,
+ * or needs the user to answer a question that must not land in their
+ * document). A held answer is still copied like any panel answer, unless the
+ * tool may have put content on the clipboard that the copy would overwrite, or
+ * the caret delivery promised to leave the user's clipboard as it was.
+ */
+export function buildAssistantCommandSendOptions(
+ command: CommandInput,
+ handlers: CommandHandlers
+): { options: SendToAIOptions; wasDelivered: () => boolean } {
+ const { delivery } = command;
+ let pasteHeld = false;
+ let clipboardPreserved = false;
+ let delivered = false;
+ const holdInPanel = (hold?: HoldDeliveryOptions): void => {
+ pasteHeld = true;
+ if (hold?.preserveClipboard) clipboardPreserved = true;
+ handlers.onResponseContent();
+ };
+
+ return {
+ options: {
+ attachment: command.attachment ?? undefined,
+ selectedContext: command.selectedContext ?? undefined,
+ suppressResponseContent: delivery?.mode === "paste",
+ // A caret in a markdown-friendly app still keeps the compact pill.
+ plainTextResponse: delivery?.mode === "paste" && delivery.plainText,
+ onApprovalRequested: () => holdInPanel(),
+ onHoldDelivery: holdInPanel,
+ onComplete: delivery
+ ? async ({ content }) => {
+ const keepsClipboard =
+ clipboardPreserved ||
+ (pasteHeld && delivery.mode === "paste" && delivery.restoreClipboard);
+ if (keepsClipboard) return;
+ const result = await handlers.deliver(pasteHeld ? PANEL_DELIVERY : delivery, content);
+ delivered = result.pasted;
+ if (result.copied) handlers.confirmCopied(content);
+ }
+ : undefined,
+ },
+ wasDelivered: () => delivered,
+ };
+}
diff --git a/src/components/onboarding/CalendarConnectionsStep.tsx b/src/components/onboarding/CalendarConnectionsStep.tsx
index ca4cbd8ad..e294ca8fd 100644
--- a/src/components/onboarding/CalendarConnectionsStep.tsx
+++ b/src/components/onboarding/CalendarConnectionsStep.tsx
@@ -55,7 +55,7 @@ export default function CalendarConnectionsStep() {
const current = useSettingsStore.getState().mcalAccounts;
store.setMcalAccounts([
...current.filter((account) => account.email !== result.email),
- { email: result.email },
+ { email: result.email, tenantId: result.tenantId },
]);
} else if (!result?.error?.includes("access_denied")) {
setError(t("integrations.microsoftCalendar.connectFailedDescription"));
diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsx
index 0df0d20f1..f784a8811 100644
--- a/src/components/ui/SettingsSection.tsx
+++ b/src/components/ui/SettingsSection.tsx
@@ -118,6 +118,14 @@ export function SettingsPanelRow({
);
}
+export function SectionLabel({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 mb-2 ps-1">
+ {children}
+ </div>
+ );
+}
+
export function SectionHeader({ title, description }: { title: string; description?: string }) {
return (
<div className="mb-3">
diff --git a/src/config/prompts.ts b/src/config/prompts.ts
index 93882f13f..f09db31fe 100644
--- a/src/config/prompts.ts
+++ b/src/config/prompts.ts
@@ -50,6 +50,10 @@ const TOOL_INSTRUCTIONS: Record<string, string> = {
"Use get_calendar_events to check the user's schedule, upcoming meetings, or calendar events.",
get_calendar_availability:
"Use get_calendar_availability when the user asks when they are free or requests open time slots. Pass timezone-aware RFC3339 start and end timestamps, deriving the correct offset for each future date from the IANA time zone rather than assuming the current offset across a daylight-saving transition. Treat the returned slotCount and each slot's localized date, weekday, times, and duration as authoritative: use them exactly and never recalculate, add, omit, merge, or invent slots. For a broad multi-day request without daily-hour bounds, ask which hours of each day to consider, then make a separate call for each day. Results reflect the local calendar cache across the user's selected connected calendars, so describe free results as no scheduled conflicts found rather than guaranteed real-time availability, and never infer event details from availability facts.",
+ find_contact:
+ "Use find_contact to look up a person's email address by name before drafting an email to them.",
+ email_draft:
+ "Use email_draft to open a pre-filled email draft for the user to review and send themselves; it never sends.",
};
const twoDigits = (value: number): string => String(value).padStart(2, "0");
@@ -71,6 +75,13 @@ function getLocalCalendarContext(): string {
return `Current local date and time: ${formatLocalRfc3339(now)}. IANA time zone: ${timeZone}.`;
}
+const CONNECTOR_TOOL_NAMES = ["find_contact", "email_draft"];
+
+// Each result that must not be retried says so in its own guidance, so the
+// rule needs no list of statuses (and grows with no new connector).
+const CONNECTOR_TOOL_RULES =
+ "Follow the guidance and message in each connector result, including when not to retry. When a result leaves it unclear who or what the user meant (a needs_clarification result that lists candidates, or find_contact finding no one or several people), ask the user before acting.";
+
export function getAgentSystemPrompt(availableTools?: string[], noteContext?: string): string {
let prompt = resolvePrompt("chatAgent", { agentName: null });
@@ -79,6 +90,9 @@ export function getAgentSystemPrompt(availableTools?: string[], noteContext?: st
if (toolLines.length > 0) {
prompt += "\n\nYou have access to tools. " + toolLines.join(" ");
}
+ if (availableTools.some((name) => CONNECTOR_TOOL_NAMES.includes(name))) {
+ prompt += "\n\n" + CONNECTOR_TOOL_RULES;
+ }
if (availableTools.includes("get_calendar_availability")) {
prompt += "\n\n" + getLocalCalendarContext();
}
diff --git a/src/helpers/appleCalendarManager.js b/src/helpers/appleCalendarManager.js
index c3aefe4e6..47ec9e195 100644
--- a/src/helpers/appleCalendarManager.js
+++ b/src/helpers/appleCalendarManager.js
@@ -274,12 +274,16 @@ class AppleCalendarManager {
this.databaseManager.replaceAppleCalendarEvents(events.map((event) => this._mapEvent(event)));
const contacts = [];
+ const notContacts = [];
for (const event of events) {
for (const attendee of event.attendees || []) {
- if (attendee.email) contacts.push({ email: attendee.email, displayName: attendee.name });
+ if (!attendee.email) continue;
+ // Rooms and the user (EventKit's current user) aren't people to write to.
+ if (attendee.resource || attendee.self) notContacts.push(attendee.email);
+ else contacts.push({ email: attendee.email, displayName: attendee.name });
}
}
- if (contacts.length > 0) this.databaseManager.upsertContacts(contacts);
+ this.databaseManager.syncCalendarContacts("apple", null, contacts, notContacts);
broadcastToWindows("acal-events-synced", {});
this.reminderScheduler.reconcileProvider("apple");
@@ -324,7 +328,10 @@ class AppleCalendarManager {
// Generic fallback only for the event's own URL field
(event.url?.startsWith("https://") ? event.url : null),
conference_data: null,
- organizer_email: event.organizer_email || null,
+ // Dropped when the user organized it, which contact lookup (this
+ // column's only reader) can't otherwise tell: Apple has no account email
+ // to exclude, and EventKit often leaves the organizer out of attendees.
+ organizer_email: event.organizer_self ? null : event.organizer_email || null,
attendees_count: attendees.length,
attendees: attendees.length
? JSON.stringify(
@@ -333,6 +340,7 @@ class AppleCalendarManager {
displayName: a.name || null,
responseStatus: a.status || null,
self: a.self || false,
+ ...(a.resource ? { resource: true } : {}),
}))
)
: null,
diff --git a/src/helpers/connectors/actionLog.js b/src/helpers/connectors/actionLog.js
new file mode 100644
index 000000000..4329bd415
--- /dev/null
+++ b/src/helpers/connectors/actionLog.js
@@ -0,0 +1,12 @@
+function createActionLog(databaseManager) {
+ return {
+ insert: (row) => databaseManager.insertConnectorAction(row),
+ update: (id, patch, fromState) =>
+ databaseManager.updateConnectorActionState(id, patch, fromState ?? null),
+ listRecent: (connector, limit, accountId) =>
+ databaseManager.listRecentConnectorActions(connector, limit, accountId),
+ reconcileInterrupted: () => databaseManager.reconcileInterruptedConnectorActions(),
+ };
+}
+
+module.exports = { createActionLog };
diff --git a/src/helpers/connectors/connectorIpc.js b/src/helpers/connectors/connectorIpc.js
new file mode 100644
index 000000000..1dcb2e9b9
--- /dev/null
+++ b/src/helpers/connectors/connectorIpc.js
@@ -0,0 +1,158 @@
+const { connectorPolicyState, policyRefusal } = require("./connectorPolicy");
+
+const POLICY_TIMEOUT_MS = 1500;
+// A name or part of an address; anything longer is not a lookup.
+const MAX_CONTACT_QUERY_LENGTH = 200;
+
+function isNonEmptyString(value) {
+ return typeof value === "string" && value.length > 0;
+}
+
+function isPlainObject(value) {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+function createConnectorPolicyResolver({
+ getAuthHeader,
+ getPolicy,
+ peekPolicy,
+ getAuthGeneration,
+ timeoutMs = POLICY_TIMEOUT_MS,
+}) {
+ // The deadline and the failure handling cover the whole resolution,
+ // including the auth-header lookup: nothing here can hang or throw.
+ return async (event) => {
+ let request = null;
+ const resolution = (async () => {
+ // Read before the (possibly async cookie) header lookup: a sign-in
+ // during it must fail the generation check, not pair old headers with
+ // the new generation.
+ const expectedAuthGeneration = getAuthGeneration();
+ const authHeaders = (await getAuthHeader(event)) || {};
+ // No account means no org policy can apply (same rule as screen context).
+ if (!authHeaders.Authorization && !authHeaders.Cookie) return "allowed";
+ request = { expectedAuthGeneration, authHeaders };
+ const snapshot = await getPolicy(request);
+ return connectorPolicyState(snapshot);
+ })().catch(() => "unavailable");
+
+ let timer;
+ const deadline = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(null), timeoutMs);
+ });
+ try {
+ const state = await Promise.race([resolution, deadline]);
+ if (state !== null) return state;
+ // A refresh that outlives the deadline must not override the verdict
+ // already held for this account; with none held, fail closed.
+ try {
+ return request && peekPolicy ? connectorPolicyState(peekPolicy(request)) : "unavailable";
+ } catch {
+ return "unavailable";
+ }
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+}
+
+function sameAccountScope(left, right) {
+ return Boolean(
+ left &&
+ right &&
+ left.accountId === right.accountId &&
+ left.authGeneration === right.authGeneration
+ );
+}
+
+// getAccountScope() is the signed-in account bound to the current credential
+// and its generation, or null.
+function registerConnectorIpc({ ipcMain, manager, getPolicyState, getAccountScope, findContacts }) {
+ // The verdict and the account that owns the receipt come from one
+ // credential: a sign-in or account switch during the policy wait leaves no
+ // account, so the action is refused rather than filed under the wrong one.
+ async function resolveCallAuth(event) {
+ const scope = getAccountScope();
+ const policyState = await getPolicyState(event);
+ return {
+ policyState,
+ accountId: sameAccountScope(scope, getAccountScope()) ? scope.accountId : null,
+ };
+ }
+
+ // Direct runs by the renderer's run id until they finish. A cancel (Esc)
+ // aborts the run's signal: a run still waiting on policy stops there, and
+ // the connector checks the signal again right before it acts.
+ const activeRuns = new Map();
+
+ ipcMain.handle("connector-status", () => manager.status());
+
+ ipcMain.handle("connector-prepare", async (event, connectorId, action, args) => {
+ if (!isNonEmptyString(connectorId) || !isNonEmptyString(action) || !isPlainObject(args)) {
+ return { status: "unavailable", reason: "invalid_request" };
+ }
+ return manager.prepare(connectorId, action, args, await resolveCallAuth(event));
+ });
+
+ ipcMain.handle("connector-commit", async (event, actionId, edits) => {
+ if (!isNonEmptyString(actionId)) return { state: "not_sent", reason: "invalid_request" };
+ return manager.commit(
+ actionId,
+ isPlainObject(edits) ? edits : {},
+ await resolveCallAuth(event)
+ );
+ });
+
+ // A run id equal to a pending approval's id must not swallow that
+ // approval's cancel, so both are cancelled.
+ ipcMain.handle("connector-cancel", (_event, actionId, reason) => {
+ if (!isNonEmptyString(actionId)) return { cancelled: false };
+ const run = activeRuns.get(actionId);
+ run?.abort();
+ const { cancelled } = manager.cancel(actionId, reason);
+ return { cancelled: Boolean(run) || cancelled };
+ });
+
+ ipcMain.handle("connector-run-direct", async (event, connectorId, action, args, runId) => {
+ if (!isNonEmptyString(connectorId) || !isNonEmptyString(action) || !isPlainObject(args)) {
+ return { state: "unavailable", reason: "invalid_request" };
+ }
+ const tracked = isNonEmptyString(runId);
+ // A second run under a live id would make the first one uncancellable.
+ if (tracked && activeRuns.has(runId)) {
+ return { state: "unavailable", reason: "invalid_request" };
+ }
+ const controller = new AbortController();
+ if (tracked) activeRuns.set(runId, controller);
+ try {
+ const auth = await resolveCallAuth(event);
+ if (controller.signal.aborted) return { state: "not_sent", reason: "cancelled" };
+ return await manager.runDirect(connectorId, action, args, auth, {
+ webContents: event.sender,
+ signal: controller.signal,
+ });
+ } finally {
+ if (tracked) activeRuns.delete(runId);
+ }
+ });
+
+ ipcMain.handle("connector-recent-actions", (_event, connectorId, limit) => {
+ if (!isNonEmptyString(connectorId)) return [];
+ return manager.recentActions(connectorId, limit, getAccountScope()?.accountId ?? null);
+ });
+
+ if (findContacts) {
+ // The results go to the model (and its provider), so the org switch
+ // applies here too, not just to actions that leave the device.
+ ipcMain.handle("connector-find-contacts", async (event, query) => {
+ if (typeof query !== "string" || !query.trim() || query.length > MAX_CONTACT_QUERY_LENGTH) {
+ return { contacts: [] };
+ }
+ const refusal = policyRefusal(await getPolicyState(event));
+ if (refusal) return { contacts: [], unavailableReason: refusal };
+ return findContacts(query.trim());
+ });
+ }
+}
+
+module.exports = { registerConnectorIpc, createConnectorPolicyResolver };
diff --git a/src/helpers/connectors/connectorManager.js b/src/helpers/connectors/connectorManager.js
new file mode 100644
index 000000000..25f58fc0c
--- /dev/null
+++ b/src/helpers/connectors/connectorManager.js
@@ -0,0 +1,459 @@
+const crypto = require("crypto");
+const { policyRefusal } = require("./connectorPolicy");
+
+const CANCEL_REASONS = new Set(["cancelled_by_user", "conversation_ended", "expired"]);
+
+// A connector is third-party code (or a stub in tests), so none of its result
+// fields are trusted: each state keeps only the fields it defines, with their
+// types checked. Anything else could leak to the renderer, or make the receipt
+// write throw and leave the row stuck at "committing".
+function stringFields(fields) {
+ return Object.fromEntries(
+ Object.entries(fields).filter(([, value]) => typeof value === "string")
+ );
+}
+
+function booleanFields(fields) {
+ return Object.fromEntries(
+ Object.entries(fields).filter(([, value]) => typeof value === "boolean")
+ );
+}
+
+function stringOr(value, fallback) {
+ return typeof value === "string" ? value : fallback;
+}
+
+const FAILED_MESSAGE = "That action didn't go through.";
+
+function failedResult(result) {
+ return {
+ state: "failed",
+ errorCode: stringOr(result.errorCode, "action_failed"),
+ message: stringOr(result.message, FAILED_MESSAGE),
+ };
+}
+
+// Anything other than a recognized outcome may still have reached the
+// provider, so it is "unknown", never "failed".
+function normalizeCommitResult(result) {
+ switch (result?.state) {
+ case "sent":
+ return { state: "sent", ...stringFields({ url: result.url }) };
+ case "failed":
+ return failedResult(result);
+ case "unknown":
+ return { state: "unknown", ...stringFields({ checkUrl: result.checkUrl }) };
+ default:
+ return { state: "unknown" };
+ }
+}
+
+// A direct action that threw or answered malformed may already have acted
+// (a compose window opened before a later step failed); calling it "failed"
+// would invite a duplicate retry.
+function uncertainDirectResult(errorCode) {
+ return {
+ state: "unknown",
+ errorCode,
+ message: "That action may have gone through. Ask the user to check before trying again.",
+ };
+}
+
+// "not_sent" is the connector saying it stopped before acting (a cancel that
+// landed in time).
+function normalizeDirectResult(result) {
+ const destination = stringFields({ destinationLabel: result?.destinationLabel });
+ switch (result?.state) {
+ case "sent":
+ return {
+ state: "sent",
+ destinationLabel: "",
+ ...destination,
+ ...booleanFields({
+ bodyCopied: result.bodyCopied,
+ subjectCopied: result.subjectCopied,
+ copyFailed: result.copyFailed,
+ }),
+ };
+ case "failed":
+ return { ...failedResult(result), ...destination };
+ case "not_sent":
+ return { state: "not_sent", reason: stringOr(result.reason, "cancelled") };
+ default:
+ return uncertainDirectResult("invalid_result");
+ }
+}
+
+const INVALID_PREPARE_RESULT = {
+ status: "failed",
+ errorCode: "invalid_result",
+ message: "Couldn't prepare that action.",
+};
+
+const RECEIPT_UNAVAILABLE_PREPARE_RESULT = {
+ status: "failed",
+ errorCode: "receipt_unavailable",
+ message: "Couldn't record this action, so nothing was prepared.",
+};
+
+function normalizePreviewNote(note) {
+ if (!note || typeof note.key !== "string") return null;
+ return note.values && typeof note.values === "object"
+ ? { key: note.key, values: stringFields(note.values) }
+ : { key: note.key };
+}
+
+// The card renders exactly this, so a preview missing a field it needs is
+// malformed rather than shown half empty.
+function normalizePreview(preview) {
+ if (!preview || typeof preview !== "object") return null;
+ const { verbKey, destinationLabel, accountLabel, body } = preview;
+ if (
+ ![verbKey, destinationLabel, accountLabel, body].every((value) => typeof value === "string")
+ ) {
+ return null;
+ }
+ return {
+ verbKey,
+ destinationLabel,
+ accountLabel,
+ body,
+ ...stringFields({ workspaceLabel: preview.workspaceLabel, title: preview.title }),
+ ...(Array.isArray(preview.notes)
+ ? { notes: preview.notes.map(normalizePreviewNote).filter(Boolean) }
+ : {}),
+ };
+}
+
+// The payload stays in main; only the fields each status defines reach the
+// renderer.
+function normalizePrepareResult(result) {
+ switch (result?.status) {
+ case "ready": {
+ const preview = normalizePreview(result.preview);
+ return preview
+ ? { status: "ready", payload: result.payload, preview }
+ : INVALID_PREPARE_RESULT;
+ }
+ case "needs_clarification":
+ return {
+ status: "needs_clarification",
+ message: stringOr(result.message, ""),
+ candidates: Array.isArray(result.candidates)
+ ? result.candidates.filter((candidate) => typeof candidate === "string")
+ : [],
+ };
+ case "failed":
+ return {
+ status: "failed",
+ errorCode: stringOr(result.errorCode, "prepare_failed"),
+ message: stringOr(result.message, INVALID_PREPARE_RESULT.message),
+ };
+ default:
+ return INVALID_PREPARE_RESULT;
+ }
+}
+
+function sanitizeEdits(edits) {
+ const clean = {};
+ if (edits && typeof edits.title === "string") clean.title = edits.title;
+ if (edits && typeof edits.body === "string") clean.body = edits.body;
+ return clean;
+}
+
+// Every action call carries `auth`: the org policy verdict and the signed-in
+// account it was resolved for. The account owns the receipt, so an action
+// with none (signed out, or mid sign-in or account switch) is refused before
+// anything is written or done.
+function createConnectorManager({
+ connectors,
+ pendingActions,
+ actionLog,
+ logger,
+ randomId = () => crypto.randomBytes(16).toString("hex"),
+}) {
+ const byId = new Map(connectors.map((connector) => [connector.id, connector]));
+
+ // Writes before a side effect gate it: without a durable row, a crash
+ // mid-send could hide a message that was actually sent.
+ function writeRequired(step, write) {
+ try {
+ return write() !== false;
+ } catch (error) {
+ logger.error("connector receipt write failed", { step, error: error.message }, "connectors");
+ return false;
+ }
+ }
+
+ // Writes after the outcome is known are best effort: a failure leaves the
+ // row in its last durable state, which reconciliation treats conservatively.
+ function record(write) {
+ try {
+ write();
+ } catch (error) {
+ logger.warn("connector receipt update failed", { error: error.message }, "connectors");
+ }
+ }
+
+ record(() => {
+ const reconciled = actionLog.reconcileInterrupted();
+ if (reconciled.unknown || reconciled.cancelled || reconciled.orphaned) {
+ logger.info("reconciled interrupted connector actions", reconciled, "connectors");
+ }
+ });
+
+ // Expired actions leave memory (and their payloads with them) on the next
+ // call, and their receipts say so rather than a later "app_quit".
+ function expireStale() {
+ for (const actionId of pendingActions.sweepExpired()) {
+ record(() =>
+ actionLog.update(actionId, { state: "expired", errorCode: "expired" }, "pending")
+ );
+ }
+ }
+
+ // A lookup that throws counts as no connection, so the connector's
+ // exception text never reaches the renderer.
+ async function readBinding(connector) {
+ try {
+ return await connector.getBinding();
+ } catch (error) {
+ logger.warn(
+ "connector binding lookup failed",
+ { connectorId: connector.id, error: error.message },
+ "connectors"
+ );
+ return null;
+ }
+ }
+
+ function resolveAction(connectorId, action, kind) {
+ const connector = byId.get(connectorId);
+ if (!connector) return { error: "unknown_connector" };
+ if (connector.actions[action]?.kind !== kind) return { error: "unknown_action" };
+ return { connector };
+ }
+
+ async function status() {
+ return Promise.all(
+ [...byId.values()].map(async (connector) => {
+ try {
+ return { id: connector.id, ...(await connector.getStatus()) };
+ } catch (error) {
+ logger.warn(
+ "connector status failed",
+ { connectorId: connector.id, error: error.message },
+ "connectors"
+ );
+ return { id: connector.id, connected: false, accountLabel: null };
+ }
+ })
+ );
+ }
+
+ async function prepare(connectorId, action, args, { policyState, accountId }) {
+ expireStale();
+ const refusal = policyRefusal(policyState);
+ if (refusal) return { status: "unavailable", reason: refusal };
+ const resolved = resolveAction(connectorId, action, "approval");
+ if (resolved.error) return { status: "unavailable", reason: resolved.error };
+ if (!accountId) return RECEIPT_UNAVAILABLE_PREPARE_RESULT;
+ const { connector } = resolved;
+
+ const binding = await readBinding(connector);
+ if (!binding) return { status: "unavailable", reason: "not_connected" };
+
+ let prepared;
+ try {
+ prepared = normalizePrepareResult(await connector.prepare(action, args || {}));
+ } catch (error) {
+ logger.warn(
+ "connector prepare threw",
+ { connectorId, action, error: error.message },
+ "connectors"
+ );
+ return { ...INVALID_PREPARE_RESULT, errorCode: "prepare_failed" };
+ }
+ if (prepared.status !== "ready") return prepared;
+
+ const actionId = pendingActions.create({
+ connectorId,
+ action,
+ binding,
+ accountId,
+ payload: prepared.payload,
+ preview: prepared.preview,
+ });
+ const recorded = writeRequired("pending", () => {
+ actionLog.insert({
+ id: actionId,
+ accountId,
+ connector: connectorId,
+ action,
+ kind: "approval",
+ destinationLabel: prepared.preview.destinationLabel,
+ state: "pending",
+ });
+ });
+ if (!recorded) {
+ pendingActions.cancel(actionId);
+ return RECEIPT_UNAVAILABLE_PREPARE_RESULT;
+ }
+ return { status: "ready", actionId, preview: prepared.preview };
+ }
+
+ // Withdrawn rather than left pending: a refused card is settled in the
+ // renderer, so nothing may commit it later.
+ function withdrawPending(actionId, reason) {
+ pendingActions.cancel(actionId);
+ record(() => actionLog.update(actionId, { state: "cancelled", errorCode: reason }, "pending"));
+ return { state: "not_sent", reason };
+ }
+
+ async function commit(actionId, edits, { policyState, accountId }) {
+ expireStale();
+ const entry = pendingActions.get(actionId);
+ if (!entry) return { state: "not_sent", reason: "not_found" };
+ // A second click while the first is sending must neither send nor
+ // overwrite the in-flight row.
+ if (entry.state !== "pending") return { state: "not_sent", reason: "not_pending" };
+
+ const refusal = policyRefusal(policyState);
+ if (refusal) return withdrawPending(actionId, refusal);
+ // Another account (or none) must not send what this one prepared.
+ if (entry.accountId !== accountId) return withdrawPending(actionId, "account_changed");
+
+ const connector = byId.get(entry.connectorId);
+ const begun = pendingActions.beginCommit(actionId, await readBinding(connector));
+ if (!begun.ok) {
+ if (begun.reason === "expired" || begun.reason === "connection_changed") {
+ const state = begun.reason === "expired" ? "expired" : "cancelled";
+ record(() => actionLog.update(actionId, { state, errorCode: begun.reason }, "pending"));
+ }
+ return { state: "not_sent", reason: begun.reason };
+ }
+
+ const recorded = writeRequired(
+ "committing",
+ () => actionLog.update(actionId, { state: "committing" }, "pending") === 1
+ );
+ if (!recorded) {
+ pendingActions.finish(actionId);
+ record(() =>
+ actionLog.update(
+ actionId,
+ { state: "cancelled", errorCode: "receipt_unavailable" },
+ "pending"
+ )
+ );
+ return { state: "not_sent", reason: "receipt_unavailable" };
+ }
+
+ let result;
+ try {
+ result = normalizeCommitResult(
+ await connector.commit(entry.action, entry.payload, sanitizeEdits(edits))
+ );
+ } catch (error) {
+ logger.warn(
+ "connector commit threw",
+ { connectorId: entry.connectorId, action: entry.action, error: error.message },
+ "connectors"
+ );
+ result = { state: "unknown" };
+ }
+
+ pendingActions.finish(actionId);
+ record(() =>
+ actionLog.update(actionId, {
+ state: result.state,
+ resultUrl: result.url || result.checkUrl || null,
+ errorCode: result.errorCode || null,
+ })
+ );
+ logger.info(
+ "connector action finished",
+ { connectorId: entry.connectorId, action: entry.action, state: result.state },
+ "connectors"
+ );
+ return result;
+ }
+
+ function cancel(actionId, reason) {
+ expireStale();
+ const safeReason = CANCEL_REASONS.has(reason) ? reason : "cancelled_by_user";
+ const cancelled = pendingActions.cancel(actionId);
+ if (cancelled) {
+ const state = safeReason === "expired" ? "expired" : "cancelled";
+ record(() => actionLog.update(actionId, { state, errorCode: safeReason }));
+ }
+ return { cancelled };
+ }
+
+ // runtime may carry a `signal`: a cancel that lands before the side effect
+ // must stop it (the connector checks it right before acting).
+ async function runDirect(connectorId, action, args, { policyState, accountId }, runtime) {
+ const refusal = policyRefusal(policyState);
+ if (refusal) return { state: "unavailable", reason: refusal };
+ const resolved = resolveAction(connectorId, action, "direct");
+ if (resolved.error) return { state: "unavailable", reason: resolved.error };
+ if (!accountId) return { state: "unavailable", reason: "receipt_unavailable" };
+
+ const id = randomId();
+ const recorded = writeRequired("direct", () => {
+ actionLog.insert({
+ id,
+ accountId,
+ connector: connectorId,
+ action,
+ kind: "direct",
+ state: "committing",
+ });
+ });
+ if (!recorded) return { state: "unavailable", reason: "receipt_unavailable" };
+
+ let result;
+ try {
+ result = normalizeDirectResult(
+ await resolved.connector.runDirect(action, args || {}, runtime || {})
+ );
+ } catch (error) {
+ logger.warn(
+ "connector direct action threw",
+ { connectorId, action, error: error.message },
+ "connectors"
+ );
+ result = uncertainDirectResult("direct_failed");
+ }
+ const outcome =
+ result.state === "not_sent"
+ ? { state: "cancelled", errorCode: result.reason }
+ : { state: result.state, errorCode: result.errorCode || null };
+ record(() =>
+ actionLog.update(id, { ...outcome, destinationLabel: result.destinationLabel || null })
+ );
+ return result;
+ }
+
+ function invalidate(connectorId) {
+ const removed = pendingActions.invalidateConnector(connectorId);
+ for (const actionId of removed) {
+ record(() =>
+ actionLog.update(actionId, { state: "cancelled", errorCode: "connection_changed" })
+ );
+ }
+ return removed;
+ }
+
+ // Receipts name the people a user wrote to: only the account that took the
+ // action sees them.
+ function recentActions(connectorId, limit, accountId) {
+ expireStale();
+ const safeLimit = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 50) : 10;
+ return actionLog.listRecent(connectorId, safeLimit, accountId);
+ }
+
+ return { status, prepare, commit, cancel, runDirect, invalidate, recentActions };
+}
+
+module.exports = { createConnectorManager };
diff --git a/src/helpers/connectors/connectorPolicy.js b/src/helpers/connectors/connectorPolicy.js
new file mode 100644
index 000000000..3226b59af
--- /dev/null
+++ b/src/helpers/connectors/connectorPolicy.js
@@ -0,0 +1,24 @@
+// Connector actions reach outside services, so unlike screen context only a
+// successful, well-formed snapshot allows them. Every failure code
+// (unresolvable, unavailable, throttled, auth context changed, and any added
+// later), a malformed snapshot, and a timeout (null) are "unavailable".
+function connectorPolicyState(snapshot) {
+ if (!snapshot || snapshot.success !== true || typeof snapshot.managed !== "boolean") {
+ return "unavailable";
+ }
+ if (!snapshot.managed) return "allowed";
+ const features = snapshot.policy?.features;
+ if (!features || typeof features !== "object") return "unavailable";
+ // Connectors are agent tools: an org that turns the agent off turns them off too.
+ return features.agentEnabled === false || features.connectorsEnabled === false
+ ? "blocked"
+ : "allowed";
+}
+
+// The reason a connector call reports for a verdict other than "allowed".
+function policyRefusal(policyState) {
+ if (policyState === "allowed") return null;
+ return policyState === "blocked" ? "policy_blocked" : "policy_unavailable";
+}
+
+module.exports = { connectorPolicyState, policyRefusal };
diff --git a/src/helpers/connectors/contactSearch.js b/src/helpers/connectors/contactSearch.js
new file mode 100644
index 000000000..381d36f01
--- /dev/null
+++ b/src/helpers/connectors/contactSearch.js
@@ -0,0 +1,123 @@
+const { parseEventTime } = require("../calendarAvailability");
+
+// Rooms, resources, groups and holiday calendars Google lists as attendees.
+const NON_PERSON_ADDRESS = /@(?:[^@]+\.)?calendar\.google\.com$/i;
+
+// Spoken names arrive without punctuation: "jean luc" for Jean-Luc, "obrien"
+// or "o brien" for O'Brien, "gabe torres" for gabe.torres@.
+function normalize(text) {
+ return String(text || "")
+ .normalize("NFD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .toLowerCase()
+ .replace(/['’]/g, "")
+ .replace(/[-_.\s]+/g, " ")
+ .trim();
+}
+
+function parseAttendees(value) {
+ if (!value) return [];
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+function collectPeople({ meetings = [], contacts = [], excludedEmails = [] }, now) {
+ const excluded = new Set(excludedEmails.map((email) => String(email).toLowerCase()));
+ const people = new Map();
+
+ const remember = (email, name, startTime, isAllDay) => {
+ if (typeof email !== "string" || !email.includes("@") || NON_PERSON_ADDRESS.test(email)) return;
+ const key = email.toLowerCase();
+ let person = people.get(key);
+ if (!person) {
+ person = { email, name: null, lastMet: null, lastMetTime: null, distance: Infinity };
+ people.set(key, person);
+ }
+ if (!person.name && name) person.name = name;
+ // All-day starts are local dates, not UTC midnight.
+ const time = parseEventTime(startTime, isAllDay);
+ if (time === null) return;
+ person.distance = Math.min(person.distance, Math.abs(time - now));
+ if (time <= now && (person.lastMetTime === null || time > person.lastMetTime)) {
+ person.lastMet = startTime;
+ person.lastMetTime = time;
+ }
+ };
+
+ for (const row of meetings) {
+ const attendees = parseAttendees(row.attendees);
+ for (const attendee of attendees) {
+ if (attendee?.self && typeof attendee.email === "string") {
+ excluded.add(attendee.email.toLowerCase());
+ }
+ }
+ for (const attendee of attendees) {
+ remember(attendee?.email, attendee?.displayName, row.start_time, row.is_all_day);
+ }
+ remember(row.organizer_email, null, row.start_time, row.is_all_day);
+ }
+ // Every sync adds its attendees here and only disconnecting their last
+ // source prunes them, so people whose meetings aged out of the calendar
+ // cache are still found. They come most recently synced first, which is how
+ // ties between them are broken.
+ for (const contact of contacts) remember(contact.email, contact.display_name, null);
+ for (const email of excluded) people.delete(email);
+ return [...people.values()];
+}
+
+function score(person, query, queryTokens, typedEmail) {
+ if (person.email.toLowerCase() === typedEmail) return 5;
+ const name = normalize(person.name);
+ const localPart = normalize(person.email.split("@")[0]);
+ if (name && name === query) return 4;
+ const words = `${name} ${localPart}`.split(" ").filter(Boolean);
+ if (queryTokens.every((token) => words.some((word) => word.startsWith(token)))) return 3;
+ const compactQuery = query.replace(/ /g, "");
+ const compactName = name.replace(/ /g, "");
+ if (
+ localPart.replace(/ /g, "").startsWith(compactQuery) ||
+ compactName.startsWith(compactQuery)
+ ) {
+ return 2;
+ }
+ // The domain only counts once the query has an @, or "al" would match
+ // everyone at alias.com.
+ const address = query.includes("@") ? normalize(person.email) : localPart;
+ if (compactName.includes(compactQuery) || address.includes(query)) return 1;
+ return 0;
+}
+
+/**
+ * People matching a name or address in the user's calendar meetings and
+ * synced contacts. A typed address ranks its owner first. Ties go to whoever
+ * the user meets closest to now, then to whoever was synced most recently;
+ * lastMet is the most recent past meeting still on record, or null. hasMore
+ * says the limit left matches out, so the model asks for a last name instead
+ * of offering the wrong few.
+ */
+function searchContacts(sources, query, { limit = 5, now = Date.now() } = {}) {
+ const normalizedQuery = normalize(query);
+ // A query without a letter or digit ("@", "-") would match everyone.
+ if (!/[\p{L}\p{N}]/u.test(normalizedQuery)) return { contacts: [], hasMore: false };
+ const queryTokens = normalizedQuery.split(" ");
+ const typedEmail = String(query).trim().toLowerCase();
+ const matches = collectPeople(sources, now)
+ .map((person) => ({
+ person,
+ score: score(person, normalizedQuery, queryTokens, typedEmail),
+ }))
+ .filter((match) => match.score > 0)
+ .sort((a, b) => b.score - a.score || a.person.distance - b.person.distance);
+ return {
+ contacts: matches
+ .slice(0, limit)
+ .map(({ person }) => ({ name: person.name, email: person.email, lastMet: person.lastMet })),
+ hasMore: matches.length > limit,
+ };
+}
+
+module.exports = { searchContacts };
diff --git a/src/helpers/connectors/emailCompose.js b/src/helpers/connectors/emailCompose.js
new file mode 100644
index 000000000..cb437af3f
--- /dev/null
+++ b/src/helpers/connectors/emailCompose.js
@@ -0,0 +1,187 @@
+// ESM like meetingJoinUrl.js: shared with the renderer (the email_draft tool
+// checks addresses) and loaded by the main-process email connector through
+// require(esm).
+
+export const COMPOSE_TARGETS = /** @type {const} */ ([
+ "gmail",
+ "outlookWork",
+ "outlookPersonal",
+ "mailto",
+]);
+
+// Windows caps every URL shell.openExternal opens at 2,081 characters, and
+// the Outlook links and mailto handlers are unmeasured, so they stay at
+// 2,000. Gmail on macOS and Linux takes much longer links (checked 2026-09-24:
+// 6,000 characters open, even through the signed-out redirect; 12,000 is an
+// HTTP 400), which matters because every non-ASCII character costs 6 to 12.
+const DEFAULT_COMPOSE_URL_LENGTH = 2000;
+const GMAIL_COMPOSE_URL_LENGTH = 6000;
+
+export function maxComposeUrlLength(target, platform) {
+ return target === "gmail" && (platform === "darwin" || platform === "linux")
+ ? GMAIL_COMPOSE_URL_LENGTH
+ : DEFAULT_COMPOSE_URL_LENGTH;
+}
+
+// Undocumented but widely used compose deep links.
+const COMPOSE_BASES = {
+ gmail: "https://mail.google.com/mail/?view=cm&fs=1",
+ outlookWork: "https://outlook.office.com/mail/deeplink/compose",
+ outlookPersonal: "https://outlook.live.com/mail/0/deeplink/compose",
+};
+
+// Combining marks may follow a label's first character: Devanagari, Thai and
+// Arabic with harakat spell words with them.
+const EMAIL_ADDRESS_PATTERN =
+ /^[^\s@<>()[\],;:"]+@(?:[\p{L}\p{N}](?:[\p{L}\p{N}\p{M}-]*[\p{L}\p{N}\p{M}])?\.)+[\p{L}\p{N}-][\p{L}\p{N}\p{M}-]+$/u;
+
+// The To field is the user's only look at the recipient, so nothing may hide
+// or fake part of it: control, format, surrogate and default-ignorable
+// characters are refused anywhere (a right-to-left override can make evil.io
+// read as corp.com; a Hangul filler shows as nothing), and a domain label may
+// not mix Latin, Cyrillic, Greek and Armenian, which share look-alike letters
+// (cоrp with a Cyrillic о). A label written in one script (münchen, пример) is
+// allowed; recipientLabel shows its punycode so a whole-script look-alike
+// (аррӏе) stands out.
+const HIDDEN_CHARACTER = /[\p{Cc}\p{Cf}\p{Cs}\p{Default_Ignorable_Code_Point}]/u;
+const LOOKALIKE_SCRIPTS = [
+ /\p{Script=Latin}/u,
+ /\p{Script=Cyrillic}/u,
+ /\p{Script=Greek}/u,
+ /\p{Script=Armenian}/u,
+];
+
+function mixesLookalikeScripts(label) {
+ return LOOKALIKE_SCRIPTS.filter((script) => script.test(label)).length > 1;
+}
+
+// The ASCII (punycode) form a mail server routes to, or null when the domain
+// has no valid one. The URL API applies the same IDNA mapping in main and in
+// the renderer.
+function asciiDomain(domain) {
+ try {
+ return new URL(`http://${domain}`).hostname;
+ } catch {
+ return null;
+ }
+}
+
+export function isValidEmailAddress(value) {
+ if (
+ typeof value !== "string" ||
+ value.length > 254 ||
+ !EMAIL_ADDRESS_PATTERN.test(value) ||
+ HIDDEN_CHARACTER.test(value)
+ ) {
+ return false;
+ }
+ const domain = value.split("@")[1];
+ return !domain.split(".").some(mixesLookalikeScripts) && asciiDomain(domain) !== null;
+}
+
+// How a recipient is shown to the user and the model: a non-ASCII domain also
+// gets the ASCII form it routes to.
+export function recipientLabel(address) {
+ const domain = address.slice(address.lastIndexOf("@") + 1);
+ const ascii = /[^\x00-\x7F]/.test(domain) ? asciiDomain(domain) : null;
+ return ascii ? `${address} (${ascii})` : address;
+}
+
+// Models often write "Josh Lee <[email protected]>"; only the address inside
+// the brackets is kept, so the name can't disguise it.
+const DISPLAY_NAME_FORM = /^[^<>]*<([^<>]*)>$/;
+
+// NFC, so a decomposed ü (u + combining diaeresis) is the same address as ü.
+export function bareEmailAddress(value) {
+ const trimmed = value.trim();
+ return (trimmed.match(DISPLAY_NAME_FORM)?.[1].trim() ?? trimmed).normalize("NFC");
+}
+
+function encodeAddresses(addresses) {
+ return addresses.map((address) => encodeURIComponent(address).replace(/%40/g, "@")).join(",");
+}
+
+function joinQuery(pairs) {
+ return pairs
+ .filter(([, value]) => value !== "")
+ .map(([key, value]) => `${key}=${value}`)
+ .join("&");
+}
+
+function buildUrl(target, { to, cc, subject, body }) {
+ const toList = encodeAddresses(to);
+ const ccList = cc.length > 0 ? encodeAddresses(cc) : "";
+
+ if (target === "mailto") {
+ // RFC 6068: line breaks in a mailto body are CRLF. A subject is one header
+ // line, and some mail apps would read a line break in it as a new header.
+ const encodedBody = body ? encodeURIComponent(body.replace(/\r\n|\r|\n/g, "\r\n")) : "";
+ const mailtoSubject = subject ? encodeURIComponent(subject.replace(/[\r\n]+/g, " ")) : "";
+ const query = joinQuery([
+ ["cc", ccList],
+ ["subject", mailtoSubject],
+ ["body", encodedBody],
+ ]);
+ return `mailto:${toList}${query ? `?${query}` : ""}`;
+ }
+
+ const encodedSubject = subject ? encodeURIComponent(subject) : "";
+ const encodedBody = body ? encodeURIComponent(body) : "";
+ if (target === "gmail") {
+ const query = joinQuery([
+ ["to", toList],
+ ["cc", ccList],
+ ["su", encodedSubject],
+ ["body", encodedBody],
+ ]);
+ return `${COMPOSE_BASES.gmail}&${query}`;
+ }
+
+ const query = joinQuery([
+ ["to", toList],
+ ["cc", ccList],
+ ["subject", encodedSubject],
+ ["body", encodedBody],
+ ]);
+ return `${COMPOSE_BASES[target]}?${query}`;
+}
+
+// Every returned URL fits the limit. What doesn't fit moves to the clipboard,
+// body first, then subject; recipients that alone don't fit are refused.
+export function buildComposeRequest({ target, to, cc = [], subject = "", body = "", platform }) {
+ if (!COMPOSE_TARGETS.includes(target)) throw new Error(`Unknown compose target: ${target}`);
+ // A lone surrogate (half an emoji from a model) would make encodeURIComponent throw.
+ subject = subject.toWellFormed();
+ body = body.toWellFormed();
+ const maxLength = maxComposeUrlLength(target, platform);
+ const fits = (url) => url.length <= maxLength;
+
+ const full = buildUrl(target, { to, cc, subject, body });
+ if (fits(full)) {
+ return { ok: true, url: full, clipboardText: null, subjectCopied: false, bodyCopied: false };
+ }
+
+ if (body) {
+ const withoutBody = buildUrl(target, { to, cc, subject, body: "" });
+ if (fits(withoutBody)) {
+ return {
+ ok: true,
+ url: withoutBody,
+ clipboardText: body,
+ subjectCopied: false,
+ bodyCopied: true,
+ };
+ }
+ }
+
+ const recipientsOnly = buildUrl(target, { to, cc, subject: "", body: "" });
+ if (!fits(recipientsOnly)) return { ok: false, reason: "too_long" };
+ const clipboardText = [subject, body].filter(Boolean).join("\n\n");
+ return {
+ ok: true,
+ url: recipientsOnly,
+ clipboardText: clipboardText || null,
+ subjectCopied: Boolean(subject),
+ bodyCopied: Boolean(body),
+ };
+}
diff --git a/src/helpers/connectors/emailConnector.js b/src/helpers/connectors/emailConnector.js
new file mode 100644
index 000000000..f780a9df5
--- /dev/null
+++ b/src/helpers/connectors/emailConnector.js
@@ -0,0 +1,128 @@
+const { execFile } = require("child_process");
+const {
+ buildComposeRequest,
+ isValidEmailAddress,
+ recipientLabel,
+ COMPOSE_TARGETS,
+} = require("./emailCompose");
+
+function stringList(value) {
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
+}
+
+// Electron hands a Linux mailto link to xdg-email without waiting for it, so
+// a missing mail app would still look like an opened draft. Only a clear "no
+// default" answer refuses: empty output, which KDE 5's xdg-mime pairs with
+// exit code 4. Any other failure lets the open go ahead and report itself.
+// Inside Flatpak the sandbox's MIME database is empty and the portal picks
+// the handler, so there is nothing to ask.
+function hasLinuxMailtoHandler({ execFile: run = execFile, env = process.env } = {}) {
+ if (env.FLATPAK_ID) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ run(
+ "xdg-mime",
+ ["query", "default", "x-scheme-handler/mailto"],
+ { timeout: 2000 },
+ (error, stdout) => {
+ const noDefault = stdout.trim() === "" && (!error || error.code === 4);
+ resolve(!noDefault);
+ }
+ );
+ });
+}
+
+// A compose window is the user's review step: they press Send in their own
+// mail client, so drafting needs no approval card.
+function createEmailConnector({
+ openExternal,
+ writeClipboard,
+ platform = process.platform,
+ hasMailtoHandler = hasLinuxMailtoHandler,
+}) {
+ return {
+ id: "email",
+ actions: { draft: { kind: "direct" } },
+
+ async getStatus() {
+ return { connected: true, accountLabel: null };
+ },
+
+ async getBinding() {
+ return null;
+ },
+
+ async runDirect(action, args, runtime) {
+ if (action !== "draft") {
+ return { state: "failed", errorCode: "unknown_action", message: "Unknown email action." };
+ }
+ const to = stringList(args.to);
+ const cc = stringList(args.cc);
+ // Failures carry it too, so the receipt says whose draft didn't open.
+ const destinationLabel = to.map(recipientLabel).join(", ");
+ const failed = (errorCode, message) => ({
+ state: "failed",
+ errorCode,
+ message,
+ destinationLabel,
+ });
+ if (to.length === 0 || [...to, ...cc].some((address) => !isValidEmailAddress(address))) {
+ return failed("invalid_address", "Every recipient must be a full email address.");
+ }
+ const target = COMPOSE_TARGETS.includes(args.target) ? args.target : "mailto";
+ const request = buildComposeRequest({
+ target,
+ to,
+ cc,
+ subject: typeof args.subject === "string" ? args.subject : "",
+ body: typeof args.body === "string" ? args.body : "",
+ platform,
+ });
+ if (!request.ok) {
+ return failed(
+ "draft_too_long",
+ "There are too many recipients for a draft link. Ask the user to add some of them in their email app."
+ );
+ }
+ // The renderer reserves the turn's one clipboard use before calling, so
+ // a draft it expected to fit its link can't replace another draft's text.
+ if (request.clipboardText !== null && args.clipboardReserved !== true) {
+ return failed("clipboard_unreserved", "This draft is too long for a link.");
+ }
+ if (target === "mailto" && platform === "linux" && !(await hasMailtoHandler())) {
+ return failed(
+ "open_failed",
+ "No email app is set up to open drafts. Ask the user to set a default email app, or to pick Gmail or Outlook for 'Draft emails in' under Integrations."
+ );
+ }
+
+ // A cancel (Esc) that landed during the checks above still stops it.
+ if (runtime.signal?.aborted) return { state: "not_sent", reason: "cancelled" };
+ try {
+ await openExternal(request.url);
+ } catch {
+ return failed("open_failed", "Couldn't open your email app.");
+ }
+ // Only after the OS took the link, so a failed open leaves the user's
+ // clipboard as it was.
+ let copied = false;
+ if (request.clipboardText !== null) {
+ try {
+ const written = await writeClipboard(request.clipboardText, runtime.webContents ?? null);
+ copied = written?.success !== false;
+ } catch {
+ // The draft is open without its text; the result says so.
+ }
+ }
+ // The compose URL carries the body, so it is never returned or logged.
+ return {
+ state: "sent",
+ destinationLabel,
+ bodyCopied: copied && request.bodyCopied,
+ subjectCopied: copied && request.subjectCopied,
+ copyFailed: request.clipboardText !== null && !copied,
+ };
+ },
+ };
+}
+
+module.exports = { createEmailConnector, hasLinuxMailtoHandler };
diff --git a/src/helpers/connectors/pendingActions.js b/src/helpers/connectors/pendingActions.js
new file mode 100644
index 000000000..dc3505737
--- /dev/null
+++ b/src/helpers/connectors/pendingActions.js
@@ -0,0 +1,107 @@
+const crypto = require("crypto");
+
+const PENDING_TTL_MS = 10 * 60 * 1000;
+
+// A pending action may only be sent under the connection it was prepared on:
+// a reconnect (generation bump) or another account must not inherit it.
+function bindingsMatch(a, b) {
+ return Boolean(
+ a &&
+ b &&
+ a.accountId === b.accountId &&
+ (a.workspaceId ?? null) === (b.workspaceId ?? null) &&
+ a.generation === b.generation
+ );
+}
+
+function createPendingActions({
+ now = Date.now,
+ randomId = () => crypto.randomBytes(16).toString("hex"),
+ ttlMs = PENDING_TTL_MS,
+} = {}) {
+ const actions = new Map();
+
+ function isExpired(entry) {
+ return now() - entry.createdAt > ttlMs;
+ }
+
+ function create({ connectorId, action, binding, accountId, payload, preview }) {
+ const actionId = randomId();
+ actions.set(actionId, {
+ actionId,
+ connectorId,
+ action,
+ binding,
+ accountId,
+ payload,
+ preview,
+ state: "pending",
+ createdAt: now(),
+ });
+ return actionId;
+ }
+
+ function get(actionId) {
+ const entry = actions.get(actionId);
+ return entry ? { ...entry } : null;
+ }
+
+ function beginCommit(actionId, currentBinding) {
+ const entry = actions.get(actionId);
+ if (!entry) return { ok: false, reason: "not_found" };
+ if (entry.state !== "pending") return { ok: false, reason: "not_pending" };
+ if (isExpired(entry)) {
+ actions.delete(actionId);
+ return { ok: false, reason: "expired" };
+ }
+ if (!bindingsMatch(entry.binding, currentBinding)) {
+ actions.delete(actionId);
+ return { ok: false, reason: "connection_changed" };
+ }
+ entry.state = "committing";
+ return { ok: true, entry: { ...entry } };
+ }
+
+ function finish(actionId) {
+ const entry = actions.get(actionId);
+ if (!entry || entry.state !== "committing") return false;
+ actions.delete(actionId);
+ return true;
+ }
+
+ // Only a pending action can be withdrawn; once committing, the send may
+ // already have reached the provider and its real outcome must be recorded.
+ function cancel(actionId) {
+ const entry = actions.get(actionId);
+ if (!entry || entry.state !== "pending") return false;
+ actions.delete(actionId);
+ return true;
+ }
+
+ function invalidateConnector(connectorId) {
+ const removed = [];
+ for (const [actionId, entry] of actions) {
+ if (entry.connectorId === connectorId && entry.state === "pending") {
+ actions.delete(actionId);
+ removed.push(actionId);
+ }
+ }
+ return removed;
+ }
+
+ // Committing actions are left alone: their real outcome is still coming.
+ function sweepExpired() {
+ const expired = [];
+ for (const [actionId, entry] of actions) {
+ if (entry.state === "pending" && isExpired(entry)) {
+ actions.delete(actionId);
+ expired.push(actionId);
+ }
+ }
+ return expired;
+ }
+
+ return { create, get, beginCommit, finish, cancel, invalidateConnector, sweepExpired };
+}
+
+module.exports = { createPendingActions, bindingsMatch, PENDING_TTL_MS };
diff --git a/src/helpers/database.js b/src/helpers/database.js
index ad1b42655..2cd130092 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -124,6 +124,12 @@ const SELECTED_CALENDAR_EVENT_FILTER = `(
))
)`;
+// A contacts row's source: "google:<account email>", "microsoft:<account
+// email>", "apple", or "manual" (added by hand to a note).
+function contactSource(provider, accountEmail = null) {
+ return accountEmail ? `${provider}:${accountEmail}` : provider;
+}
+
class DatabaseManager {
constructor() {
this.db = null;
@@ -496,6 +502,31 @@ class DatabaseManager {
} catch (err) {
if (!err.message.includes("duplicate column")) throw err;
}
+ // Receipts for agent connector actions. Never holds message content:
+ // destination labels, states and result links only.
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS connector_actions (
+ id TEXT PRIMARY KEY,
+ account_id TEXT,
+ connector TEXT NOT NULL,
+ action TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ destination_label TEXT,
+ state TEXT NOT NULL,
+ result_url TEXT,
+ error_code TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+ try {
+ this.db.exec("ALTER TABLE connector_actions ADD COLUMN account_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_connector_actions_connector ON connector_actions(connector, created_at)"
+ );
try {
this.db.exec("ALTER TABLE agent_conversations ADD COLUMN cloud_id TEXT");
} catch (err) {
@@ -640,6 +671,17 @@ class DatabaseManager {
)
`);
+ try {
+ this.db.exec("ALTER TABLE microsoft_calendar_tokens ADD COLUMN tenant_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE microsoft_calendar_tokens ADD COLUMN own_addresses TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS microsoft_calendars (
id TEXT PRIMARY KEY,
@@ -664,6 +706,18 @@ class DatabaseManager {
this.db.pragma("user_version = 2");
}
+ // One-time reset (user_version 3): older builds stored rooms without a
+ // resource flag, and incremental syncs never resend unchanged events; a
+ // forced full sync stores them flagged, purges the rooms those builds
+ // wrote to contacts and tags the contacts it sees with their source.
+ if (this.db.pragma("user_version", { simple: true }) < 3) {
+ this.db.exec("UPDATE google_calendars SET sync_token = NULL, sync_token_expires_at = NULL");
+ this.db.exec(
+ "UPDATE microsoft_calendars SET sync_token = NULL, sync_token_expires_at = NULL"
+ );
+ this.db.pragma("user_version = 3");
+ }
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS calendar_events (
id TEXT PRIMARY KEY,
@@ -764,6 +818,24 @@ class DatabaseManager {
)
`);
+ // Every source (see contactSource) that has seen a contact, so a
+ // disconnect only removes people no other source still has. Rows older
+ // builds stored have none.
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS contact_sources (
+ email TEXT NOT NULL REFERENCES contacts(email) ON DELETE CASCADE,
+ source TEXT NOT NULL,
+ PRIMARY KEY (email, source)
+ )
+ `);
+ // Pre-release builds kept a single source in contacts.source.
+ if (this.db.pragma("table_info(contacts)").some((column) => column.name === "source")) {
+ this.db.exec(
+ "INSERT OR IGNORE INTO contact_sources (email, source) SELECT email, source FROM contacts WHERE source IS NOT NULL"
+ );
+ this.db.exec("UPDATE contacts SET source = NULL WHERE source IS NOT NULL");
+ }
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS speaker_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -3301,6 +3373,7 @@ class DatabaseManager {
}
this.db.prepare("DELETE FROM analytics_events WHERE account_id = ?").run(accountId);
this.db.prepare("DELETE FROM analytics_clear_requests WHERE account_id = ?").run(accountId);
+ this.db.prepare("DELETE FROM connector_actions WHERE account_id = ?").run(accountId);
this.db.prepare("DELETE FROM space_accounts WHERE account_id = ?").run(accountId);
};
@@ -4448,6 +4521,7 @@ class DatabaseManager {
}
this.db.prepare("DELETE FROM google_calendars WHERE account_email = ?").run(email);
this.db.prepare("DELETE FROM google_calendar_tokens WHERE google_email = ?").run(email);
+ this._removeContactSources("source = ?", contactSource("google", email));
});
transaction();
return { success: true };
@@ -4726,6 +4800,184 @@ class DatabaseManager {
}
}
+ // accountId is the account the action ran under (resolved from its
+ // credential by the connector IPC), not this.activeAccountId, which lags a
+ // sign-in or account switch.
+ insertConnectorAction({
+ id,
+ accountId,
+ connector,
+ action,
+ kind,
+ destinationLabel = null,
+ state,
+ resultUrl = null,
+ errorCode = null,
+ }) {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare(
+ `INSERT INTO connector_actions
+ (id, account_id, connector, action, kind, destination_label, state, result_url, error_code)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ )
+ .run(id, accountId, connector, action, kind, destinationLabel, state, resultUrl, errorCode);
+ }
+
+ // With fromState, only a row still in that state moves, so a caller can tell
+ // a durable transition (1 row) from a missing or already-moved row (0).
+ updateConnectorActionState(
+ id,
+ { state, destinationLabel = null, resultUrl = null, errorCode = null },
+ fromState = null
+ ) {
+ if (!this.db) throw new Error("Database not initialized");
+ const guard = fromState === null ? "" : " AND state = ?";
+ const params = [
+ state,
+ destinationLabel,
+ resultUrl,
+ errorCode,
+ id,
+ ...(fromState === null ? [] : [fromState]),
+ ];
+ return this.db
+ .prepare(
+ `UPDATE connector_actions
+ SET state = ?,
+ destination_label = COALESCE(?, destination_label),
+ result_url = COALESCE(?, result_url),
+ error_code = COALESCE(?, error_code),
+ updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?${guard}`
+ )
+ .run(...params).changes;
+ }
+
+ // Receipts name the people a user wrote to, so only the account that took
+ // the action sees them.
+ listRecentConnectorActions(connector, limit, accountId) {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!accountId) return [];
+ return this.db
+ .prepare(
+ `SELECT id, connector, action, kind,
+ destination_label AS destinationLabel, state,
+ result_url AS resultUrl, error_code AS errorCode,
+ created_at AS createdAt
+ FROM connector_actions
+ WHERE connector = ? AND account_id = ?
+ ORDER BY created_at DESC, rowid DESC
+ LIMIT ?`
+ )
+ .all(connector, accountId, limit);
+ }
+
+ // A quit mid-send can't tell whether the provider acted, so committing rows
+ // become unknown; pending rows were never sent. Rows without an account
+ // (only pre-release builds wrote them) are listed to no one and no account
+ // deletion reaches them, so they are deleted.
+ reconcileInterruptedConnectorActions() {
+ if (!this.db) throw new Error("Database not initialized");
+ const unknown = this.db
+ .prepare(
+ "UPDATE connector_actions SET state = 'unknown', error_code = 'app_quit', updated_at = CURRENT_TIMESTAMP WHERE state = 'committing'"
+ )
+ .run().changes;
+ const cancelled = this.db
+ .prepare(
+ "UPDATE connector_actions SET state = 'cancelled', error_code = 'app_quit', updated_at = CURRENT_TIMESTAMP WHERE state = 'pending'"
+ )
+ .run().changes;
+ const orphaned = this.db
+ .prepare("DELETE FROM connector_actions WHERE account_id IS NULL")
+ .run().changes;
+ return { unknown, cancelled, orphaned };
+ }
+
+ // What find_contact searches. calendar_events only holds a sync window
+ // (about two days back to a month ahead), so the meetings nearest to now go
+ // first, and the contacts table (every synced attendee until its last
+ // source is disconnected) covers older ones, most recently seen first. Only
+ // the user's own meetings count: not cancelled or declined ones, not a
+ // colleague's shared Google calendar (whose people still come through
+ // contacts). Contacts come only from hand-added rows and connected
+ // accounts; rows older builds stored have no source and are left out.
+ // excludedEmails are the user's own addresses and every address a stored
+ // event flags as a room or resource.
+ getContactLookupSources(meetingLimit = 1000) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const meetings = this.db
+ .prepare(
+ `SELECT start_time, is_all_day, organizer_email, attendees
+ FROM calendar_events
+ WHERE (attendees IS NOT NULL OR organizer_email IS NOT NULL)
+ AND status IN ('confirmed', 'tentative')
+ AND self_response_status != 'declined'
+ AND ${SELECTED_CALENDAR_EVENT_FILTER}
+ AND (provider != 'google' OR EXISTS (
+ SELECT 1 FROM google_calendars
+ WHERE google_calendars.id = calendar_events.calendar_id
+ AND (google_calendars.is_primary = 1 OR google_calendars.id = google_calendars.account_email)
+ ))
+ ORDER BY ABS(julianday(start_time) - julianday('now')) IS NULL,
+ ABS(julianday(start_time) - julianday('now'))
+ LIMIT ?`
+ )
+ .all(meetingLimit);
+ const accounts = this.db
+ .prepare(
+ `SELECT 'google' AS provider, account_email FROM google_calendars
+ WHERE account_email IS NOT NULL
+ UNION
+ SELECT 'microsoft', account_email FROM microsoft_calendars
+ WHERE account_email IS NOT NULL`
+ )
+ .all();
+ const appleConnected = Boolean(this.db.prepare("SELECT 1 FROM apple_calendars").get());
+ const sources = [
+ contactSource("manual"),
+ ...(appleConnected ? [contactSource("apple")] : []),
+ ...accounts.map((row) => contactSource(row.provider, row.account_email)),
+ ];
+ const contacts = this.db
+ .prepare(
+ `SELECT email, display_name FROM contacts
+ WHERE email IN (
+ SELECT email FROM contact_sources
+ WHERE source IN (${sources.map(() => "?").join(", ")})
+ )
+ ORDER BY updated_at DESC`
+ )
+ .all(...sources);
+ const microsoftAliases = this.db
+ .prepare(
+ "SELECT own_addresses FROM microsoft_calendar_tokens WHERE own_addresses IS NOT NULL"
+ )
+ .all()
+ .flatMap((row) => JSON.parse(row.own_addresses));
+ const resources = this.db
+ .prepare(
+ `SELECT DISTINCT attendee.value ->> '$.email' AS email
+ FROM calendar_events, json_each(calendar_events.attendees) AS attendee
+ WHERE json_valid(calendar_events.attendees)
+ AND attendee.value ->> '$.resource' = 1`
+ )
+ .all()
+ .map((row) => row.email);
+ const excludedEmails = [
+ ...accounts.map((row) => row.account_email),
+ ...microsoftAliases,
+ ...resources,
+ ];
+ return { meetings, contacts, excludedEmails };
+ } catch (error) {
+ debugLogger.error("Error reading contact lookup sources", { error: error.message });
+ return { meetings: [], contacts: [], excludedEmails: [] };
+ }
+ }
+
getNoteByCalendarEventId(eventId, excludeNoteId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -4751,15 +5003,23 @@ class DatabaseManager {
}
}
- upsertContacts(contacts) {
+ // With a source (see contactSource), records that it has seen these
+ // contacts.
+ upsertContacts(contacts, source = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const transaction = this.db.transaction((list) => {
- const stmt = this.db.prepare(
+ const upsert = this.db.prepare(
"INSERT INTO contacts (email, display_name, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) ON CONFLICT(email) DO UPDATE SET display_name = COALESCE(excluded.display_name, contacts.display_name), updated_at = CURRENT_TIMESTAMP"
);
+ const addSource = this.db.prepare(
+ "INSERT OR IGNORE INTO contact_sources (email, source) VALUES (?, ?)"
+ );
for (const c of list) {
- if (c.email) stmt.run(c.email.toLowerCase().trim(), c.displayName || null);
+ if (!c.email) continue;
+ const email = c.email.toLowerCase().trim();
+ upsert.run(email, c.displayName || null);
+ if (source) addSource.run(email, source);
}
});
transaction(contacts);
@@ -4770,13 +5030,63 @@ class DatabaseManager {
}
}
+ // A note participant becomes a hand-added contact only when nothing stored
+ // it before: picking a synced contact from autocomplete leaves it to the
+ // accounts that synced it.
+ addManualContact(contact) {
+ if (!this.db) throw new Error("Database not initialized");
+ const email = contact.email?.toLowerCase().trim();
+ const isNew =
+ Boolean(email) && !this.db.prepare("SELECT 1 FROM contacts WHERE email = ?").get(email);
+ return this.upsertContacts([contact], isNew ? contactSource("manual") : null);
+ }
+
+ // Hand-added contacts stay, whatever a sync says about the address.
+ removeContacts(emails) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare(
+ "DELETE FROM contacts WHERE email = ? AND email NOT IN (SELECT email FROM contact_sources WHERE source = ?)"
+ );
+ const transaction = this.db.transaction((list) => {
+ for (const email of list) stmt.run(email.toLowerCase().trim(), contactSource("manual"));
+ });
+ transaction(emails);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error removing contacts", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ // Drops the matching sources and deletes the contacts no other source still
+ // has. Rows older builds stored have no sources and stay.
+ _removeContactSources(match, value) {
+ this.db
+ .prepare(
+ `DELETE FROM contacts
+ WHERE email IN (SELECT email FROM contact_sources WHERE ${match})
+ AND email NOT IN (SELECT email FROM contact_sources WHERE NOT (${match}))`
+ )
+ .run(value, value);
+ this.db.prepare(`DELETE FROM contact_sources WHERE ${match}`).run(value);
+ }
+
+ // A calendar sync's attendees. Rooms and the user's own addresses are
+ // deleted rather than stored: older builds stored them, and nothing else
+ // prunes this table.
+ syncCalendarContacts(provider, accountEmail, contacts, notContacts) {
+ if (contacts.length > 0) this.upsertContacts(contacts, contactSource(provider, accountEmail));
+ if (notContacts.length > 0) this.removeContacts(notContacts);
+ }
+
searchContacts(query) {
try {
if (!this.db) throw new Error("Database not initialized");
const pattern = `%${query || ""}%`;
return this.db
.prepare(
- "SELECT * FROM contacts WHERE email LIKE ? OR display_name LIKE ? ORDER BY display_name ASC, email ASC LIMIT 20"
+ "SELECT email, display_name, created_at, updated_at FROM contacts WHERE email LIKE ? OR display_name LIKE ? ORDER BY display_name ASC, email ASC LIMIT 20"
)
.all(pattern, pattern);
} catch (error) {
@@ -4792,6 +5102,7 @@ class DatabaseManager {
this.db.prepare("DELETE FROM calendar_events WHERE provider = 'google'").run();
this.db.prepare("DELETE FROM google_calendars").run();
this.db.prepare("DELETE FROM google_calendar_tokens").run();
+ this._removeContactSources("source LIKE ?", contactSource("google", "%"));
});
transaction();
return { success: true };
@@ -4885,13 +5196,14 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const stmt = this.db.prepare(
- `INSERT INTO microsoft_calendar_tokens (microsoft_email, access_token, refresh_token, expires_at, scope)
- VALUES (?, ?, ?, ?, ?)
+ `INSERT INTO microsoft_calendar_tokens (microsoft_email, access_token, refresh_token, expires_at, scope, tenant_id)
+ VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(microsoft_email) DO UPDATE SET
access_token = excluded.access_token,
refresh_token = excluded.refresh_token,
expires_at = excluded.expires_at,
scope = excluded.scope,
+ tenant_id = COALESCE(excluded.tenant_id, tenant_id),
updated_at = CURRENT_TIMESTAMP`
);
stmt.run(
@@ -4899,7 +5211,8 @@ class DatabaseManager {
tokens.access_token,
tokens.refresh_token,
tokens.expires_at,
- tokens.scope
+ tokens.scope,
+ tokens.tenant_id ?? null
);
return { success: true };
} catch (error) {
@@ -4931,7 +5244,7 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT microsoft_email AS email FROM microsoft_calendar_tokens ORDER BY created_at ASC"
+ "SELECT microsoft_email AS email, tenant_id AS tenantId FROM microsoft_calendar_tokens ORDER BY created_at ASC"
)
.all();
} catch (error) {
@@ -4940,6 +5253,26 @@ class DatabaseManager {
}
}
+ // The account's other addresses (primary SMTP address, aliases), which
+ // attendee lists use instead of the sign-in name.
+ saveMicrosoftOwnAddresses(email, addresses) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare("UPDATE microsoft_calendar_tokens SET own_addresses = ? WHERE microsoft_email = ?")
+ .run(JSON.stringify(addresses), email);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error saving Microsoft addresses", { error: error.message }, "mcal");
+ throw error;
+ }
+ }
+
+ getMicrosoftOwnAddresses(email) {
+ const row = this.getMicrosoftTokensByEmail(email);
+ return row?.own_addresses ? JSON.parse(row.own_addresses) : [];
+ }
+
removeMicrosoftAccount(email) {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -4960,6 +5293,7 @@ class DatabaseManager {
this.db
.prepare("DELETE FROM microsoft_calendar_tokens WHERE microsoft_email = ?")
.run(email);
+ this._removeContactSources("source = ?", contactSource("microsoft", email));
});
transaction();
return { success: true };
@@ -5048,6 +5382,7 @@ class DatabaseManager {
this.db.prepare("DELETE FROM calendar_events WHERE provider = 'microsoft'").run();
this.db.prepare("DELETE FROM microsoft_calendars").run();
this.db.prepare("DELETE FROM microsoft_calendar_tokens").run();
+ this._removeContactSources("source LIKE ?", contactSource("microsoft", "%"));
});
transaction();
return { success: true };
@@ -5138,6 +5473,7 @@ class DatabaseManager {
const transaction = this.db.transaction(() => {
this.db.prepare("DELETE FROM calendar_events WHERE provider = 'apple'").run();
this.db.prepare("DELETE FROM apple_calendars").run();
+ this._removeContactSources("source = ?", contactSource("apple"));
});
transaction();
return { success: true };
diff --git a/src/helpers/googleCalendarManager.js b/src/helpers/googleCalendarManager.js
index 01d6cb398..c21ace573 100644
--- a/src/helpers/googleCalendarManager.js
+++ b/src/helpers/googleCalendarManager.js
@@ -231,6 +231,11 @@ class GoogleCalendarManager {
const toUpsert = [];
const toRemove = [];
const contactsToUpsert = [];
+ const notContacts = [];
+ const ownEmail = (accountEmail || "").toLowerCase();
+ // Google's self flag marks the calendar's owner: the user (possibly under
+ // an alias) on their primary calendar, a colleague on a shared one.
+ const selfIsUser = Boolean(calendar.is_primary) || calendar.id === accountEmail;
for (const item of allItems) {
if (item.status === "cancelled") {
@@ -264,6 +269,7 @@ class GoogleCalendarManager {
displayName: a.displayName || null,
responseStatus: a.responseStatus || null,
self: a.self || false,
+ ...(a.resource ? { resource: true } : {}),
}))
)
: null,
@@ -271,8 +277,11 @@ class GoogleCalendarManager {
if (item.attendees) {
for (const a of item.attendees) {
- if (a.email)
- contactsToUpsert.push({ email: a.email, displayName: a.displayName || null });
+ if (!a.email) continue;
+ // Rooms and the user's own addresses aren't people to write to.
+ const isUser = a.email.toLowerCase() === ownEmail || (a.self && selfIsUser);
+ if (a.resource || isUser) notContacts.push(a.email);
+ else contactsToUpsert.push({ email: a.email, displayName: a.displayName || null });
}
}
}
@@ -292,7 +301,12 @@ class GoogleCalendarManager {
if (nextSyncToken) {
this.databaseManager.updateCalendarSyncToken(calendar.id, nextSyncToken, tokenExpiresAt);
}
- if (contactsToUpsert.length > 0) this.databaseManager.upsertContacts(contactsToUpsert);
+ this.databaseManager.syncCalendarContacts(
+ "google",
+ accountEmail,
+ contactsToUpsert,
+ notContacts
+ );
}
onWakeFromSleep() {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 45bc3d0d3..20dc6df10 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -33,6 +33,11 @@ const {
} = require("./policyResponseError");
const { classifyAndLog } = require("./networkErrors");
const { resolveSystemDefaultMicrophone } = require("./systemDefaultMicrophone");
+const {
+ registerConnectorIpc,
+ createConnectorPolicyResolver,
+} = require("./connectors/connectorIpc");
+const { searchContacts } = require("./connectors/contactSearch");
// The renderer's ModelRegistry is not main-loadable; the raw registry data is
// packaged, and the route resolver only needs {id, baseUrl} per provider.
const transcriptionProviderBaseUrls = () =>
@@ -609,6 +614,7 @@ class IPCHandlers {
this.whisperCudaManager = managers.whisperCudaManager;
this.whisperVulkanManager = managers.whisperVulkanManager;
this.googleCalendarManager = managers.googleCalendarManager;
+ this.connectorManager = managers.connectorManager;
this.microsoftCalendarManager = managers.microsoftCalendarManager;
this.appleCalendarManager = managers.appleCalendarManager;
this.meetingDetectionEngine = managers.meetingDetectionEngine;
@@ -6046,6 +6052,28 @@ class IPCHandlers {
broadcast: (snapshot) => broadcastToWindows("workspace-policy-changed", snapshot),
logger: debugLogger,
});
+ if (this.connectorManager) {
+ registerConnectorIpc({
+ ipcMain,
+ manager: this.connectorManager,
+ getPolicyState: createConnectorPolicyResolver({
+ getAuthHeader,
+ getPolicy: (options) => workspacePolicyManager.getPolicy(options),
+ peekPolicy: (options) => workspacePolicyManager.peekPolicy(options),
+ getAuthGeneration: () => tokenStore.getState().generation,
+ }),
+ // The account bound to the credential in use, the same binding
+ // get-active-account-scope serves (not the separately synced
+ // database scope, which lags a sign-in or account switch).
+ getAccountScope: () =>
+ accountScopeBinding.resolveActiveAccountScope({
+ ...tokenStore.getState(),
+ binding: accountScopeBinding.read(),
+ }),
+ findContacts: (query) =>
+ searchContacts(this.databaseManager.getContactLookupSources(), query),
+ });
+ }
this.enterpriseIdentityManager = createEnterpriseIdentityManager({
cachePath: path.join(app.getPath("userData"), "managed-enterprise-config.json"),
getApiUrl,
@@ -11535,7 +11563,7 @@ class IPCHandlers {
ipcMain.handle("upsert-contact", async (_event, contact) => {
try {
- this.databaseManager.upsertContacts([contact]);
+ this.databaseManager.addManualContact(contact);
return { success: true };
} catch (error) {
return { success: false };
diff --git a/src/helpers/microsoftCalendarManager.js b/src/helpers/microsoftCalendarManager.js
index ff8031f08..6b77eaf92 100644
--- a/src/helpers/microsoftCalendarManager.js
+++ b/src/helpers/microsoftCalendarManager.js
@@ -165,6 +165,7 @@ class MicrosoftCalendarManager {
} catch (err) {
debugLogger.error("Error fetching calendars", { email, error: err.message }, "mcal");
}
+ await this._refreshOwnAddresses(email);
}
this.databaseManager.applyMicrosoftPrimaryOnlyToSelection(this.primaryOnly);
@@ -237,6 +238,11 @@ class MicrosoftCalendarManager {
const toUpsert = [];
const contactsToUpsert = [];
+ const notContacts = [];
+ const ownAddresses = new Set([
+ (accountEmail || "").toLowerCase(),
+ ...this.databaseManager.getMicrosoftOwnAddresses(accountEmail),
+ ]);
for (const item of events) {
// An occurrence still stripped after backfill (master fetch failed) has no
// subject, attendees, or join link. Overwriting a row a previous sync
@@ -247,11 +253,13 @@ class MicrosoftCalendarManager {
}
toUpsert.push(this._mapEvent(item, calendar));
for (const a of item.attendees || []) {
- if (a.emailAddress?.address) {
- contactsToUpsert.push({
- email: a.emailAddress.address,
- displayName: a.emailAddress.name || null,
- });
+ const address = a.emailAddress?.address;
+ if (!address) continue;
+ // Rooms and the user's own addresses aren't people to write to.
+ if (a.type === "resource" || ownAddresses.has(address.toLowerCase())) {
+ notContacts.push(address);
+ } else {
+ contactsToUpsert.push({ email: address, displayName: a.emailAddress.name || null });
}
}
}
@@ -271,7 +279,12 @@ class MicrosoftCalendarManager {
if (deltaLink) {
this.databaseManager.updateMicrosoftCalendarSyncToken(calendar.id, deltaLink, tokenExpiresAt);
}
- if (contactsToUpsert.length > 0) this.databaseManager.upsertContacts(contactsToUpsert);
+ this.databaseManager.syncCalendarContacts(
+ "microsoft",
+ accountEmail,
+ contactsToUpsert,
+ notContacts
+ );
}
// Merges each stripped occurrence with its series master (fetched once per
@@ -337,6 +350,7 @@ class MicrosoftCalendarManager {
displayName: a.emailAddress?.name || null,
responseStatus: RESPONSE_STATUS_BY_GRAPH[a.status?.response] || "needsAction",
self: (a.emailAddress?.address || "").toLowerCase() === accountEmail,
+ ...(a.type === "resource" ? { resource: true } : {}),
}))
)
: null,
@@ -378,6 +392,30 @@ class MicrosoftCalendarManager {
return Array.from(this.accounts.keys());
}
+ // Attendee lists address the user by their primary SMTP address or an
+ // alias, which can differ from the sign-in name the account is stored under.
+ async _refreshOwnAddresses(email) {
+ try {
+ const me = await this._apiGet("/me?$select=mail,userPrincipalName,proxyAddresses", email);
+ const aliases = (me.proxyAddresses || [])
+ .filter((entry) => /^smtp:/i.test(entry))
+ .map((entry) => entry.slice("smtp:".length));
+ const addresses = [me.mail, me.userPrincipalName, ...aliases]
+ .filter((address) => typeof address === "string" && address.includes("@"))
+ .map((address) => address.toLowerCase());
+ const ownAddresses = [...new Set(addresses)];
+ this.databaseManager.saveMicrosoftOwnAddresses(email, ownAddresses);
+ // Syncs before this lookup may have stored an alias as a contact.
+ this.databaseManager.removeContacts(ownAddresses);
+ } catch (err) {
+ debugLogger.warn(
+ "Error fetching Microsoft account addresses",
+ { email, error: err.message },
+ "mcal"
+ );
+ }
+ }
+
// calendarView/delta expands recurrences into occurrences and returns a
// deltaLink for incremental syncs (stored in microsoft_calendars.sync_token).
_deltaUrl(calendarId) {
diff --git a/src/helpers/microsoftCalendarOAuth.js b/src/helpers/microsoftCalendarOAuth.js
index 7f808e18c..149ab3c04 100644
--- a/src/helpers/microsoftCalendarOAuth.js
+++ b/src/helpers/microsoftCalendarOAuth.js
@@ -10,6 +10,21 @@ const MICROSOFT_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.
const CALENDAR_SCOPE =
"openid profile email offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Calendars.Read";
+function decodeIdToken(idToken) {
+ if (!idToken) return null;
+ try {
+ return JSON.parse(Buffer.from(idToken.split(".")[1], "base64url").toString());
+ } catch {
+ return null;
+ }
+}
+
+// The Entra tenant tells a personal Microsoft account from a work or school
+// one, whatever the address's domain.
+function tenantIdOf(tokenData) {
+ return decodeIdToken(tokenData.id_token)?.tid ?? null;
+}
+
class MicrosoftCalendarOAuth {
constructor(databaseManager) {
this.databaseManager = databaseManager;
@@ -62,7 +77,7 @@ class MicrosoftCalendarOAuth {
}
this._saveTokens(email, tokenData);
- return { success: true, email };
+ return { success: true, email, tenantId: tenantIdOf(tokenData) };
},
});
}
@@ -135,21 +150,16 @@ class MicrosoftCalendarOAuth {
refresh_token: tokenData.refresh_token,
expires_at: Date.now() + tokenData.expires_in * 1000,
scope: tokenData.scope || CALENDAR_SCOPE,
+ tenant_id: tenantIdOf(tokenData),
});
}
// Work accounts often omit the id_token "email" claim; fall back to
// preferred_username, then Graph /me.
async _resolveEmail(tokenData) {
- if (tokenData.id_token) {
- try {
- const payload = JSON.parse(
- Buffer.from(tokenData.id_token.split(".")[1], "base64url").toString()
- );
- if (payload.email) return payload.email;
- if (payload.preferred_username?.includes("@")) return payload.preferred_username;
- } catch {}
- }
+ const payload = decodeIdToken(tokenData.id_token);
+ if (payload?.email) return payload.email;
+ if (payload?.preferred_username?.includes("@")) return payload.preferred_username;
try {
const response = await net.fetch("https://graph.microsoft.com/v1.0/me", {
diff --git a/src/helpers/policyValidation.js b/src/helpers/policyValidation.js
index 7f71461f0..6a4230d96 100644
--- a/src/helpers/policyValidation.js
+++ b/src/helpers/policyValidation.js
@@ -57,6 +57,8 @@ function isValidPolicyShape(policy) {
// Additive within policy version 1: absent (older server) means allowed.
(policy.features?.screenContextEnabled === undefined ||
typeof policy.features.screenContextEnabled === "boolean") &&
+ (policy.features?.connectorsEnabled === undefined ||
+ typeof policy.features.connectorsEnabled === "boolean") &&
SHARING_MODES.includes(policy.sharing?.externalLinkSharing) &&
LOCAL_HISTORY_MODES.includes(policy.dataRetention?.localHistoryMode) &&
typeof policy.dataRetention?.cloudBackupAllowed === "boolean" &&
diff --git a/src/helpers/workspacePolicyManager.js b/src/helpers/workspacePolicyManager.js
index 9eea6b78b..862526560 100644
--- a/src/helpers/workspacePolicyManager.js
+++ b/src/helpers/workspacePolicyManager.js
@@ -387,7 +387,23 @@ function createWorkspacePolicyManager({
return pending;
}
- return { getPolicy };
+ // The verdict already held in memory for this identity, without a refresh,
+ // for callers with a hard deadline whose refresh is taking too long.
+ function peekPolicy(request) {
+ let identity;
+ try {
+ identity = captureIdentity(request ?? {});
+ } catch {
+ return null;
+ }
+ const current = snapshots.get(identityKey(identity));
+ if (!current || (current.data.managed === false && requiresManagedPolicy(identity))) {
+ return null;
+ }
+ return publicSnapshot(identity, current.data, "cached", current.revision);
+ }
+
+ return { getPolicy, peekPolicy };
}
// Main-process capture gate: block an explicit managed denial or an
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index 07194c91a..4736eeebe 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -650,6 +650,7 @@
"connectFailedDescription": "حدث خطأ ما أثناء الاتصال بتطبيق Calendar.app. يرجى إعادة تشغيل OpenWhispr والمحاولة مرة أخرى."
},
"sections": {
+ "connectors": "الموصلات",
"calendar": "التقويم (Calendar)",
"api": "API",
"mcp": "MCP",
@@ -710,6 +711,80 @@
"description": "يلتقط OpenWhispr الصوت مباشرة من نظامك — فهو لا ينضم أبدًا إلى اجتماعاتك كمشارك. ما عليك سوى ربط التقويم الخاص بك وتدوين الملاحظات كالمعتاد."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "إرسال إلى {{destination}}"
+ },
+ "identity": "بصفتك {{account}}",
+ "identityWithWorkspace": "بصفتك {{account}} في {{workspace}}",
+ "send": "إرسال",
+ "edit": "تعديل",
+ "doneEditing": "تم التعديل",
+ "cancel": "إلغاء",
+ "titleLabel": "العنوان",
+ "bodyLabel": "الرسالة",
+ "sending": "جارٍ الإرسال…",
+ "sent": "تم الإرسال إلى {{destination}}.",
+ "open": "فتح",
+ "failed": "تعذّر الإرسال: {{message}}",
+ "unknown": "تعذّر تأكيد الإرسال. تحقق من {{destination}}.",
+ "cancelled": "تم الإلغاء. لم يتم إرسال شيء.",
+ "notSent": "لم يُرسل."
+ },
+ "policyOff": "أوقفت مؤسستك تشغيل الموصلات.",
+ "email": {
+ "title": "مسودات البريد الإلكتروني",
+ "description": "يفتح المساعد مسودة معبأة مسبقًا في تطبيق البريد الإلكتروني الخاص بك. راجعها واضغط إرسال بنفسك.",
+ "proRequired": "قم بالترقية إلى خطة مدفوعة ليكتب المساعد مسودات رسائلك الإلكترونية.",
+ "unavailable": "مسودات البريد الإلكتروني غير متاحة حاليًا.",
+ "targetLabel": "صياغة رسائل البريد الإلكتروني في",
+ "autoResolved": "تلقائي · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (العمل أو المدرسة)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "تطبيق البريد الافتراضي"
+ }
+ },
+ "recent": {
+ "title": "الإجراءات الأخيرة",
+ "actions": {
+ "email_draft": "مسودة إلى {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "مسودة بريد إلكتروني"
+ },
+ "states": {
+ "pending": "قيد الانتظار",
+ "committing": "قيد التنفيذ",
+ "sent": "تم",
+ "failed": "فشل",
+ "unknown": "لم يتم التأكيد",
+ "cancelled": "أُلغي",
+ "expired": "منتهي الصلاحية"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "فُتحت مسودة إلى {{destination}}.",
+ "draftOpenedBodyCopied": "فُتحت مسودة إلى {{destination}}. نص الرسالة في الحافظة.",
+ "draftOpenedSubjectCopied": "فُتحت مسودة إلى {{destination}}. الموضوع ونص الرسالة في الحافظة.",
+ "draftOpenedOnlySubjectCopied": "تم فتح مسودة إلى {{destination}}. الموضوع موجود في الحافظة.",
+ "needsDetails": "يلزم مزيد من التفاصيل.",
+ "unavailable": "الموصلات غير متاحة حاليًا.",
+ "failed": "لم ينجح ذلك.",
+ "unknown": "لم يتم التأكيد. تحقق مما إذا كان الإجراء قد تم قبل المحاولة مرة أخرى.",
+ "draftUnknown": "لم يتم التأكيد: ربما لم تُفتح المسودة إلى {{destination}}. تحقق قبل المحاولة مرة أخرى.",
+ "contactsFound": "جهات الاتصال التي عُثر عليها: {{total}}",
+ "draftLimit": "يمكن فتح {{count}} مسودات فقط لكل طلب.",
+ "clipboardBusy": "لم تُفتح: نص مسودة أخرى لا يزال في الحافظة.",
+ "errors": {
+ "open_failed": "تعذّر فتح تطبيق البريد الإلكتروني.",
+ "draft_too_long": "عدد المستلمين كبير جدًا لرابط المسودة.",
+ "invalid_address": "يلزم إدخال عناوين بريد إلكتروني كاملة."
+ }
+ }
+ },
"auth": {
"cloudNotConfigured": "السحابة غير مهيأة",
"common": {
@@ -1248,6 +1323,8 @@
},
"tools": {
"search_notesName": "البحث في الملاحظات",
+ "email_draftName": "مسودة بريد إلكتروني",
+ "find_contactName": "البحث عن جهة اتصال",
"get_noteName": "الحصول على الملاحظة",
"create_noteName": "إنشاء ملاحظة",
"update_noteName": "تحديث الملاحظة",
@@ -1260,6 +1337,8 @@
"update_dictionaryName": "تحديث القاموس",
"update_snippetsName": "تحديث المقتطفات",
"search_notesStatus": "جاري البحث في الملاحظات...",
+ "email_draftStatus": "جارٍ فتح مسودة بريد إلكتروني...",
+ "find_contactStatus": "جارٍ البحث عن جهات الاتصال...",
"web_searchStatus": "جاري البحث في الويب...",
"copy_to_clipboardStatus": "جاري النسخ إلى الحافظة...",
"get_calendar_eventsStatus": "جاري التحقق من التقويم...",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index cc388791f..2133c0bbc 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3848,6 +3848,8 @@
},
"tools": {
"search_notesName": "Notizen durchsuchen",
+ "email_draftName": "E-Mail-Entwurf",
+ "find_contactName": "Kontakt suchen",
"get_noteName": "Notiz abrufen",
"create_noteName": "Notiz erstellen",
"update_noteName": "Notiz aktualisieren",
@@ -3860,6 +3862,8 @@
"update_dictionaryName": "Wörterbuch aktualisieren",
"update_snippetsName": "Snippets aktualisieren",
"search_notesStatus": "Notizen werden durchsucht...",
+ "email_draftStatus": "E-Mail-Entwurf wird geöffnet...",
+ "find_contactStatus": "Kontakte werden gesucht...",
"web_searchStatus": "Websuche...",
"copy_to_clipboardStatus": "In Zwischenablage kopieren...",
"get_calendar_eventsStatus": "Kalender wird geprüft...",
@@ -3951,6 +3955,7 @@
"connectFailedDescription": "Beim Verbinden mit Calendar.app ist ein Fehler aufgetreten. Starte OpenWhispr neu und versuche es erneut."
},
"sections": {
+ "connectors": "Konnektoren",
"calendar": "Kalender",
"api": "API",
"mcp": "MCP",
@@ -4011,6 +4016,80 @@
"description": "OpenWhispr erfasst Audio direkt von deinem System — es nimmt niemals als Teilnehmer an deinen Meetings teil. Verbinde einfach deinen Kalender und mach Notizen wie gewohnt."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "An {{destination}} senden"
+ },
+ "identity": "Als {{account}}",
+ "identityWithWorkspace": "Als {{account}} in {{workspace}}",
+ "send": "Senden",
+ "edit": "Bearbeiten",
+ "doneEditing": "Bearbeitung fertig",
+ "cancel": "Abbrechen",
+ "titleLabel": "Titel",
+ "bodyLabel": "Nachricht",
+ "sending": "Wird gesendet…",
+ "sent": "An {{destination}} gesendet.",
+ "open": "Öffnen",
+ "failed": "Senden fehlgeschlagen: {{message}}",
+ "unknown": "Konnte nicht bestätigt werden. Bitte {{destination}} prüfen.",
+ "cancelled": "Abgebrochen. Es wurde nichts gesendet.",
+ "notSent": "Nicht gesendet."
+ },
+ "policyOff": "Konnektoren wurden von deiner Organisation deaktiviert.",
+ "email": {
+ "title": "E-Mail-Entwürfe",
+ "description": "Der Assistent öffnet einen vorausgefüllten Entwurf in deiner E-Mail-App. Du prüfst ihn und klickst selbst auf Senden.",
+ "proRequired": "Upgrade auf einen kostenpflichtigen Plan, damit der Assistent E-Mails für dich entwirft.",
+ "unavailable": "E-Mail-Entwürfe sind gerade nicht verfügbar.",
+ "targetLabel": "E-Mails entwerfen in",
+ "autoResolved": "Automatisch · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (geschäftlich oder Schule)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Standard-E-Mail-App"
+ }
+ },
+ "recent": {
+ "title": "Letzte Aktionen",
+ "actions": {
+ "email_draft": "Entwurf an {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "E-Mail-Entwurf"
+ },
+ "states": {
+ "pending": "Wartet",
+ "committing": "Läuft",
+ "sent": "Erledigt",
+ "failed": "Fehlgeschlagen",
+ "unknown": "Nicht bestätigt",
+ "cancelled": "Abgebrochen",
+ "expired": "Abgelaufen"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Entwurf an {{destination}} geöffnet.",
+ "draftOpenedBodyCopied": "Entwurf an {{destination}} geöffnet. Der Text ist in deiner Zwischenablage.",
+ "draftOpenedSubjectCopied": "Entwurf an {{destination}} geöffnet. Betreff und Text sind in deiner Zwischenablage.",
+ "draftOpenedOnlySubjectCopied": "Entwurf an {{destination}} geöffnet. Der Betreff ist in deiner Zwischenablage.",
+ "needsDetails": "Es fehlen Angaben.",
+ "unavailable": "Konnektoren sind gerade nicht verfügbar.",
+ "failed": "Das hat nicht funktioniert.",
+ "unknown": "Nicht bestätigt. Prüfe, ob es geklappt hat, bevor du es erneut versuchst.",
+ "draftUnknown": "Nicht bestätigt: Der Entwurf an {{destination}} wurde möglicherweise nicht geöffnet. Prüfe das, bevor du es erneut versuchst.",
+ "contactsFound": "Gefundene Kontakte: {{total}}",
+ "draftLimit": "Pro Anfrage können nur {{count}} Entwürfe geöffnet werden.",
+ "clipboardBusy": "Nicht geöffnet: Der Text eines anderen Entwurfs ist noch in deiner Zwischenablage.",
+ "errors": {
+ "open_failed": "Deine E-Mail-App konnte nicht geöffnet werden.",
+ "draft_too_long": "Zu viele Empfänger für einen Entwurfslink.",
+ "invalid_address": "Vollständige E-Mail-Adressen erforderlich."
+ }
+ }
+ },
"notesView": {
"searchPlaceholder": "Notizen durchsuchen…",
"newNote": "Neue Notiz",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 2c766d143..666f2f677 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3848,6 +3848,8 @@
},
"tools": {
"search_notesName": "Search notes",
+ "email_draftName": "Email draft",
+ "find_contactName": "Find contact",
"get_noteName": "Get note",
"create_noteName": "Create note",
"update_noteName": "Update note",
@@ -3860,6 +3862,8 @@
"update_dictionaryName": "Update dictionary",
"update_snippetsName": "Update snippets",
"search_notesStatus": "Searching notes...",
+ "email_draftStatus": "Opening an email draft...",
+ "find_contactStatus": "Looking up contacts...",
"web_searchStatus": "Searching the web...",
"copy_to_clipboardStatus": "Copying to clipboard...",
"get_calendar_eventsStatus": "Checking calendar...",
@@ -3951,6 +3955,7 @@
"connectFailedDescription": "Something went wrong while connecting to Calendar.app. Please restart OpenWhispr and try again."
},
"sections": {
+ "connectors": "Connectors",
"calendar": "Calendar",
"api": "API",
"mcp": "MCP",
@@ -4011,6 +4016,80 @@
"description": "OpenWhispr captures audio directly from your system — it never joins your meetings as a participant. Just connect your calendar and take notes as normal."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Send to {{destination}}"
+ },
+ "identity": "As {{account}}",
+ "identityWithWorkspace": "As {{account}} in {{workspace}}",
+ "send": "Send",
+ "edit": "Edit",
+ "doneEditing": "Done editing",
+ "cancel": "Cancel",
+ "titleLabel": "Title",
+ "bodyLabel": "Message",
+ "sending": "Sending…",
+ "sent": "Sent to {{destination}}.",
+ "open": "Open",
+ "failed": "Couldn't send: {{message}}",
+ "unknown": "Couldn't confirm it was sent. Check {{destination}}.",
+ "cancelled": "Cancelled. Nothing was sent.",
+ "notSent": "Not sent."
+ },
+ "policyOff": "Connectors are turned off by your organization.",
+ "email": {
+ "title": "Email drafts",
+ "description": "The assistant opens a pre-filled draft in your email app. You review it and press Send yourself.",
+ "proRequired": "Upgrade to a paid plan to let the assistant draft emails for you.",
+ "unavailable": "Email drafts aren't available right now.",
+ "targetLabel": "Draft emails in",
+ "autoResolved": "Automatic · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (work or school)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Default mail app"
+ }
+ },
+ "recent": {
+ "title": "Recent actions",
+ "actions": {
+ "email_draft": "Draft to {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Email draft"
+ },
+ "states": {
+ "pending": "Waiting",
+ "committing": "In progress",
+ "sent": "Done",
+ "failed": "Failed",
+ "unknown": "Not confirmed",
+ "cancelled": "Cancelled",
+ "expired": "Expired"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Opened a draft to {{destination}}.",
+ "draftOpenedBodyCopied": "Opened a draft to {{destination}}. The body is on your clipboard.",
+ "draftOpenedSubjectCopied": "Opened a draft to {{destination}}. The subject and body are on your clipboard.",
+ "draftOpenedOnlySubjectCopied": "Opened a draft to {{destination}}. The subject is on your clipboard.",
+ "needsDetails": "Needs more details.",
+ "unavailable": "Connectors aren't available right now.",
+ "failed": "That didn't work.",
+ "unknown": "Not confirmed. Check whether it went through before trying again.",
+ "draftUnknown": "Not confirmed: the draft to {{destination}} may not have opened. Check before trying again.",
+ "contactsFound": "Contacts found: {{total}}",
+ "draftLimit": "Only {{count}} drafts can open per request.",
+ "clipboardBusy": "Not opened: another draft's text is still on your clipboard.",
+ "errors": {
+ "open_failed": "Couldn't open your email app.",
+ "draft_too_long": "Too many recipients for a draft link.",
+ "invalid_address": "Needs full email addresses."
+ }
+ }
+ },
"notesView": {
"searchPlaceholder": "Search notes…",
"newNote": "New Note",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 2c7aa4839..ad5bf16e2 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -3732,6 +3732,8 @@
},
"tools": {
"search_notesName": "Buscar notas",
+ "email_draftName": "Borrador de correo",
+ "find_contactName": "Buscar contacto",
"get_noteName": "Obtener nota",
"create_noteName": "Crear nota",
"update_noteName": "Actualizar nota",
@@ -3744,6 +3746,8 @@
"update_dictionaryName": "Actualizar diccionario",
"update_snippetsName": "Actualizar snippets",
"search_notesStatus": "Buscando notas...",
+ "email_draftStatus": "Abriendo un borrador de correo...",
+ "find_contactStatus": "Buscando contactos...",
"web_searchStatus": "Buscando en la web...",
"copy_to_clipboardStatus": "Copiando al portapapeles...",
"get_calendar_eventsStatus": "Consultando calendario...",
@@ -3835,6 +3839,7 @@
"connectFailedDescription": "Se produjo un error al conectar con Calendar.app. Reinicia OpenWhispr e inténtalo de nuevo."
},
"sections": {
+ "connectors": "Conectores",
"calendar": "Calendario",
"api": "API",
"mcp": "MCP",
@@ -3895,6 +3900,80 @@
"description": "OpenWhispr captura el audio directamente de tu sistema — nunca se une a tus reuniones como participante. Solo conecta tu calendario y toma notas con normalidad."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Enviar a {{destination}}"
+ },
+ "identity": "Como {{account}}",
+ "identityWithWorkspace": "Como {{account}} en {{workspace}}",
+ "send": "Enviar",
+ "edit": "Editar",
+ "doneEditing": "Edición terminada",
+ "cancel": "Cancelar",
+ "titleLabel": "Título",
+ "bodyLabel": "Mensaje",
+ "sending": "Enviando…",
+ "sent": "Enviado a {{destination}}.",
+ "open": "Abrir",
+ "failed": "No se pudo enviar: {{message}}",
+ "unknown": "No se pudo confirmar el envío. Verifica {{destination}}.",
+ "cancelled": "Cancelado. No se envió nada.",
+ "notSent": "No enviado."
+ },
+ "policyOff": "Tu organización ha desactivado los conectores.",
+ "email": {
+ "title": "Borradores de correo",
+ "description": "El asistente abre un borrador prellenado en tu aplicación de correo. Tú lo revisas y pulsas Enviar.",
+ "proRequired": "Actualiza a un plan de pago para que el asistente redacte correos por ti.",
+ "unavailable": "Los borradores de correo no están disponibles en este momento.",
+ "targetLabel": "Redactar correos en",
+ "autoResolved": "Automático · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (trabajo o escuela)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Aplicación de correo predeterminada"
+ }
+ },
+ "recent": {
+ "title": "Acciones recientes",
+ "actions": {
+ "email_draft": "Borrador a {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Borrador de correo"
+ },
+ "states": {
+ "pending": "Esperando",
+ "committing": "En curso",
+ "sent": "Listo",
+ "failed": "Fallido",
+ "unknown": "Sin confirmar",
+ "cancelled": "Cancelado",
+ "expired": "Caducado"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Se abrió un borrador para {{destination}}.",
+ "draftOpenedBodyCopied": "Se abrió un borrador para {{destination}}. El cuerpo está en tu portapapeles.",
+ "draftOpenedSubjectCopied": "Se abrió un borrador para {{destination}}. El asunto y el cuerpo están en tu portapapeles.",
+ "draftOpenedOnlySubjectCopied": "Se abrió un borrador para {{destination}}. El asunto está en tu portapapeles.",
+ "needsDetails": "Faltan detalles.",
+ "unavailable": "Los conectores no están disponibles en este momento.",
+ "failed": "No funcionó.",
+ "unknown": "Sin confirmar. Comprueba si se completó antes de volver a intentarlo.",
+ "draftUnknown": "Sin confirmar: puede que el borrador para {{destination}} no se haya abierto. Compruébalo antes de volver a intentarlo.",
+ "contactsFound": "Contactos encontrados: {{total}}",
+ "draftLimit": "Solo se pueden abrir {{count}} borradores por solicitud.",
+ "clipboardBusy": "No se abrió: el texto de otro borrador sigue en tu portapapeles.",
+ "errors": {
+ "open_failed": "No se pudo abrir tu aplicación de correo.",
+ "draft_too_long": "Demasiados destinatarios para un enlace de borrador.",
+ "invalid_address": "Se necesitan direcciones de correo completas."
+ }
+ }
+ },
"calendar": {
"title": "Google Calendar",
"status": "Estado",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index a56a18517..b98f5bd37 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3848,6 +3848,8 @@
},
"tools": {
"search_notesName": "Rechercher des notes",
+ "email_draftName": "Brouillon d'e-mail",
+ "find_contactName": "Rechercher un contact",
"get_noteName": "Obtenir une note",
"create_noteName": "Créer une note",
"update_noteName": "Mettre à jour une note",
@@ -3860,6 +3862,8 @@
"update_dictionaryName": "Mettre à jour le dictionnaire",
"update_snippetsName": "Mettre à jour les snippets",
"search_notesStatus": "Recherche de notes...",
+ "email_draftStatus": "Ouverture d'un brouillon d'e-mail...",
+ "find_contactStatus": "Recherche de contacts...",
"web_searchStatus": "Recherche sur le web...",
"copy_to_clipboardStatus": "Copie dans le presse-papiers...",
"get_calendar_eventsStatus": "Vérification du calendrier...",
@@ -3951,6 +3955,7 @@
"connectFailedDescription": "Une erreur s'est produite lors de la connexion à Calendar.app. Redémarrez OpenWhispr et réessayez."
},
"sections": {
+ "connectors": "Connecteurs",
"calendar": "Calendrier",
"api": "API",
"mcp": "MCP",
@@ -4011,6 +4016,80 @@
"description": "OpenWhispr capture l'audio directement depuis votre système — il ne rejoint jamais vos réunions en tant que participant. Connectez simplement votre calendrier et prenez vos notes normalement."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Envoyer à {{destination}}"
+ },
+ "identity": "En tant que {{account}}",
+ "identityWithWorkspace": "En tant que {{account}} dans {{workspace}}",
+ "send": "Envoyer",
+ "edit": "Modifier",
+ "doneEditing": "Modification terminée",
+ "cancel": "Annuler",
+ "titleLabel": "Titre",
+ "bodyLabel": "Message",
+ "sending": "Envoi en cours…",
+ "sent": "Envoyé à {{destination}}.",
+ "open": "Ouvrir",
+ "failed": "Échec de l'envoi : {{message}}",
+ "unknown": "Impossible de confirmer l'envoi. Vérifiez {{destination}}.",
+ "cancelled": "Annulé. Rien n'a été envoyé.",
+ "notSent": "Non envoyé."
+ },
+ "policyOff": "Votre organisation a désactivé les connecteurs.",
+ "email": {
+ "title": "Brouillons d'e-mails",
+ "description": "L'assistant ouvre un brouillon pré-rempli dans votre application de messagerie. Vous le vérifiez et appuyez vous-même sur Envoyer.",
+ "proRequired": "Passez à un plan payant pour que l'assistant rédige des e-mails pour vous.",
+ "unavailable": "Les brouillons d'e-mails ne sont pas disponibles pour le moment.",
+ "targetLabel": "Rédiger les e-mails dans",
+ "autoResolved": "Automatique · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (professionnel ou scolaire)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Application de messagerie par défaut"
+ }
+ },
+ "recent": {
+ "title": "Actions récentes",
+ "actions": {
+ "email_draft": "Brouillon à {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Brouillon d'e-mail"
+ },
+ "states": {
+ "pending": "En attente",
+ "committing": "En cours",
+ "sent": "Terminé",
+ "failed": "Échec",
+ "unknown": "Non confirmé",
+ "cancelled": "Annulé",
+ "expired": "Expiré"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Brouillon ouvert pour {{destination}}.",
+ "draftOpenedBodyCopied": "Brouillon ouvert pour {{destination}}. Le corps du message est dans votre presse-papiers.",
+ "draftOpenedSubjectCopied": "Brouillon ouvert pour {{destination}}. L'objet et le corps du message sont dans votre presse-papiers.",
+ "draftOpenedOnlySubjectCopied": "Brouillon ouvert pour {{destination}}. L'objet est dans votre presse-papiers.",
+ "needsDetails": "Il manque des précisions.",
+ "unavailable": "Les connecteurs ne sont pas disponibles pour le moment.",
+ "failed": "Cela n'a pas fonctionné.",
+ "unknown": "Non confirmé. Vérifiez si l'action a abouti avant de réessayer.",
+ "draftUnknown": "Non confirmé : le brouillon pour {{destination}} ne s'est peut-être pas ouvert. Vérifiez avant de réessayer.",
+ "contactsFound": "Contacts trouvés : {{total}}",
+ "draftLimit": "Seuls {{count}} brouillons peuvent s'ouvrir par demande.",
+ "clipboardBusy": "Non ouvert : le texte d'un autre brouillon est encore dans votre presse-papiers.",
+ "errors": {
+ "open_failed": "Impossible d'ouvrir votre application de messagerie.",
+ "draft_too_long": "Trop de destinataires pour un lien de brouillon.",
+ "invalid_address": "Des adresses e-mail complètes sont nécessaires."
+ }
+ }
+ },
"notesView": {
"searchPlaceholder": "Rechercher des notes…",
"newNote": "Nouvelle note",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 629bcb89c..f83e6f1aa 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -3679,6 +3679,8 @@
},
"tools": {
"search_notesName": "Cerca nelle note",
+ "email_draftName": "Bozza email",
+ "find_contactName": "Trova contatto",
"get_noteName": "Ottieni nota",
"create_noteName": "Crea nota",
"update_noteName": "Aggiorna nota",
@@ -3691,6 +3693,8 @@
"update_dictionaryName": "Aggiorna dizionario",
"update_snippetsName": "Aggiorna snippet",
"search_notesStatus": "Ricerca nelle note...",
+ "email_draftStatus": "Apertura di una bozza email...",
+ "find_contactStatus": "Ricerca contatti...",
"web_searchStatus": "Ricerca sul web...",
"copy_to_clipboardStatus": "Copia negli appunti...",
"get_calendar_eventsStatus": "Controllo del calendario...",
@@ -3782,6 +3786,7 @@
"connectFailedDescription": "Si è verificato un errore durante la connessione a Calendar.app. Riavvia OpenWhispr e riprova."
},
"sections": {
+ "connectors": "Connettori",
"calendar": "Calendario",
"api": "API",
"mcp": "MCP",
@@ -3842,6 +3847,80 @@
"description": "OpenWhispr cattura l'audio direttamente dal tuo sistema — non entra mai nelle tue riunioni come partecipante. Basta collegare il calendario e prendere appunti normalmente."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Invia a {{destination}}"
+ },
+ "identity": "Come {{account}}",
+ "identityWithWorkspace": "Come {{account}} in {{workspace}}",
+ "send": "Invia",
+ "edit": "Modifica",
+ "doneEditing": "Modifica completata",
+ "cancel": "Annulla",
+ "titleLabel": "Titolo",
+ "bodyLabel": "Messaggio",
+ "sending": "Invio in corso…",
+ "sent": "Inviato a {{destination}}.",
+ "open": "Apri",
+ "failed": "Invio non riuscito: {{message}}",
+ "unknown": "Impossibile confermare l'invio. Controlla {{destination}}.",
+ "cancelled": "Annullato. Non è stato inviato nulla.",
+ "notSent": "Non inviato."
+ },
+ "policyOff": "La tua organizzazione ha disattivato i connettori.",
+ "email": {
+ "title": "Bozze email",
+ "description": "L'assistente apre una bozza precompilata nella tua app di posta. La rivedi e premi Invia tu stesso.",
+ "proRequired": "Passa a un piano a pagamento per far scrivere all'assistente le bozze delle email.",
+ "unavailable": "Le bozze email non sono disponibili al momento.",
+ "targetLabel": "Crea bozze email in",
+ "autoResolved": "Automatico · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (lavoro o scuola)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "App di posta predefinita"
+ }
+ },
+ "recent": {
+ "title": "Azioni recenti",
+ "actions": {
+ "email_draft": "Bozza a {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Bozza email"
+ },
+ "states": {
+ "pending": "In attesa",
+ "committing": "In corso",
+ "sent": "Completato",
+ "failed": "Non riuscito",
+ "unknown": "Non confermato",
+ "cancelled": "Annullato",
+ "expired": "Scaduto"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Bozza aperta per {{destination}}.",
+ "draftOpenedBodyCopied": "Bozza aperta per {{destination}}. Il testo è negli appunti.",
+ "draftOpenedSubjectCopied": "Bozza aperta per {{destination}}. L'oggetto e il testo sono negli appunti.",
+ "draftOpenedOnlySubjectCopied": "Bozza per {{destination}} aperta. L'oggetto è negli appunti.",
+ "needsDetails": "Servono più dettagli.",
+ "unavailable": "I connettori non sono disponibili al momento.",
+ "failed": "Non ha funzionato.",
+ "unknown": "Non confermato. Controlla se è andato a buon fine prima di riprovare.",
+ "draftUnknown": "Non confermato: la bozza per {{destination}} potrebbe non essersi aperta. Controlla prima di riprovare.",
+ "contactsFound": "Contatti trovati: {{total}}",
+ "draftLimit": "Si possono aprire solo {{count}} bozze per richiesta.",
+ "clipboardBusy": "Non aperta: il testo di un'altra bozza è ancora negli appunti.",
+ "errors": {
+ "open_failed": "Impossibile aprire l'app email.",
+ "draft_too_long": "Troppi destinatari per un link di bozza.",
+ "invalid_address": "Servono indirizzi email completi."
+ }
+ }
+ },
"calendar": {
"title": "Google Calendar",
"status": "Stato",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 23fa4bdc4..a89a905f3 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -3679,6 +3679,8 @@
},
"tools": {
"search_notesName": "ノートを検索",
+ "email_draftName": "メールの下書き",
+ "find_contactName": "連絡先を検索",
"get_noteName": "ノートを取得",
"create_noteName": "ノートを作成",
"update_noteName": "ノートを更新",
@@ -3691,6 +3693,8 @@
"update_dictionaryName": "辞書を更新",
"update_snippetsName": "スニペットを更新",
"search_notesStatus": "ノートを検索中...",
+ "email_draftStatus": "メールの下書きを開いています...",
+ "find_contactStatus": "連絡先を検索中...",
"web_searchStatus": "ウェブを検索中...",
"copy_to_clipboardStatus": "クリップボードにコピー中...",
"get_calendar_eventsStatus": "カレンダーを確認中...",
@@ -3782,6 +3786,7 @@
"connectFailedDescription": "Calendar.app への接続中にエラーが発生しました。OpenWhispr を再起動してもう一度お試しください。"
},
"sections": {
+ "connectors": "コネクタ",
"calendar": "カレンダー",
"api": "API",
"mcp": "MCP",
@@ -3842,6 +3847,80 @@
"description": "OpenWhispr はシステムから直接オーディオをキャプチャします — 参加者としてミーティングに参加することはありません。カレンダーを接続して、通常通りノートを取るだけです。"
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "{{destination}} に送信"
+ },
+ "identity": "{{account}} として",
+ "identityWithWorkspace": "{{workspace}} の {{account}} として",
+ "send": "送信",
+ "edit": "編集",
+ "doneEditing": "編集完了",
+ "cancel": "キャンセル",
+ "titleLabel": "タイトル",
+ "bodyLabel": "メッセージ",
+ "sending": "送信中…",
+ "sent": "{{destination}} に送信しました。",
+ "open": "開く",
+ "failed": "送信できませんでした: {{message}}",
+ "unknown": "送信されたか確認できませんでした。{{destination}} を確認してください。",
+ "cancelled": "キャンセルしました。何も送信されていません。",
+ "notSent": "送信されていません。"
+ },
+ "policyOff": "組織によってコネクタが無効にされています。",
+ "email": {
+ "title": "メール下書き",
+ "description": "アシスタントがメールアプリに下書きを自動入力して開きます。内容を確認し、自分で送信を押してください。",
+ "proRequired": "アシスタントにメールの下書きを作成させるには、有料プランへのアップグレードが必要です。",
+ "unavailable": "現在メール下書きを利用できません。",
+ "targetLabel": "メールを作成するアプリ",
+ "autoResolved": "自動 · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook(職場または学校)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "既定のメールアプリ"
+ }
+ },
+ "recent": {
+ "title": "最近のアクション",
+ "actions": {
+ "email_draft": "{{destination}} 宛ての下書き"
+ },
+ "unlabeledActions": {
+ "email_draft": "メール下書き"
+ },
+ "states": {
+ "pending": "待機中",
+ "committing": "処理中",
+ "sent": "完了",
+ "failed": "失敗",
+ "unknown": "未確認",
+ "cancelled": "キャンセル済み",
+ "expired": "期限切れ"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "{{destination}} 宛ての下書きを開きました。",
+ "draftOpenedBodyCopied": "{{destination}} 宛ての下書きを開きました。本文はクリップボードにあります。",
+ "draftOpenedSubjectCopied": "{{destination}} 宛ての下書きを開きました。件名と本文はクリップボードにあります。",
+ "draftOpenedOnlySubjectCopied": "{{destination}} 宛ての下書きを開きました。件名はクリップボードにあります。",
+ "needsDetails": "詳細が必要です。",
+ "unavailable": "現在コネクタを利用できません。",
+ "failed": "うまくいきませんでした。",
+ "unknown": "未確認です。再試行する前に完了したかどうかを確認してください。",
+ "draftUnknown": "未確認:{{destination}} 宛ての下書きが開かなかった可能性があります。再試行する前に確認してください。",
+ "contactsFound": "見つかった連絡先: {{total}}",
+ "draftLimit": "1回のリクエストで開ける下書きは{{count}}件までです。",
+ "clipboardBusy": "開いていません:別の下書きのテキストがまだクリップボードにあります。",
+ "errors": {
+ "open_failed": "メールアプリを開けませんでした。",
+ "draft_too_long": "下書きリンクには宛先が多すぎます。",
+ "invalid_address": "完全なメールアドレスが必要です。"
+ }
+ }
+ },
"calendar": {
"title": "Google カレンダー",
"status": "ステータス",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 50e6d0c1b..c1ca7dbd1 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -3679,6 +3679,8 @@
},
"tools": {
"search_notesName": "Pesquisar notas",
+ "email_draftName": "Rascunho de e-mail",
+ "find_contactName": "Encontrar contato",
"get_noteName": "Obter nota",
"create_noteName": "Criar nota",
"update_noteName": "Atualizar nota",
@@ -3691,6 +3693,8 @@
"update_dictionaryName": "Atualizar dicionário",
"update_snippetsName": "Atualizar snippets",
"search_notesStatus": "Pesquisando notas...",
+ "email_draftStatus": "Abrindo um rascunho de e-mail...",
+ "find_contactStatus": "Procurando contatos...",
"web_searchStatus": "Pesquisando na web...",
"copy_to_clipboardStatus": "Copiando para a área de transferência...",
"get_calendar_eventsStatus": "Verificando calendário...",
@@ -3782,6 +3786,7 @@
"connectFailedDescription": "Ocorreu um erro ao conectar ao Calendar.app. Reinicie o OpenWhispr e tente novamente."
},
"sections": {
+ "connectors": "Conectores",
"calendar": "Calendário",
"api": "API",
"mcp": "MCP",
@@ -3842,6 +3847,80 @@
"description": "O OpenWhispr captura áudio diretamente do seu sistema — ele nunca entra nas suas reuniões como participante. Basta conectar seu calendário e fazer anotações normalmente."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Enviar para {{destination}}"
+ },
+ "identity": "Como {{account}}",
+ "identityWithWorkspace": "Como {{account}} em {{workspace}}",
+ "send": "Enviar",
+ "edit": "Editar",
+ "doneEditing": "Edição concluída",
+ "cancel": "Cancelar",
+ "titleLabel": "Título",
+ "bodyLabel": "Mensagem",
+ "sending": "Enviando…",
+ "sent": "Enviado para {{destination}}.",
+ "open": "Abrir",
+ "failed": "Não foi possível enviar: {{message}}",
+ "unknown": "Não foi possível confirmar o envio. Verifique {{destination}}.",
+ "cancelled": "Cancelado. Nada foi enviado.",
+ "notSent": "Não enviado."
+ },
+ "policyOff": "Sua organização desativou os conectores.",
+ "email": {
+ "title": "Rascunhos de e-mail",
+ "description": "O assistente abre um rascunho pré-preenchido no seu aplicativo de e-mail. Você revisa e aperta Enviar.",
+ "proRequired": "Atualize para um plano pago para que o assistente escreva rascunhos de e-mail para você.",
+ "unavailable": "Os rascunhos de e-mail não estão disponíveis no momento.",
+ "targetLabel": "Criar rascunhos de e-mail em",
+ "autoResolved": "Automático · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (trabalho ou escola)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Aplicativo de e-mail padrão"
+ }
+ },
+ "recent": {
+ "title": "Ações recentes",
+ "actions": {
+ "email_draft": "Rascunho para {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Rascunho de e-mail"
+ },
+ "states": {
+ "pending": "Aguardando",
+ "committing": "Em andamento",
+ "sent": "Concluído",
+ "failed": "Falhou",
+ "unknown": "Não confirmado",
+ "cancelled": "Cancelado",
+ "expired": "Expirado"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Rascunho aberto para {{destination}}.",
+ "draftOpenedBodyCopied": "Rascunho aberto para {{destination}}. O corpo está na sua área de transferência.",
+ "draftOpenedSubjectCopied": "Rascunho aberto para {{destination}}. O assunto e o corpo estão na sua área de transferência.",
+ "draftOpenedOnlySubjectCopied": "Rascunho para {{destination}} aberto. O assunto está na sua área de transferência.",
+ "needsDetails": "Faltam detalhes.",
+ "unavailable": "Os conectores não estão disponíveis no momento.",
+ "failed": "Não funcionou.",
+ "unknown": "Não confirmado. Verifique se foi concluído antes de tentar novamente.",
+ "draftUnknown": "Não confirmado: o rascunho para {{destination}} pode não ter sido aberto. Verifique antes de tentar novamente.",
+ "contactsFound": "Contatos encontrados: {{total}}",
+ "draftLimit": "Só é possível abrir {{count}} rascunhos por solicitação.",
+ "clipboardBusy": "Não aberto: o texto de outro rascunho ainda está na sua área de transferência.",
+ "errors": {
+ "open_failed": "Não foi possível abrir seu aplicativo de e-mail.",
+ "draft_too_long": "Destinatários demais para um link de rascunho.",
+ "invalid_address": "São necessários endereços de e-mail completos."
+ }
+ }
+ },
"calendar": {
"title": "Google Agenda",
"status": "Status",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 52e020e62..2983eb617 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -3723,6 +3723,8 @@
},
"tools": {
"search_notesName": "Поиск заметок",
+ "email_draftName": "Черновик письма",
+ "find_contactName": "Найти контакт",
"get_noteName": "Получить заметку",
"create_noteName": "Создать заметку",
"update_noteName": "Обновить заметку",
@@ -3735,6 +3737,8 @@
"update_dictionaryName": "Обновить словарь",
"update_snippetsName": "Обновить сниппеты",
"search_notesStatus": "Поиск в заметках...",
+ "email_draftStatus": "Открытие черновика письма...",
+ "find_contactStatus": "Поиск контактов...",
"web_searchStatus": "Поиск в интернете...",
"copy_to_clipboardStatus": "Копирование в буфер обмена...",
"get_calendar_eventsStatus": "Проверка календаря...",
@@ -3826,6 +3830,7 @@
"connectFailedDescription": "При подключении к Calendar.app произошла ошибка. Перезапустите OpenWhispr и попробуйте снова."
},
"sections": {
+ "connectors": "Коннекторы",
"calendar": "Календарь",
"api": "API",
"mcp": "MCP",
@@ -3886,6 +3891,80 @@
"description": "OpenWhispr захватывает аудио напрямую из вашей системы — он никогда не присоединяется к встречам как участник. Просто подключите календарь и делайте заметки как обычно."
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "Отправить в {{destination}}"
+ },
+ "identity": "От имени {{account}}",
+ "identityWithWorkspace": "От имени {{account}} в {{workspace}}",
+ "send": "Отправить",
+ "edit": "Изменить",
+ "doneEditing": "Готово",
+ "cancel": "Отмена",
+ "titleLabel": "Заголовок",
+ "bodyLabel": "Сообщение",
+ "sending": "Отправка…",
+ "sent": "Отправлено в {{destination}}.",
+ "open": "Открыть",
+ "failed": "Не удалось отправить: {{message}}",
+ "unknown": "Не удалось подтвердить отправку. Проверьте {{destination}}.",
+ "cancelled": "Отменено. Ничего не отправлено.",
+ "notSent": "Не отправлено."
+ },
+ "policyOff": "Ваша организация отключила коннекторы.",
+ "email": {
+ "title": "Черновики писем",
+ "description": "Ассистент открывает предзаполненный черновик в вашем почтовом приложении. Вы проверяете его и сами нажимаете «Отправить».",
+ "proRequired": "Перейдите на платный план, чтобы ассистент составлял для вас черновики писем.",
+ "unavailable": "Черновики писем сейчас недоступны.",
+ "targetLabel": "Создавать черновики писем в",
+ "autoResolved": "Автоматически · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook (рабочий или учебный)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "Почтовое приложение по умолчанию"
+ }
+ },
+ "recent": {
+ "title": "Последние действия",
+ "actions": {
+ "email_draft": "Черновик для {{destination}}"
+ },
+ "unlabeledActions": {
+ "email_draft": "Черновик письма"
+ },
+ "states": {
+ "pending": "Ожидание",
+ "committing": "Выполняется",
+ "sent": "Готово",
+ "failed": "Не удалось",
+ "unknown": "Не подтверждено",
+ "cancelled": "Отменено",
+ "expired": "Истекло"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "Открыт черновик для {{destination}}.",
+ "draftOpenedBodyCopied": "Открыт черновик для {{destination}}. Текст письма в буфере обмена.",
+ "draftOpenedSubjectCopied": "Открыт черновик для {{destination}}. Тема и текст письма в буфере обмена.",
+ "draftOpenedOnlySubjectCopied": "Открыт черновик для {{destination}}. Тема скопирована в буфер обмена.",
+ "needsDetails": "Нужны уточнения.",
+ "unavailable": "Коннекторы сейчас недоступны.",
+ "failed": "Не получилось.",
+ "unknown": "Не подтверждено. Проверьте, выполнено ли действие, прежде чем повторять.",
+ "draftUnknown": "Не подтверждено: черновик для {{destination}} мог не открыться. Проверьте, прежде чем повторять.",
+ "contactsFound": "Найдено контактов: {{total}}",
+ "draftLimit": "Лимит черновиков на один запрос: {{count}}.",
+ "clipboardBusy": "Не открыто: текст другого черновика всё ещё в буфере обмена.",
+ "errors": {
+ "open_failed": "Не удалось открыть почтовое приложение.",
+ "draft_too_long": "Слишком много получателей для ссылки на черновик.",
+ "invalid_address": "Нужны полные адреса электронной почты."
+ }
+ }
+ },
"calendar": {
"title": "Google Календарь",
"status": "Статус",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index f5851b154..c72d23e48 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -3679,6 +3679,8 @@
},
"tools": {
"search_notesName": "搜索笔记",
+ "email_draftName": "邮件草稿",
+ "find_contactName": "查找联系人",
"get_noteName": "获取笔记",
"create_noteName": "创建笔记",
"update_noteName": "更新笔记",
@@ -3691,6 +3693,8 @@
"update_dictionaryName": "更新词典",
"update_snippetsName": "更新片段",
"search_notesStatus": "正在搜索笔记...",
+ "email_draftStatus": "正在打开邮件草稿...",
+ "find_contactStatus": "正在查找联系人...",
"web_searchStatus": "正在搜索网页...",
"copy_to_clipboardStatus": "正在复制到剪贴板...",
"get_calendar_eventsStatus": "正在查看日历...",
@@ -3782,6 +3786,7 @@
"connectFailedDescription": "连接 Calendar.app 时出错。请重启 OpenWhispr 后重试。"
},
"sections": {
+ "connectors": "连接器",
"calendar": "日历",
"api": "API",
"mcp": "MCP",
@@ -3842,6 +3847,80 @@
"description": "OpenWhispr 直接从您的系统捕获音频 — 它不会以参与者身份加入您的会议。只需连接日历,正常记录笔记即可。"
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "发送到 {{destination}}"
+ },
+ "identity": "以 {{account}} 身份",
+ "identityWithWorkspace": "以 {{account}}({{workspace}})身份",
+ "send": "发送",
+ "edit": "编辑",
+ "doneEditing": "编辑完成",
+ "cancel": "取消",
+ "titleLabel": "标题",
+ "bodyLabel": "消息",
+ "sending": "发送中…",
+ "sent": "已发送到 {{destination}}。",
+ "open": "打开",
+ "failed": "发送失败:{{message}}",
+ "unknown": "无法确认是否已发送,请检查 {{destination}}。",
+ "cancelled": "已取消,未发送任何内容。",
+ "notSent": "未发送。"
+ },
+ "policyOff": "您的组织已关闭连接器。",
+ "email": {
+ "title": "邮件草稿",
+ "description": "助手会在您的邮件应用中打开预填好的草稿,由您检查并亲自点击发送。",
+ "proRequired": "升级到付费计划,让助手为您起草邮件。",
+ "unavailable": "邮件草稿暂时不可用。",
+ "targetLabel": "在此处起草邮件",
+ "autoResolved": "自动 · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook(工作或学校)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "默认邮件应用"
+ }
+ },
+ "recent": {
+ "title": "最近的操作",
+ "actions": {
+ "email_draft": "发送给 {{destination}} 的草稿"
+ },
+ "unlabeledActions": {
+ "email_draft": "邮件草稿"
+ },
+ "states": {
+ "pending": "等待中",
+ "committing": "进行中",
+ "sent": "已完成",
+ "failed": "失败",
+ "unknown": "未确认",
+ "cancelled": "已取消",
+ "expired": "已过期"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "已打开发送给 {{destination}} 的草稿。",
+ "draftOpenedBodyCopied": "已打开发送给 {{destination}} 的草稿。正文已在剪贴板中。",
+ "draftOpenedSubjectCopied": "已打开发送给 {{destination}} 的草稿。主题和正文已在剪贴板中。",
+ "draftOpenedOnlySubjectCopied": "已打开发给 {{destination}} 的草稿。主题已在剪贴板中。",
+ "needsDetails": "需要更多信息。",
+ "unavailable": "连接器暂时不可用。",
+ "failed": "操作未成功。",
+ "unknown": "未确认。请先检查是否已完成,再重试。",
+ "draftUnknown": "未确认:发给 {{destination}} 的草稿可能没有打开。请先检查,再重试。",
+ "contactsFound": "找到的联系人:{{total}}",
+ "draftLimit": "每次请求最多只能打开 {{count}} 份草稿。",
+ "clipboardBusy": "未打开:另一份草稿的文字仍在剪贴板中。",
+ "errors": {
+ "open_failed": "无法打开您的邮件应用。",
+ "draft_too_long": "收件人太多,无法生成草稿链接。",
+ "invalid_address": "需要完整的电子邮件地址。"
+ }
+ }
+ },
"calendar": {
"title": "Google 日历",
"status": "状态",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 31e99d283..961e56de5 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -3679,6 +3679,8 @@
},
"tools": {
"search_notesName": "搜尋筆記",
+ "email_draftName": "郵件草稿",
+ "find_contactName": "尋找聯絡人",
"get_noteName": "取得筆記",
"create_noteName": "建立筆記",
"update_noteName": "更新筆記",
@@ -3691,6 +3693,8 @@
"update_dictionaryName": "更新字典",
"update_snippetsName": "更新片段",
"search_notesStatus": "正在搜尋筆記...",
+ "email_draftStatus": "正在開啟郵件草稿...",
+ "find_contactStatus": "正在尋找聯絡人...",
"web_searchStatus": "正在搜尋網頁...",
"copy_to_clipboardStatus": "正在複製到剪貼簿...",
"get_calendar_eventsStatus": "正在查看行事曆...",
@@ -3782,6 +3786,7 @@
"connectFailedDescription": "連線 Calendar.app 時發生錯誤。請重新啟動 OpenWhispr 後再試一次。"
},
"sections": {
+ "connectors": "連接器",
"calendar": "行事曆",
"api": "API",
"mcp": "MCP",
@@ -3842,6 +3847,80 @@
"description": "OpenWhispr 直接從您的系統擷取音訊 — 它不會以參與者身分加入您的會議。只需連接日曆,正常記錄筆記即可。"
}
},
+ "connectors": {
+ "approval": {
+ "headers": {
+ "default": "傳送至 {{destination}}"
+ },
+ "identity": "以 {{account}} 身分",
+ "identityWithWorkspace": "以 {{account}}({{workspace}})身分",
+ "send": "傳送",
+ "edit": "編輯",
+ "doneEditing": "編輯完成",
+ "cancel": "取消",
+ "titleLabel": "標題",
+ "bodyLabel": "訊息",
+ "sending": "傳送中…",
+ "sent": "已傳送至 {{destination}}。",
+ "open": "開啟",
+ "failed": "無法傳送:{{message}}",
+ "unknown": "無法確認是否已傳送,請檢查 {{destination}}。",
+ "cancelled": "已取消,未傳送任何內容。",
+ "notSent": "未傳送。"
+ },
+ "policyOff": "您的組織已關閉連接器。",
+ "email": {
+ "title": "郵件草稿",
+ "description": "助理會在您的郵件應用程式中開啟預先填寫的草稿,由您檢查並親自按下傳送。",
+ "proRequired": "升級到付費方案,讓助理為您草擬郵件。",
+ "unavailable": "郵件草稿暫時無法使用。",
+ "targetLabel": "在此撰寫郵件",
+ "autoResolved": "自動 · {{target}}",
+ "targets": {
+ "gmail": "Gmail",
+ "outlookWork": "Outlook(公司或學校)",
+ "outlookPersonal": "Outlook.com",
+ "mailto": "預設郵件應用程式"
+ }
+ },
+ "recent": {
+ "title": "近期操作",
+ "actions": {
+ "email_draft": "傳送給 {{destination}} 的草稿"
+ },
+ "unlabeledActions": {
+ "email_draft": "郵件草稿"
+ },
+ "states": {
+ "pending": "等待中",
+ "committing": "進行中",
+ "sent": "已完成",
+ "failed": "失敗",
+ "unknown": "未確認",
+ "cancelled": "已取消",
+ "expired": "已過期"
+ }
+ },
+ "toolStatus": {
+ "draftOpened": "已開啟傳送給 {{destination}} 的草稿。",
+ "draftOpenedBodyCopied": "已開啟傳送給 {{destination}} 的草稿。內文已在剪貼簿中。",
+ "draftOpenedSubjectCopied": "已開啟傳送給 {{destination}} 的草稿。主旨和內文已在剪貼簿中。",
+ "draftOpenedOnlySubjectCopied": "已開啟寄給 {{destination}} 的草稿。主旨已在剪貼簿中。",
+ "needsDetails": "需要更多資訊。",
+ "unavailable": "連接器暫時無法使用。",
+ "failed": "操作未成功。",
+ "unknown": "未確認。請先檢查是否已完成,再重試。",
+ "draftUnknown": "未確認:寄給 {{destination}} 的草稿可能沒有開啟。請先檢查,再重試。",
+ "contactsFound": "找到的聯絡人:{{total}}",
+ "draftLimit": "每次請求最多只能開啟 {{count}} 份草稿。",
+ "clipboardBusy": "未開啟:另一份草稿的文字仍在剪貼簿中。",
+ "errors": {
+ "open_failed": "無法開啟您的郵件應用程式。",
+ "draft_too_long": "收件者太多,無法產生草稿連結。",
+ "invalid_address": "需要完整的電子郵件地址。"
+ }
+ }
+ },
"calendar": {
"title": "Google 日曆",
"status": "狀態",
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 88aeb1d68..3cb0aab8b 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -1111,7 +1111,11 @@ class ReasoningService extends BaseReasoningService {
config: {
systemPrompt: string;
tools?: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
- executeToolCall?: (name: string, args: string) => Promise<ToolExecutionResult>;
+ executeToolCall?: (
+ name: string,
+ args: string,
+ toolCallId: string
+ ) => Promise<ToolExecutionResult>;
screenContext?: { data: string; mediaType: string };
}
): AsyncGenerator<AgentStreamChunk, void, unknown> {
@@ -1125,7 +1129,11 @@ class ReasoningService extends BaseReasoningService {
config: {
systemPrompt: string;
tools?: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
- executeToolCall?: (name: string, args: string) => Promise<ToolExecutionResult>;
+ executeToolCall?: (
+ name: string,
+ args: string,
+ toolCallId: string
+ ) => Promise<ToolExecutionResult>;
screenContext?: { data: string; mediaType: string };
},
operationGeneration: number
@@ -1173,7 +1181,7 @@ class ReasoningService extends BaseReasoningService {
if (operationWasCancelled()) return;
let toolResult: ToolExecutionResult;
try {
- toolResult = await config.executeToolCall(call.name, call.arguments);
+ toolResult = await config.executeToolCall(call.name, call.arguments, call.id);
} catch (error) {
const errMsg = `Error: ${(error as Error).message}`;
toolResult = { data: errMsg, displayText: errMsg };
diff --git a/src/services/tools/ToolRegistry.ts b/src/services/tools/ToolRegistry.ts
index 948fdb78a..63f7e8bcd 100644
--- a/src/services/tools/ToolRegistry.ts
+++ b/src/services/tools/ToolRegistry.ts
@@ -1,5 +1,5 @@
import { jsonSchema } from "ai";
-import type { Tool } from "ai";
+import type { Tool, ToolExecutionOptions } from "ai";
export interface ToolResult {
success: boolean;
@@ -7,12 +7,70 @@ export interface ToolResult {
displayText: string;
}
+export interface HoldDeliveryOptions {
+ /** The tool may have put user content on the clipboard; don't copy the answer over it. */
+ preserveClipboard?: boolean;
+}
+
+/**
+ * Per-call context from the chat turn that invoked the tool. Absent when a
+ * tool runs outside a chat turn (tests, direct calls).
+ */
+export interface ToolExecutionContext {
+ toolCallId: string;
+ /** Aborts when the turn is cancelled or its conversation ends. */
+ signal: AbortSignal;
+ /** Tells the chat surface an approval card needs the user's attention. */
+ onApprovalRequested: () => void;
+ /**
+ * The turn's answer must stay in the chat surface instead of being pasted at
+ * the user's caret: the tool opened something outside the app or needs the
+ * user to answer.
+ */
+ onHoldDelivery: (options?: HoldDeliveryOptions) => void;
+ /**
+ * Counts one use of `key` in this turn and reports whether it stays within
+ * `limit`, so a tool can cap what one turn does (drafts opened, clipboard
+ * writes). Synchronous, so tool calls running in parallel can't overshoot.
+ */
+ claimTurnSlot: (key: string, limit: number) => boolean;
+ /** Gives back a claimed use of `key` whose action never happened. */
+ releaseTurnSlot: (key: string) => void;
+}
+
export interface ToolDefinition {
name: string;
description: string;
parameters: Record<string, unknown>;
readOnly: boolean;
- execute: (args: Record<string, unknown>) => Promise<ToolResult>;
+ execute: (args: Record<string, unknown>, context?: ToolExecutionContext) => Promise<ToolResult>;
+}
+
+// What an aborted call returns; its turn is over, so nobody shows it.
+const ABORTED_RESULT: ToolResult = { success: false, data: null, displayText: "" };
+
+/**
+ * Runs a tool, but settles as soon as its turn is aborted: a tool that
+ * ignores the signal (a fetch with no timeout) must not keep a cancelled turn,
+ * and the chat's send lock, waiting. Its late result is dropped, and a call
+ * that arrives after the abort never runs.
+ */
+export function executeTool(
+ def: ToolDefinition,
+ args: Record<string, unknown>,
+ context?: ToolExecutionContext
+): Promise<ToolResult> {
+ const signal = context?.signal;
+ if (!signal) return def.execute(args, context);
+ if (signal.aborted) return Promise.resolve(ABORTED_RESULT);
+ return new Promise((resolve, reject) => {
+ const settleAborted = () => resolve(ABORTED_RESULT);
+ signal.addEventListener("abort", settleAborted, { once: true });
+ def
+ .execute(args, context)
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener("abort", settleAborted));
+ });
}
export class ToolRegistry {
@@ -30,15 +88,27 @@ export class ToolRegistry {
return Array.from(this.tools.values());
}
- toAISDKFormat(): Record<string, Tool> {
+ /**
+ * The AI SDK hands the stream only the model-facing output, so
+ * `onDisplayText` receives each call's displayText for its tool step.
+ */
+ toAISDKFormat(
+ createContext?: (toolCallId: string) => ToolExecutionContext,
+ onDisplayText?: (toolCallId: string, displayText: string) => void
+ ): Record<string, Tool> {
const result: Record<string, Tool> = {};
for (const def of this.getAll()) {
result[def.name] = {
description: def.description,
inputSchema: jsonSchema(def.parameters),
- execute: async (args: unknown) => {
+ execute: async (args: unknown, options: ToolExecutionOptions) => {
try {
- const toolResult = await def.execute(args as Record<string, unknown>);
+ const toolResult = await executeTool(
+ def,
+ args as Record<string, unknown>,
+ createContext?.(options.toolCallId)
+ );
+ onDisplayText?.(options.toolCallId, toolResult.displayText);
return toolResult.success ? toolResult.data : { error: toolResult.displayText };
} catch (error) {
return { error: (error as Error).message || "Tool execution failed" };
diff --git a/src/services/tools/connectors/emailDraftTool.ts b/src/services/tools/connectors/emailDraftTool.ts
new file mode 100644
index 000000000..655f4bd46
--- /dev/null
+++ b/src/services/tools/connectors/emailDraftTool.ts
@@ -0,0 +1,203 @@
+import i18n from "../../../i18n";
+import type { ToolDefinition, ToolExecutionContext, ToolResult } from "../ToolRegistry";
+import {
+ bareEmailAddress,
+ buildComposeRequest,
+ isValidEmailAddress,
+ recipientLabel,
+} from "../../../helpers/connectors/emailCompose";
+import type { ConnectorDirectResult } from "../../../types/connectors";
+import type { EmailDraftTarget } from "../../../utils/emailDraftTarget";
+import { getCachedPlatform } from "../../../utils/platform";
+import {
+ failedResult,
+ needsClarificationResult,
+ notSentResult,
+ unavailableResult,
+ unknownResult,
+} from "./toolOutcome";
+
+// Enough for "email Josh and Dana each a recap"; a model stuck in a loop, or
+// following an injected instruction, can't bury the user in compose windows.
+const MAX_DRAFTS_PER_TURN = 3;
+
+function addressList(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === "string").map(bareEmailAddress)
+ : [];
+}
+
+interface Overflow {
+ subject: boolean;
+ body: boolean;
+}
+
+function overflowedText({ subject, body }: Overflow): string {
+ return subject && body ? "subject and body" : subject ? "subject" : "body";
+}
+
+function draftOpenedGuidance(
+ result: Extract<ConnectorDirectResult, { state: "sent" }>,
+ overflow: Overflow
+): string {
+ if (result.copyFailed) {
+ const text = overflowedText(overflow);
+ return `The draft opened, but its ${text} didn't fit in a link and couldn't be copied to the clipboard. Put the ${text} in your reply so the user can paste it into the draft.`;
+ }
+ if (result.subjectCopied && result.bodyCopied) {
+ return "The subject and body were too long for a link, so they are on the user's clipboard (subject first, then a blank line, then the body). Tell them to paste the subject and body into the draft.";
+ }
+ if (result.subjectCopied) {
+ return "The subject was too long for a link, so it is on the user's clipboard. Tell them to paste it into the subject line.";
+ }
+ if (result.bodyCopied) {
+ return "The body was too long for a link, so it is on the user's clipboard. Tell them to paste it into the draft.";
+ }
+ return "Tell the user the draft is open for them to review and send.";
+}
+
+export function createEmailDraftTool(target: EmailDraftTarget): ToolDefinition {
+ return {
+ name: "email_draft",
+ description:
+ "Open a pre-filled email draft in the user's email app so they can review and send it themselves. This never sends email. `to` and `cc` must be full email addresses; call find_contact first when you only have a name.",
+ parameters: {
+ type: "object",
+ properties: {
+ to: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ description: "Recipient email addresses",
+ },
+ cc: { type: "array", items: { type: "string" }, description: "Cc email addresses" },
+ subject: { type: "string", description: "Subject line" },
+ body: { type: "string", description: "Plain-text body; blank lines between paragraphs" },
+ },
+ required: ["to", "subject", "body"],
+ additionalProperties: false,
+ },
+ readOnly: false,
+
+ async execute(
+ args: Record<string, unknown>,
+ context?: ToolExecutionContext
+ ): Promise<ToolResult> {
+ // Every outcome keeps the turn off the caret: an opened compose window
+ // takes focus, and a question back must not land in the user's document.
+ context?.onHoldDelivery();
+ const to = addressList(args.to);
+ const cc = addressList(args.cc);
+ const invalid = [...to, ...cc].filter((address) => !isValidEmailAddress(address));
+ if (to.length === 0 || invalid.length > 0) {
+ const rejected = invalid.map((address) => JSON.stringify(address)).join(", ");
+ return needsClarificationResult(
+ `Every recipient must be an email address like [email protected]${rejected ? ` (not ${rejected})` : ""}. If you already know the address, call email_draft again with it. If you only have a name, call find_contact first.`
+ );
+ }
+
+ if (context?.signal.aborted) return notSentResult("cancelled");
+ const draft = {
+ target,
+ to,
+ cc,
+ subject: typeof args.subject === "string" ? args.subject : "",
+ body: typeof args.body === "string" ? args.body : "",
+ };
+ // Main builds the same request; checking it here claims the clipboard
+ // before any await, so a second overflowing draft in the turn can't
+ // replace the first one's text before the user pastes it. Main refuses
+ // to use the clipboard unless this draft reserved it. Built before the
+ // slots are claimed, so nothing can throw between a claim and its release.
+ const preview = buildComposeRequest({ ...draft, platform: getCachedPlatform() });
+ const clipboardReserved = preview.ok && preview.clipboardText !== null;
+ const overflow = {
+ subject: preview.ok && preview.subjectCopied,
+ body: preview.ok && preview.bodyCopied,
+ };
+ // Shown to the user and in guidance with any punycode form; the data
+ // keeps bare addresses so the model can reuse them in a retry.
+ const destination = to.map(recipientLabel).join(", ");
+
+ if (context && !context.claimTurnSlot("email_draft", MAX_DRAFTS_PER_TURN)) {
+ return notSentResult(
+ "draft_limit",
+ `Only ${MAX_DRAFTS_PER_TURN} drafts can open per request. Tell the user which drafts opened and ask them to request the rest again.`,
+ i18n.t("connectors.toolStatus.draftLimit", { count: MAX_DRAFTS_PER_TURN })
+ );
+ }
+ if (clipboardReserved && context && !context.claimTurnSlot("clipboard", 1)) {
+ context.releaseTurnSlot("email_draft");
+ return notSentResult(
+ "clipboard_in_use",
+ "This draft is too long for a link, and its text would replace another draft's text on the clipboard. Tell the user to paste the earlier draft's text first, then ask again for this one.",
+ i18n.t("connectors.toolStatus.clipboardBusy")
+ );
+ }
+ // A draft that never opened gives its slots back, so a retry in the
+ // same turn isn't refused for text that never reached the clipboard.
+ const releaseSlots = (): void => {
+ context?.releaseTurnSlot("email_draft");
+ if (clipboardReserved) context?.releaseTurnSlot("clipboard");
+ };
+
+ // Main may still be resolving policy when the user presses Esc; the
+ // cancel names this run so main drops it instead of opening a window.
+ const runId = crypto.randomUUID();
+ const cancelRun = () =>
+ void window.electronAPI?.connectorCancel?.(runId, "cancelled_by_user");
+ context?.signal.addEventListener("abort", cancelRun, { once: true });
+ // A rejected call (no handler in main) is treated like a missing API.
+ const result = await window.electronAPI
+ ?.connectorRunDirect?.("email", "draft", { ...draft, clipboardReserved }, runId)
+ .catch(() => undefined);
+ context?.signal.removeEventListener("abort", cancelRun);
+ if (!result) {
+ releaseSlots();
+ return unavailableResult("connectors_unavailable");
+ }
+ // Sticky for the turn once text may be on the clipboard, so the answer
+ // isn't copied over it.
+ const preserveClipboard = (): void => context?.onHoldDelivery({ preserveClipboard: true });
+ // An unknown run may have opened a window and used the clipboard, so
+ // it keeps its slots.
+ if (result.state === "unknown") {
+ if (clipboardReserved) preserveClipboard();
+ return unknownResult(
+ `The draft to ${destination} may or may not have opened. Ask the user to check for a draft window.`,
+ i18n.t("connectors.toolStatus.draftUnknown", { destination })
+ );
+ }
+ if (result.state !== "sent") releaseSlots();
+ else if (result.copyFailed) context?.releaseTurnSlot("clipboard");
+ if (result.state === "not_sent") return notSentResult(result.reason);
+ if (result.state === "unavailable") return unavailableResult(result.reason);
+ if (result.state === "failed") return failedResult(result.errorCode, result.message);
+
+ const bodyCopied = Boolean(result.bodyCopied);
+ const subjectCopied = Boolean(result.subjectCopied);
+ if (bodyCopied || subjectCopied) preserveClipboard();
+
+ return {
+ success: true,
+ data: {
+ status: "draft_opened",
+ recipients: to,
+ bodyCopied,
+ subjectCopied,
+ guidance: draftOpenedGuidance(result, overflow),
+ },
+ displayText: i18n.t(
+ subjectCopied && bodyCopied
+ ? "connectors.toolStatus.draftOpenedSubjectCopied"
+ : subjectCopied
+ ? "connectors.toolStatus.draftOpenedOnlySubjectCopied"
+ : bodyCopied
+ ? "connectors.toolStatus.draftOpenedBodyCopied"
+ : "connectors.toolStatus.draftOpened",
+ { destination }
+ ),
+ };
+ },
+ };
+}
diff --git a/src/services/tools/connectors/findContactTool.ts b/src/services/tools/connectors/findContactTool.ts
new file mode 100644
index 000000000..8b86702f4
--- /dev/null
+++ b/src/services/tools/connectors/findContactTool.ts
@@ -0,0 +1,48 @@
+import i18n from "../../../i18n";
+import type { ToolDefinition, ToolExecutionContext, ToolResult } from "../ToolRegistry";
+import { needsClarificationResult, unavailableResult } from "./toolOutcome";
+
+export const findContactTool: ToolDefinition = {
+ name: "find_contact",
+ description:
+ "Look up people's email addresses by name from the user's calendar meetings and saved contacts. Returns up to 5 matches with name, email and the date of the most recent past meeting (null when none is on record).",
+ parameters: {
+ type: "object",
+ properties: {
+ name: { type: "string", description: "A name or part of an email address" },
+ },
+ required: ["name"],
+ additionalProperties: false,
+ },
+ readOnly: true,
+
+ async execute(
+ args: Record<string, unknown>,
+ context?: ToolExecutionContext
+ ): Promise<ToolResult> {
+ // A lookup is almost always followed by a question for the user ("what
+ // should the email say?", "which Josh?"), and that must never be pasted
+ // into their document, so the answer stays in the panel whatever it finds.
+ context?.onHoldDelivery();
+ const name = typeof args.name === "string" ? args.name.trim() : "";
+ if (!name) return needsClarificationResult("Ask the user whose email address to look up.");
+
+ const response = await window.electronAPI?.connectorFindContacts?.(name);
+ if (response?.unavailableReason) return unavailableResult(response.unavailableReason);
+ const contacts = response?.contacts ?? [];
+ const guidance =
+ contacts.length === 0
+ ? "No match. Ask the user for the email address."
+ : response?.hasMore
+ ? `More than ${contacts.length} people match and only the closest are listed. Unless one is clearly meant, ask the user for the last name or email address.`
+ : contacts.length > 1
+ ? "Several people match. Ask the user which one unless the request makes it clear."
+ : undefined;
+
+ return {
+ success: true,
+ data: { contacts, ...(guidance ? { guidance } : {}) },
+ displayText: i18n.t("connectors.toolStatus.contactsFound", { total: contacts.length }),
+ };
+ },
+};
diff --git a/src/services/tools/connectors/runApprovalAction.ts b/src/services/tools/connectors/runApprovalAction.ts
new file mode 100644
index 000000000..b9f6f1d36
--- /dev/null
+++ b/src/services/tools/connectors/runApprovalAction.ts
@@ -0,0 +1,23 @@
+import type { ToolExecutionContext, ToolResult } from "../ToolRegistry";
+import { requestApproval } from "../../../stores/connectorApprovalStore";
+import { approvalOutcomeResult, prepareFailureResult, unavailableResult } from "./toolOutcome";
+
+/** Prepare in main, show the card, and report what the user decided. */
+export async function runApprovalAction(
+ context: ToolExecutionContext | undefined,
+ connectorId: string,
+ action: string,
+ args: Record<string, unknown>
+): Promise<ToolResult> {
+ if (!context) return unavailableResult("no_chat_context");
+ const prepared = await window.electronAPI?.connectorPrepare?.(connectorId, action, args);
+ if (!prepared) return unavailableResult("connectors_unavailable");
+ if (prepared.status !== "ready") return prepareFailureResult(prepared);
+
+ const outcome = await requestApproval(context, {
+ actionId: prepared.actionId,
+ connectorId,
+ preview: prepared.preview,
+ });
+ return approvalOutcomeResult(outcome, prepared.preview.destinationLabel);
+}
diff --git a/src/services/tools/connectors/toolOutcome.ts b/src/services/tools/connectors/toolOutcome.ts
new file mode 100644
index 000000000..b550c6b91
--- /dev/null
+++ b/src/services/tools/connectors/toolOutcome.ts
@@ -0,0 +1,113 @@
+import i18n from "../../../i18n";
+import type { ToolResult } from "../ToolRegistry";
+import type { ApprovalOutcome, ConnectorPrepareResult } from "../../../types/connectors";
+
+const NO_RETRY = "Do not retry this action unless the user asks you to.";
+
+// Connector results always return success: true, so the model gets the
+// structured status (the AI SDK path turns failures into a bare error string).
+// data is for the model; displayText is the user's tool step, so it is
+// localized and never carries codes.
+export function needsClarificationResult(message: string, candidates: string[] = []): ToolResult {
+ return {
+ success: true,
+ data: { status: "needs_clarification", message, candidates },
+ displayText: i18n.t("connectors.toolStatus.needsDetails"),
+ };
+}
+
+export function unavailableResult(reason: string): ToolResult {
+ return {
+ success: true,
+ data: { status: "unavailable", reason, guidance: NO_RETRY },
+ displayText: i18n.t(
+ reason === "policy_blocked" ? "connectors.policyOff" : "connectors.toolStatus.unavailable"
+ ),
+ };
+}
+
+export function notSentResult(
+ reason: string,
+ guidance: string = NO_RETRY,
+ displayText: string = i18n.t("connectors.approval.notSent")
+): ToolResult {
+ return {
+ success: true,
+ data: { status: "not_sent", reason, guidance },
+ displayText,
+ };
+}
+
+export function failedResult(errorCode: string, message: string): ToolResult {
+ return {
+ success: true,
+ data: { status: "failed", errorCode, error: message },
+ displayText: i18n.t(`connectors.toolStatus.errors.${errorCode}`, {
+ defaultValue: i18n.t("connectors.toolStatus.failed"),
+ }),
+ };
+}
+
+export function unknownResult(
+ guidance: string,
+ displayText: string = i18n.t("connectors.toolStatus.unknown")
+): ToolResult {
+ return {
+ success: true,
+ data: { status: "unknown", guidance: `${guidance} ${NO_RETRY}` },
+ displayText,
+ };
+}
+
+export function prepareFailureResult(
+ result: Exclude<ConnectorPrepareResult, { status: "ready" }>
+): ToolResult {
+ switch (result.status) {
+ case "needs_clarification":
+ return needsClarificationResult(result.message, result.candidates);
+ case "failed":
+ return failedResult(result.errorCode, result.message);
+ case "unavailable":
+ return unavailableResult(result.reason);
+ }
+}
+
+export function approvalOutcomeResult(outcome: ApprovalOutcome, destination: string): ToolResult {
+ switch (outcome.state) {
+ case "sent":
+ return {
+ success: true,
+ data: {
+ status: "sent",
+ url: outcome.url,
+ destination,
+ ...(outcome.finalText !== undefined ? { finalText: outcome.finalText } : {}),
+ },
+ displayText: i18n.t("connectors.approval.sent", { destination }),
+ };
+ case "cancelled":
+ return {
+ success: true,
+ data: {
+ status: "cancelled_by_user",
+ guidance: `The user cancelled this action. ${NO_RETRY} Ask what they would like to change if it is unclear.`,
+ },
+ displayText: i18n.t("connectors.approval.cancelled"),
+ };
+ case "not_sent":
+ return notSentResult(outcome.reason);
+ case "failed":
+ return failedResult(outcome.errorCode, outcome.message);
+ case "unknown":
+ return {
+ success: true,
+ data: {
+ status: "unknown",
+ destination,
+ checkUrl: outcome.checkUrl,
+ guidance: `It may or may not have been sent. ${NO_RETRY} Tell the user to check ${destination}.`,
+ },
+ displayText: i18n.t("connectors.approval.unknown", { destination }),
+ };
+ }
+}
diff --git a/src/services/tools/index.ts b/src/services/tools/index.ts
index cb71e1ad5..a63af205a 100644
--- a/src/services/tools/index.ts
+++ b/src/services/tools/index.ts
@@ -10,7 +10,10 @@ import { calendarTool } from "./calendarTool";
import { calendarAvailabilityTool } from "./calendarAvailabilityTool";
import { createSnippetTool, createUpdateSnippetsTool, type SnippetActions } from "./snippetTool";
import { createUpdateDictionaryTool, type DictionaryActions } from "./dictionaryTool";
+import { createEmailDraftTool } from "./connectors/emailDraftTool";
+import { findContactTool } from "./connectors/findContactTool";
import type { ContainerScope } from "../../types/chat";
+import type { EmailDraftTarget } from "../../utils/emailDraftTarget";
export { ToolRegistry } from "./ToolRegistry";
export type { ToolDefinition, ToolResult } from "./ToolRegistry";
@@ -24,6 +27,8 @@ interface ToolRegistrySettings {
webSearchEnabled: boolean;
/** Live dictionary and snippet access; enables the vocabulary tools. */
vocabulary?: DictionaryActions & SnippetActions;
+ /** Present only when connectors are available (signed in, paid, policy allows). */
+ connectors?: { emailDraftTarget: EmailDraftTarget };
}
export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry {
@@ -53,5 +58,10 @@ export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry
registry.register(calendarAvailabilityTool);
}
+ if (settings.connectors) {
+ registry.register(findContactTool);
+ registry.register(createEmailDraftTool(settings.connectors.emailDraftTarget));
+ }
+
return registry;
}
diff --git a/src/stores/connectorApprovalStore.ts b/src/stores/connectorApprovalStore.ts
new file mode 100644
index 000000000..253c36bd1
--- /dev/null
+++ b/src/stores/connectorApprovalStore.ts
@@ -0,0 +1,218 @@
+import { create } from "zustand";
+import type { ToolExecutionContext } from "../services/tools/ToolRegistry";
+import type {
+ ApprovalOutcome,
+ ConnectorCommitResult,
+ ConnectorEdits,
+ ConnectorPreview,
+} from "../types/connectors";
+
+export const APPROVAL_TTL_MS = 10 * 60 * 1000;
+
+export type ApprovalState =
+ "pending" | "committing" | "sent" | "failed" | "unknown" | "cancelled" | "not_sent";
+
+/** What the card shows and what Send commits; starts as the preview. */
+export interface ApprovalDraft {
+ title?: string;
+ body: string;
+}
+
+export interface ApprovalEntry {
+ toolCallId: string;
+ actionId: string;
+ connectorId: string;
+ preview: ConnectorPreview;
+ draft: ApprovalDraft;
+ state: ApprovalState;
+ url?: string;
+ message?: string;
+}
+
+interface ApprovalStoreState {
+ entries: Record<string, ApprovalEntry>;
+}
+
+export const useConnectorApprovalStore = create<ApprovalStoreState>(() => ({ entries: {} }));
+
+interface PendingResolution {
+ resolve: (outcome: ApprovalOutcome) => void;
+ timer: ReturnType<typeof setTimeout>;
+ detach: () => void;
+}
+
+// Promise resolvers stay outside zustand state: they are not renderable.
+const resolutions = new Map<string, PendingResolution>();
+
+const COMMIT_RESULT_STATES = new Set(["sent", "failed", "unknown", "not_sent"]);
+
+// Main passes an untyped CommonJS connector's result straight through, so a
+// malformed commit result (wrong key, unrecognized state, or no result at
+// all) must never be trusted at face value — it would otherwise leave the
+// switch below with no matching case, and the approval would hang forever.
+function isConnectorCommitResult(value: unknown): value is ConnectorCommitResult {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "state" in value &&
+ typeof (value as { state: unknown }).state === "string" &&
+ COMMIT_RESULT_STATES.has((value as { state: string }).state)
+ );
+}
+
+function entryFor(toolCallId: string): ApprovalEntry | undefined {
+ return useConnectorApprovalStore.getState().entries[toolCallId];
+}
+
+function patchEntry(toolCallId: string, patch: Partial<ApprovalEntry>): void {
+ useConnectorApprovalStore.setState((state) => {
+ const entry = state.entries[toolCallId];
+ if (!entry) return state;
+ return { entries: { ...state.entries, [toolCallId]: { ...entry, ...patch } } };
+ });
+}
+
+function settle(
+ toolCallId: string,
+ outcome: ApprovalOutcome,
+ state: ApprovalState,
+ patch: Partial<ApprovalEntry> = {}
+): void {
+ const pending = resolutions.get(toolCallId);
+ if (!pending) return;
+ resolutions.delete(toolCallId);
+ clearTimeout(pending.timer);
+ pending.detach();
+ patchEntry(toolCallId, { state, ...patch });
+ pending.resolve(outcome);
+}
+
+// Conversation end and expiry only withdraw a card that is still pending: a
+// committing send may already have reached the provider.
+function withdraw(toolCallId: string, reason: "conversation_ended" | "expired"): void {
+ const entry = entryFor(toolCallId);
+ if (!entry || entry.state !== "pending") return;
+ void window.electronAPI?.connectorCancel?.(entry.actionId, reason);
+ settle(toolCallId, { state: "not_sent", reason }, "not_sent");
+}
+
+export function requestApproval(
+ context: ToolExecutionContext,
+ request: { actionId: string; connectorId: string; preview: ConnectorPreview }
+): Promise<ApprovalOutcome> {
+ const { toolCallId, signal } = context;
+ if (signal.aborted) {
+ void window.electronAPI?.connectorCancel?.(request.actionId, "conversation_ended");
+ return Promise.resolve({ state: "not_sent", reason: "conversation_ended" });
+ }
+ // A second request for the same tool call must never steal the first
+ // card's resolver, timer or entry — that would cross-wire two actions:
+ // the first card would show the second action's outcome (or vice versa)
+ // and the loser's promise would never resolve.
+ if (resolutions.has(toolCallId)) {
+ void window.electronAPI?.connectorCancel?.(request.actionId, "cancelled_by_user");
+ return Promise.resolve({ state: "not_sent", reason: "duplicate_tool_call" });
+ }
+ return new Promise((resolve) => {
+ const onAbort = (): void => withdraw(toolCallId, "conversation_ended");
+ signal.addEventListener("abort", onAbort, { once: true });
+ const timer = setTimeout(() => withdraw(toolCallId, "expired"), APPROVAL_TTL_MS);
+ resolutions.set(toolCallId, {
+ resolve,
+ timer,
+ detach: () => signal.removeEventListener("abort", onAbort),
+ });
+ const draft: ApprovalDraft = {
+ ...(request.preview.title !== undefined ? { title: request.preview.title } : {}),
+ body: request.preview.body,
+ };
+ useConnectorApprovalStore.setState((state) => ({
+ entries: {
+ ...state.entries,
+ [toolCallId]: { toolCallId, ...request, draft, state: "pending" },
+ },
+ }));
+ context.onApprovalRequested();
+ });
+}
+
+export function updateApprovalDraft(toolCallId: string, patch: Partial<ApprovalDraft>): void {
+ const entry = entryFor(toolCallId);
+ if (!entry || entry.state !== "pending") return;
+ patchEntry(toolCallId, {
+ draft: {
+ ...entry.draft,
+ ...(patch.body !== undefined ? { body: patch.body } : {}),
+ ...(patch.title !== undefined && entry.preview.title !== undefined
+ ? { title: patch.title }
+ : {}),
+ },
+ });
+}
+
+export function cancelApproval(toolCallId: string): void {
+ const entry = entryFor(toolCallId);
+ if (!entry || entry.state !== "pending") return;
+ void window.electronAPI?.connectorCancel?.(entry.actionId, "cancelled_by_user");
+ settle(toolCallId, { state: "cancelled" }, "cancelled");
+}
+
+// Send commits the draft (what the card shows), never an edit-mode snapshot:
+// leaving edit mode must not discard the user's changes.
+export async function approveAction(toolCallId: string): Promise<void> {
+ const entry = entryFor(toolCallId);
+ if (!entry || entry.state !== "pending") return;
+ const edits: ConnectorEdits = { ...entry.draft };
+ patchEntry(toolCallId, { state: "committing" });
+ const pending = resolutions.get(toolCallId);
+ if (pending) {
+ clearTimeout(pending.timer);
+ pending.detach();
+ }
+
+ let raw: unknown;
+ try {
+ raw = await window.electronAPI?.connectorCommit?.(entry.actionId, edits);
+ } catch {
+ // The request may have reached main and been sent; never claim it wasn't.
+ raw = undefined;
+ }
+ // A missing result, or one that doesn't match a state the switch below
+ // understands (wrong key, unrecognized state), is exactly as uncertain as
+ // a thrown IPC call — never let it fall through with no case to settle.
+ const result: ConnectorCommitResult = isConnectorCommitResult(raw) ? raw : { state: "unknown" };
+
+ const finalText = entry.draft.body !== entry.preview.body ? entry.draft.body : undefined;
+ switch (result.state) {
+ case "sent":
+ settle(
+ toolCallId,
+ { state: "sent", url: result.url, ...(finalText !== undefined ? { finalText } : {}) },
+ "sent",
+ { url: result.url }
+ );
+ break;
+ case "failed":
+ settle(
+ toolCallId,
+ { state: "failed", errorCode: result.errorCode, message: result.message },
+ "failed",
+ { message: result.message }
+ );
+ break;
+ case "unknown":
+ settle(
+ toolCallId,
+ {
+ state: "unknown",
+ ...(result.checkUrl !== undefined ? { checkUrl: result.checkUrl } : {}),
+ },
+ "unknown",
+ { url: result.checkUrl }
+ );
+ break;
+ case "not_sent":
+ settle(toolCallId, { state: "not_sent", reason: result.reason }, "not_sent");
+ break;
+ }
+}
diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.ts
index b31e2bb41..8b4e0f389 100644
--- a/src/stores/policyRules.ts
+++ b/src/stores/policyRules.ts
@@ -211,6 +211,28 @@ export function isScreenContextAllowed(state: PolicyDecisionSnapshot): boolean {
return managedPolicyDecision(state, (policy) => policy.features.screenContextEnabled !== false);
}
+/**
+ * Whether agent connectors may run. They are agent tools, so turning the
+ * agent off turns them off too. Servers that predate the field send none;
+ * absent means allowed.
+ */
+export function isConnectorsAllowed(state: PolicyDecisionSnapshot): boolean {
+ return managedPolicyDecision(
+ state,
+ (policy) => policy.features.agentEnabled && policy.features.connectorsEnabled !== false
+ );
+}
+
+/**
+ * Whether a resolved org policy turned connectors off. Unlike
+ * isConnectorsAllowed, a policy that is still loading or failed to load is not
+ * reported as an org decision, and neither is one that only requires a newer
+ * app version (the update banner says that).
+ */
+export function isConnectorsBlockedByOrg(state: PolicyDecisionSnapshot): boolean {
+ return state.status === "managed" && isPolicyActionAllowed(state) && !isConnectorsAllowed(state);
+}
+
const warnedUnknownRequiredModelIds = new Set<string>();
/**
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index f4dab3dd8..6435badf6 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -12,7 +12,8 @@ import type {
LocalServerPrefs,
SelfHostedType,
} from "../types/electron";
-import type { CalendarAccount } from "../types/calendar";
+import type { CalendarAccount, MicrosoftCalendarAccount } from "../types/calendar";
+import { normalizeEmailDraftTarget, type EmailDraftTargetSetting } from "../utils/emailDraftTarget";
import { PROMPT_KIND_LIST, type PromptKind } from "../config/prompts/registry";
import { sweepRetiredPromptOverrides } from "../config/retiredPrompts";
import { sweepRetiredCloudModelSelections } from "../config/retiredCloudModels";
@@ -888,7 +889,7 @@ export interface SettingsState
gcalAccounts: CalendarAccount[];
gcalConnected: boolean;
gcalEmail: string;
- mcalAccounts: CalendarAccount[];
+ mcalAccounts: MicrosoftCalendarAccount[];
mcalConnected: boolean;
notificationsEnabled: boolean;
notifyMeetingDetection: boolean;
@@ -986,6 +987,7 @@ export interface SettingsState
// Voice-agent screen context: opt-in screenshot capture, plus an optional
// dedicated model used only when a screenshot is attached.
voiceAgentScreenContext: boolean;
+ emailDraftTarget: EmailDraftTargetSetting;
useDictationAgentVisionModel: boolean;
dictationAgentVisionMode: InferenceMode;
dictationAgentVisionProvider: string;
@@ -1012,6 +1014,7 @@ export interface SettingsState
setDictationAgentCustomApiKey: (key: string) => void;
setVoiceAgentScreenContext: (value: boolean) => void;
+ setEmailDraftTarget: (value: EmailDraftTargetSetting) => void;
setUseDictationAgentVisionModel: (value: boolean) => void;
setDictationAgentVisionProvider: (value: string) => void;
setDictationAgentVisionModel: (value: string) => void;
@@ -1202,7 +1205,7 @@ export interface SettingsState
setFloatingIconAutoHide: (enabled: boolean) => void;
setStartMinimized: (enabled: boolean) => void;
setGcalAccounts: (accounts: CalendarAccount[]) => void;
- setMcalAccounts: (accounts: CalendarAccount[]) => void;
+ setMcalAccounts: (accounts: MicrosoftCalendarAccount[]) => void;
setNotificationsEnabled: (value: boolean) => void;
setNotifyMeetingDetection: (value: boolean) => void;
setNotifyCalendarReminders: (value: boolean) => void;
@@ -1642,7 +1645,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
};
})(),
...(() => {
- let accounts: CalendarAccount[] = [];
+ let accounts: MicrosoftCalendarAccount[] = [];
try {
const parsed = JSON.parse(readString("mcalAccounts", "[]"));
if (Array.isArray(parsed)) accounts = parsed;
@@ -1926,6 +1929,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
dictationAgentCustomApiKey: readString("dictationAgentCustomApiKey", ""),
voiceAgentScreenContext: readBoolean("voiceAgentScreenContext", false),
+ emailDraftTarget: normalizeEmailDraftTarget(readString("emailDraftTarget", "auto")),
useDictationAgentVisionModel: readBoolean("useDictationAgentVisionModel", false),
// Cloud already vision-routes screenshot commands, so the override is BYOK-only.
dictationAgentVisionMode: "providers" as InferenceMode,
@@ -1965,6 +1969,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
),
setVoiceAgentScreenContext: createBooleanSetter("voiceAgentScreenContext"),
+ setEmailDraftTarget: createStringSetter("emailDraftTarget"),
setUseDictationAgentVisionModel: createBooleanSetter("useDictationAgentVisionModel"),
setDictationAgentVisionProvider: createStringSetter("dictationAgentVisionProvider"),
setDictationAgentVisionModel: createStringSetter("dictationAgentVisionModel"),
@@ -2418,7 +2423,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
gcalEmail: accounts[0]?.email ?? "",
});
},
- setMcalAccounts: (accounts: CalendarAccount[]) => {
+ setMcalAccounts: (accounts: MicrosoftCalendarAccount[]) => {
if (isBrowser) localStorage.setItem("mcalAccounts", JSON.stringify(accounts));
useSettingsStore.setState({
mcalAccounts: accounts,
@@ -3608,6 +3613,21 @@ export async function initializeSettings(): Promise<void> {
);
}
+ // Picks up tenant ids stored after the accounts were first saved here; an
+ // empty answer (including a failed read) leaves the saved list alone.
+ try {
+ const status = await window.electronAPI.mcalGetConnectionStatus?.();
+ if (status?.accounts.length) {
+ useSettingsStore.getState().setMcalAccounts(status.accounts);
+ }
+ } catch (err) {
+ logger.warn(
+ "Failed to hydrate Microsoft Calendar accounts",
+ { error: (err as Error).message },
+ "settings"
+ );
+ }
+
try {
const currentState = useSettingsStore.getState();
await window.electronAPI.gcalSetPrimaryOnly?.(currentState.gcalPrimaryOnly);
@@ -3726,6 +3746,8 @@ export async function initializeSettings(): Promise<void> {
} else {
value = parsed;
}
+ } else if (key === "emailDraftTarget") {
+ value = normalizeEmailDraftTarget(newValue);
} else {
value = newValue;
}
diff --git a/src/types/calendar.ts b/src/types/calendar.ts
index 6db5ee800..efa708514 100644
--- a/src/types/calendar.ts
+++ b/src/types/calendar.ts
@@ -63,6 +63,11 @@ export interface CalendarAccount {
email: string;
}
+export interface MicrosoftCalendarAccount extends CalendarAccount {
+ /** Entra tenant id; null or absent for accounts connected by older builds. */
+ tenantId?: string | null;
+}
+
export interface CalendarConnectionStatus {
connected: boolean;
email: string | null;
@@ -73,6 +78,7 @@ export interface CalendarAttendee {
displayName: string | null;
responseStatus: CalendarResponseStatus | null;
self: boolean;
+ resource?: boolean;
}
export interface Contact {
diff --git a/src/types/connectors.ts b/src/types/connectors.ts
new file mode 100644
index 000000000..08d4e5771
--- /dev/null
+++ b/src/types/connectors.ts
@@ -0,0 +1,83 @@
+export type ConnectorPolicyState = "allowed" | "blocked" | "unavailable";
+
+export type ConnectorCancelReason = "cancelled_by_user" | "conversation_ended" | "expired";
+
+export interface ConnectorPreviewNote {
+ key: string;
+ values?: Record<string, string>;
+}
+
+export interface ConnectorPreview {
+ /** i18n suffix under connectors.approval.headers (e.g. "default", "post"). */
+ verbKey: string;
+ destinationLabel: string;
+ accountLabel: string;
+ workspaceLabel?: string;
+ title?: string;
+ body: string;
+ notes?: ConnectorPreviewNote[];
+}
+
+export interface ConnectorEdits {
+ title?: string;
+ body?: string;
+}
+
+export type ConnectorPrepareResult =
+ | { status: "ready"; actionId: string; preview: ConnectorPreview }
+ | { status: "needs_clarification"; message: string; candidates: string[] }
+ | { status: "failed"; errorCode: string; message: string }
+ | { status: "unavailable"; reason: string };
+
+export type ConnectorCommitResult =
+ | { state: "sent"; url?: string }
+ | { state: "failed"; errorCode: string; message: string }
+ | { state: "unknown"; checkUrl?: string }
+ | { state: "not_sent"; reason: string };
+
+export type ConnectorDirectResult =
+ | {
+ state: "sent";
+ destinationLabel: string;
+ bodyCopied?: boolean;
+ subjectCopied?: boolean;
+ copyFailed?: boolean;
+ }
+ | { state: "failed"; errorCode: string; message: string; destinationLabel?: string }
+ | { state: "unknown"; errorCode: string; message: string }
+ | { state: "unavailable"; reason: string }
+ | { state: "not_sent"; reason: string };
+
+export type ApprovalOutcome =
+ | { state: "sent"; url?: string; finalText?: string }
+ | { state: "failed"; errorCode: string; message: string }
+ | { state: "unknown"; checkUrl?: string }
+ | { state: "cancelled" }
+ | { state: "not_sent"; reason: string };
+
+export interface ConnectorStatus {
+ id: string;
+ connected: boolean;
+ accountLabel: string | null;
+}
+
+export type ConnectorActionState =
+ "pending" | "committing" | "sent" | "failed" | "unknown" | "cancelled" | "expired";
+
+export interface ConnectorActionRecord {
+ id: string;
+ connector: string;
+ action: string;
+ kind: "approval" | "direct";
+ destinationLabel: string | null;
+ state: ConnectorActionState;
+ resultUrl: string | null;
+ errorCode: string | null;
+ createdAt: string;
+}
+
+export interface ContactMatch {
+ name: string | null;
+ email: string;
+ lastMet: string | null;
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 73ba5dc43..7246fc487 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -6,7 +6,21 @@ import type {
ManagedEnterpriseConfig,
ManagedEnterpriseRequestContext,
} from "./enterpriseIdentity";
-import type { CalendarAvailabilityRequest, CalendarAvailabilityResult } from "./calendar";
+import type {
+ CalendarAvailabilityRequest,
+ CalendarAvailabilityResult,
+ MicrosoftCalendarAccount,
+} from "./calendar";
+import type {
+ ConnectorActionRecord,
+ ConnectorCancelReason,
+ ConnectorCommitResult,
+ ConnectorDirectResult,
+ ConnectorEdits,
+ ConnectorPrepareResult,
+ ConnectorStatus,
+ ContactMatch,
+} from "./connectors";
export type LocalTranscriptionProvider = "whisper" | "nvidia" | "cohere";
@@ -2900,6 +2914,31 @@ declare global {
gcalGetUpcomingEvents?: (
windowMinutes?: number
) => Promise<{ success: boolean; events: any[] }>;
+ connectorStatus?: () => Promise<ConnectorStatus[]>;
+ connectorPrepare?: (
+ connectorId: string,
+ action: string,
+ args: Record<string, unknown>
+ ) => Promise<ConnectorPrepareResult>;
+ connectorCommit?: (actionId: string, edits: ConnectorEdits) => Promise<ConnectorCommitResult>;
+ /** Cancels a pending approval, or a direct run (by its runId) still waiting on policy. */
+ connectorCancel?: (
+ actionId: string,
+ reason: ConnectorCancelReason
+ ) => Promise<{ cancelled: boolean }>;
+ connectorRunDirect?: (
+ connectorId: string,
+ action: string,
+ args: Record<string, unknown>,
+ runId?: string
+ ) => Promise<ConnectorDirectResult>;
+ connectorRecentActions?: (
+ connectorId: string,
+ limit?: number
+ ) => Promise<ConnectorActionRecord[]>;
+ connectorFindContacts?: (
+ query: string
+ ) => Promise<{ contacts: ContactMatch[]; hasMore?: boolean; unavailableReason?: string }>;
calendarGetAvailability?: (
request: CalendarAvailabilityRequest
) => Promise<
@@ -3132,11 +3171,16 @@ declare global {
onGcalEventsSynced?: (callback: (data: any) => void) => () => void;
// Microsoft Calendar
- mcalStartOAuth?: () => Promise<{ success: boolean; email?: string; error?: string }>;
+ mcalStartOAuth?: () => Promise<{
+ success: boolean;
+ email?: string;
+ tenantId?: string | null;
+ error?: string;
+ }>;
mcalDisconnect?: (email?: string) => Promise<{ success: boolean; error?: string }>;
mcalGetConnectionStatus?: () => Promise<{
connected: boolean;
- accounts: Array<{ email: string }>;
+ accounts: MicrosoftCalendarAccount[];
}>;
mcalSetPrimaryOnly?: (value: boolean) => Promise<{ success: boolean; error?: string }>;
onMcalConnectionChanged?: (callback: (data: any) => void) => () => void;
diff --git a/src/types/policy.ts b/src/types/policy.ts
index 57437b738..e48f70e68 100644
--- a/src/types/policy.ts
+++ b/src/types/policy.ts
@@ -36,6 +36,11 @@ export interface OrgPolicy {
webSearchEnabled: boolean;
/** Absent on servers that predate the field; absent means allowed. */
screenContextEnabled?: boolean;
+ /**
+ * Agent connectors (email drafts, Slack, Linear, GitHub). Absent on
+ * servers that predate the field; absent means allowed.
+ */
+ connectorsEnabled?: boolean;
/**
* Server-only Mem0 agent-memory gate, enforced by the API on
* `/api/agent/stream`; the app never reads it. Absent on older servers.
diff --git a/src/utils/connectorEligibility.ts b/src/utils/connectorEligibility.ts
new file mode 100644
index 000000000..eaa6811ee
--- /dev/null
+++ b/src/utils/connectorEligibility.ts
@@ -0,0 +1,12 @@
+import type { UsageState } from "../lib/usageStore";
+
+/**
+ * Connectors are paid-only (subscription or trial, like useUsage's
+ * hasPaidAccess). Usage data is only loaded while a surface mounts useUsage(),
+ * so other windows (the voice assistant) pass the persisted isSubscribed flag,
+ * which the API also sets for trials.
+ */
+export function hasConnectorPlan(usage: UsageState, isSubscribedFlag: boolean): boolean {
+ if (usage.status === "success") return usage.data.isSubscribed || usage.data.isTrial;
+ return isSubscribedFlag;
+}
diff --git a/src/utils/emailDraftTarget.ts b/src/utils/emailDraftTarget.ts
new file mode 100644
index 000000000..3c6f1bee7
--- /dev/null
+++ b/src/utils/emailDraftTarget.ts
@@ -0,0 +1,42 @@
+import { COMPOSE_TARGETS } from "../helpers/connectors/emailCompose";
+import type { MicrosoftCalendarAccount } from "../types/calendar";
+
+export const EMAIL_DRAFT_TARGETS = COMPOSE_TARGETS;
+export const EMAIL_DRAFT_TARGET_SETTINGS = ["auto", ...EMAIL_DRAFT_TARGETS] as const;
+
+export type EmailDraftTarget = (typeof EMAIL_DRAFT_TARGETS)[number];
+export type EmailDraftTargetSetting = (typeof EMAIL_DRAFT_TARGET_SETTINGS)[number];
+
+// Microsoft's fixed tenant for every consumer (outlook.com, hotmail) account.
+const PERSONAL_MICROSOFT_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
+
+// Accounts connected before the tenant was stored fall back to the domain.
+// Consumer accounts live on these brands under country domains too
+// (hotmail.de, outlook.fr, live.co.uk, outlook.com.br).
+const PERSONAL_MICROSOFT_DOMAIN =
+ /^(?:outlook|hotmail|live|msn|windowslive|passport)\.(?:com|net|[a-z]{2}|co\.[a-z]{2}|com\.[a-z]{2})$/;
+
+function isPersonalMicrosoftAccount({ email, tenantId }: MicrosoftCalendarAccount): boolean {
+ if (tenantId) return tenantId === PERSONAL_MICROSOFT_TENANT_ID;
+ return PERSONAL_MICROSOFT_DOMAIN.test(email.split("@")[1]?.toLowerCase() ?? "");
+}
+
+export function normalizeEmailDraftTarget(value: string): EmailDraftTargetSetting {
+ return (EMAIL_DRAFT_TARGET_SETTINGS as readonly string[]).includes(value)
+ ? (value as EmailDraftTargetSetting)
+ : "auto";
+}
+
+export function resolveEmailDraftTarget(context: {
+ emailDraftTarget: string;
+ gcalConnected: boolean;
+ mcalAccounts: MicrosoftCalendarAccount[];
+}): EmailDraftTarget {
+ const setting = normalizeEmailDraftTarget(context.emailDraftTarget);
+ if (setting !== "auto") return setting;
+ if (context.gcalConnected) return "gmail";
+ if (context.mcalAccounts.some((account) => !isPersonalMicrosoftAccount(account))) {
+ return "outlookWork";
+ }
+ return context.mcalAccounts.length > 0 ? "outlookPersonal" : "mailto";
+}
diff --git a/test/components/approvalCard.test.js b/test/components/approvalCard.test.js
new file mode 100644
index 000000000..853fab9b7
--- /dev/null
+++ b/test/components/approvalCard.test.js
@@ -0,0 +1,74 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createElement } = require("react");
+const { renderToStaticMarkup } = require("react-dom/server");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// The harness renders i18n keys verbatim, so assertions match keys.
+async function renderCard(t, entry) {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-approval-card-test-",
+ mockModules: {
+ "/ui/button": `
+ import React from "react";
+ export function Button(props) { return React.createElement("button", props); }
+ `,
+ },
+ });
+ const { ApprovalCard } = await vite.ssrLoadModule("/components/chat/ApprovalCard.tsx");
+ return renderToStaticMarkup(createElement(ApprovalCard, { entry }));
+}
+
+const PREVIEW = {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ workspaceLabel: "Acme",
+ body: "Quarterly numbers attached",
+};
+
+test("a pending card shows the exact content and Send, Edit, Cancel", async (t) => {
+ const markup = await renderCard(t, {
+ toolCallId: "call-1",
+ actionId: "a1",
+ connectorId: "slack",
+ preview: PREVIEW,
+ draft: { body: PREVIEW.body },
+ state: "pending",
+ });
+ assert.match(markup, /Quarterly numbers attached/);
+ assert.match(markup, /connectors\.approval\.headers\.default/);
+ assert.match(markup, /connectors\.approval\.identityWithWorkspace/);
+ assert.match(markup, /connectors\.approval\.send/);
+ assert.match(markup, /connectors\.approval\.edit/);
+ assert.match(markup, /connectors\.approval\.cancel/);
+ assert.doesNotMatch(markup, /autofocus/i);
+});
+
+test("an unknown outcome tells the user to check, with no retry", async (t) => {
+ const markup = await renderCard(t, {
+ toolCallId: "call-2",
+ actionId: "a2",
+ connectorId: "slack",
+ preview: PREVIEW,
+ draft: { body: PREVIEW.body },
+ state: "unknown",
+ });
+ assert.match(markup, /connectors\.approval\.unknown/);
+ assert.doesNotMatch(markup, /connectors\.approval\.send/);
+});
+
+test("a sent card offers Open", async (t) => {
+ const markup = await renderCard(t, {
+ toolCallId: "call-3",
+ actionId: "a3",
+ connectorId: "slack",
+ preview: PREVIEW,
+ draft: { body: PREVIEW.body },
+ state: "sent",
+ url: "https://slack.test/p/1",
+ });
+ assert.match(markup, /connectors\.approval\.sent/);
+ assert.match(markup, /connectors\.approval\.open/);
+});
diff --git a/test/components/approvalFlow.test.js b/test/components/approvalFlow.test.js
new file mode 100644
index 000000000..02cb34f34
--- /dev/null
+++ b/test/components/approvalFlow.test.js
@@ -0,0 +1,145 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");
+
+function click(element) {
+ element.dispatchEvent({
+ type: "click",
+ bubbles: true,
+ button: 0,
+ defaultPrevented: false,
+ cancelBubble: false,
+ preventDefault() {
+ this.defaultPrevented = true;
+ },
+ stopPropagation() {
+ this.cancelBubble = true;
+ },
+ });
+}
+
+// No i18next instance is initialized, so buttons render their keys.
+function button(root, label) {
+ const found = findElement(
+ root,
+ (element) => element.tagName === "BUTTON" && element.textContent === label
+ );
+ assert.ok(found, `button ${label} is rendered`);
+ return found;
+}
+
+// Mounts a card for a real runApprovalAction turn; returns what the test drives.
+async function mountApprovalTurn(t) {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+ const commits = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorPrepare: async () => ({
+ status: "ready",
+ actionId: "a1",
+ preview: {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ body: "Original text",
+ },
+ }),
+ connectorCommit: async (actionId, edits) => {
+ commits.push({ actionId, edits });
+ return { state: "sent", url: "https://slack.test/p/1" };
+ },
+ connectorCancel: async () => ({ cancelled: true }),
+ },
+ },
+ });
+ const container = installInteractiveDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-approval-flow-test-",
+ mockModules: {
+ // toolOutcome.ts localizes tool-step text through the app's i18n
+ // module, which would initialize react-i18next; keep keys as labels.
+ "/i18n": `export default { t: (key) => key };`,
+ "/ui/button": `
+ import React from "react";
+ export function Button(props) { return React.createElement("button", props); }
+ `,
+ },
+ });
+ const store = await vite.ssrLoadModule("/stores/connectorApprovalStore.ts");
+ const { runApprovalAction } = await vite.ssrLoadModule(
+ "/services/tools/connectors/runApprovalAction.ts"
+ );
+ const { ApprovalCard } = await vite.ssrLoadModule("/components/chat/ApprovalCard.tsx");
+ store.useConnectorApprovalStore.setState({ entries: {} });
+
+ function Harness() {
+ const entry = store.useConnectorApprovalStore((state) => state.entries["call-1"]);
+ return entry ? React.createElement(ApprovalCard, { entry }) : null;
+ }
+ const { createRoot } = require("react-dom/client");
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Harness)));
+
+ const controller = new AbortController();
+ let toolResult;
+ await React.act(async () => {
+ toolResult = runApprovalAction(
+ {
+ toolCallId: "call-1",
+ signal: controller.signal,
+ onApprovalRequested() {},
+ onHoldDelivery() {},
+ },
+ "slack",
+ "send_message",
+ { destination: "#eng", text: "Original text" }
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+ });
+ assert.match(container.textContent, /Original text/);
+ return { container, store, commits, toolResult };
+}
+
+test("Edit, change, Done editing, Send: the reviewed text is what gets sent", async (t) => {
+ const { container, store, commits, toolResult } = await mountApprovalTurn(t);
+ await React.act(async () => click(button(container, "connectors.approval.edit")));
+ // Editing must not lose the direction-detection the static view gets:
+ // an RTL draft opened for editing should still render right-to-left.
+ const bodyField = findElement(container, (element) => element.tagName === "TEXTAREA");
+ assert.ok(bodyField, "the body textarea is rendered in edit mode");
+ assert.equal(bodyField.getAttribute("dir"), "auto");
+ // What the textarea's onChange calls with the typed value.
+ await React.act(async () => store.updateApprovalDraft("call-1", { body: "Edited text" }));
+ await React.act(async () => click(button(container, "connectors.approval.doneEditing")));
+ assert.match(container.textContent, /Edited text/);
+ await React.act(async () => click(button(container, "connectors.approval.send")));
+
+ const result = await toolResult;
+ assert.deepEqual(commits, [{ actionId: "a1", edits: { body: "Edited text" } }]);
+ assert.equal(result.data.status, "sent");
+ assert.equal(result.data.finalText, "Edited text");
+ assert.match(container.textContent, /connectors\.approval\.sent/);
+});
+
+test("Send while editing commits the edit and leaves edit mode", async (t) => {
+ const { container, store, commits, toolResult } = await mountApprovalTurn(t);
+
+ await React.act(async () => click(button(container, "connectors.approval.edit")));
+ await React.act(async () => store.updateApprovalDraft("call-1", { body: "Edited text" }));
+ await React.act(async () => click(button(container, "connectors.approval.send")));
+ await toolResult;
+
+ assert.deepEqual(commits, [{ actionId: "a1", edits: { body: "Edited text" } }]);
+ // A boolean: a failing assert would otherwise try to print the fake DOM node.
+ assert.ok(
+ !findElement(container, (element) => element.tagName === "TEXTAREA"),
+ "the card left edit mode"
+ );
+ assert.match(container.textContent, /Edited text/);
+});
diff --git a/test/components/chatViewNewChat.test.js b/test/components/chatViewNewChat.test.js
new file mode 100644
index 000000000..418611032
--- /dev/null
+++ b/test/components/chatViewNewChat.test.js
@@ -0,0 +1,119 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+const { installInteractiveDom } = require("../lib/interactiveDom");
+
+// ChatView with its real message sender (and its submission lock), the
+// streaming hook replaced by one whose send stays pending until the test
+// settles it: a turn still waiting on a tool when the user starts a new chat.
+const MOCKS = {
+ "/useChatStreaming": `
+ import { useCallback, useState } from "react";
+ export function useChatStreaming(options) {
+ globalThis.__chatStreamingOptions = options;
+ const [agentState, setAgentState] = useState("idle");
+ const cancelStream = useCallback(() => {
+ globalThis.__cancelCount += 1;
+ setAgentState("idle");
+ }, []);
+ const sendToAI = useCallback(() => {
+ setAgentState("tool-executing");
+ return globalThis.__pendingSend;
+ }, []);
+ return { agentState, toolStatus: "", activeToolName: "", sendToAI, cancelStream };
+ }
+ `,
+ "/useChatPersistence": `
+ export function useChatPersistence() {
+ return {
+ conversationId: null,
+ messages: [],
+ setMessages() {},
+ createConversation: async () => 1,
+ saveUserMessage: async () => {},
+ saveAssistantMessage() {},
+ loadConversation: async () => {},
+ handleNewChat() {},
+ };
+ }
+ `,
+ "/ChatInput": `
+ export function ChatInput(props) {
+ globalThis.__chatInput = props;
+ return null;
+ }
+ `,
+ "/ConversationList": `
+ export default function ConversationList(props) {
+ globalThis.__conversationList = props;
+ return null;
+ }
+ `,
+ "/ChatMessages": `export function ChatMessages() { return null; }`,
+ "/ChatEmptyIllustration": `export function ChatEmptyIllustration() { return null; }`,
+ "/EmptyChatState": `export default function EmptyChatState() { return null; }`,
+ "/ui/dialog": `export function ConfirmDialog() { return null; }`,
+ "/hooks/useDialogs": `
+ export function useDialogs() {
+ return { confirmDialog: { open: false }, showConfirmDialog() {}, hideConfirmDialog() {} };
+ }
+ `,
+};
+
+async function renderChatView(t) {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__pendingSend;
+ delete globalThis.__chatInput;
+ delete globalThis.__conversationList;
+ delete globalThis.__cancelCount;
+ delete globalThis.__chatStreamingOptions;
+ });
+ installBrowserGlobals(t);
+ const container = installInteractiveDom(t);
+ globalThis.__cancelCount = 0;
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-chat-view-new-chat-test-",
+ mockModules: MOCKS,
+ });
+ const { default: ChatView } = await vite.ssrLoadModule("/components/chat/ChatView.tsx");
+ const { createRoot } = require("react-dom/client");
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(ChatView)));
+}
+
+test("typed chat offers the connector tools", async (t) => {
+ await renderChatView(t);
+ assert.equal(globalThis.__chatStreamingOptions.allowConnectors, true);
+});
+
+// Each way of leaving the conversation cancels its running reply.
+const LEAVE_CONVERSATION = {
+ "New chat": (list) => list.onNewChat(),
+ "switching conversation": (list) => list.onSelectConversation(7),
+};
+
+for (const [leave, leaveConversation] of Object.entries(LEAVE_CONVERSATION)) {
+ test(`${leave} cancels the reply, and the input stays busy until it lets go`, async (t) => {
+ let settleSend;
+ globalThis.__pendingSend = new Promise((resolve) => {
+ settleSend = resolve;
+ });
+ await renderChatView(t);
+
+ await React.act(async () => {
+ void globalThis.__chatInput.onTextSubmit("Search the web for flights");
+ });
+ await React.act(async () => leaveConversation(globalThis.__conversationList));
+
+ assert.equal(globalThis.__cancelCount, 1);
+ // The old send still holds the submission lock, so a message typed now
+ // would be dropped; the input must not look ready for one.
+ assert.notEqual(globalThis.__chatInput.agentState, "idle");
+
+ await React.act(async () => settleSend());
+ assert.equal(globalThis.__chatInput.agentState, "idle");
+ });
+}
diff --git a/test/components/connectorsSection.test.js b/test/components/connectorsSection.test.js
new file mode 100644
index 000000000..dfb6e022e
--- /dev/null
+++ b/test/components/connectorsSection.test.js
@@ -0,0 +1,245 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+
+const { createElement } = React;
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+const { findElement, installInteractiveDom } = require("../lib/interactiveDom");
+
+const MOCKS = {
+ "/stores/policyStore": `
+ export function usePolicyStore(selector) { return selector({}); }
+ `,
+ "/stores/policyRules": `
+ export function isConnectorsBlockedByOrg() { return globalThis.__connectorsBlocked; }
+ export function isConnectorsAllowed() { return globalThis.__connectorsAllowed; }
+ `,
+ "/stores/settingsStore": `
+ const state = {
+ isSignedIn: true,
+ emailDraftTarget: "auto",
+ setEmailDraftTarget() {},
+ gcalConnected: false,
+ mcalAccounts: [{ email: "[email protected]", tenantId: null }],
+ };
+ export function useSettingsStore(selector) { return selector(state); }
+ `,
+ "/lib/usageStore": `
+ export const getUsageState = () => globalThis.__usage;
+ export const subscribeUsage = () => () => {};
+ `,
+ "/lib/subscriptionFlag": `
+ export const readIsSubscribed = () => Boolean(globalThis.__subscribedFlag);
+ export const subscribeIsSubscribed = () => () => {};
+ `,
+ "react-i18next": `
+ const t = (key, options) => (options ? key + JSON.stringify(options) : key);
+ export const useTranslation = () => ({ t, i18n: { language: "en" } });
+ `,
+ "/ui/select": `
+ import React from "react";
+ const Pass = ({ children }) => React.createElement("div", null, children);
+ export const Select = Pass;
+ export const SelectContent = Pass;
+ export const SelectTrigger = Pass;
+ export const SelectValue = () => null;
+ export const SelectItem = ({ children }) => React.createElement("span", null, children);
+ `,
+ "/ui/button": `
+ import React from "react";
+ export function Button(props) { return React.createElement("button", props); }
+ `,
+};
+
+const usage = (isSubscribed) => ({
+ status: "success",
+ accountId: "acct",
+ data: { isSubscribed, isTrial: false },
+ isRefreshing: false,
+});
+
+// An org block is a resolved policy that disallows connectors, so it implies
+// not allowed; `allowed: false` alone is a policy that is loading or failed.
+function setPlan(t, { usageState, subscribedFlag = false, blocked = false, allowed = !blocked }) {
+ globalThis.__usage = usageState;
+ globalThis.__subscribedFlag = subscribedFlag;
+ globalThis.__connectorsBlocked = blocked;
+ globalThis.__connectorsAllowed = allowed;
+ t.after(() => {
+ delete globalThis.__usage;
+ delete globalThis.__subscribedFlag;
+ delete globalThis.__connectorsBlocked;
+ delete globalThis.__connectorsAllowed;
+ });
+}
+
+async function renderSection(t, plan, electronAPI = {}) {
+ // Registered first so it runs before the globals it needs are torn down.
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+ installBrowserGlobals(t, { window: { electronAPI } });
+ setPlan(t, plan);
+ const container = installInteractiveDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-connectors-section-test-",
+ noExternal: ["react-i18next"],
+ mockModules: MOCKS,
+ });
+ const { ConnectorsSection } = await vite.ssrLoadModule("/components/ConnectorsSection.tsx");
+ root = createRoot(container);
+ await React.act(async () => root.render(createElement(ConnectorsSection, { onUpgrade() {} })));
+ return container;
+}
+
+function listItems(container) {
+ const items = [];
+ const walk = (node) => {
+ if (node.tagName === "LI") items.push(node.textContent);
+ for (const child of node.childNodes ?? []) walk(child);
+ };
+ walk(container);
+ return items;
+}
+
+const receipt = (id, destinationLabel, state = "sent") => ({
+ id,
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ destinationLabel,
+ state,
+ resultUrl: null,
+ errorCode: null,
+ createdAt: "2026-09-24 10:00:00",
+});
+
+test("paid users choose where drafts open", async (t) => {
+ const { textContent } = await renderSection(t, { usageState: usage(true) });
+ assert.match(textContent, /connectors\.email\.title/);
+ assert.match(textContent, /connectors\.email\.targets\.gmail/);
+ assert.match(textContent, /connectors\.email\.description/);
+ assert.doesNotMatch(textContent, /integrations\.api\.viewPlans/);
+});
+
+test("automatic names the app it resolved to", async (t) => {
+ const { textContent } = await renderSection(t, { usageState: usage(true) });
+ assert.match(
+ textContent,
+ /connectors\.email\.autoResolved\{"target":"connectors\.email\.targets\.outlookWork"\}/
+ );
+});
+
+test("while usage is unknown, the card follows the saved flag like the chat does", async (t) => {
+ const loading = { status: "loading", accountId: "acct" };
+ const { textContent } = await renderSection(t, { usageState: loading, subscribedFlag: true });
+ assert.match(textContent, /connectors\.email\.description/);
+});
+
+test("while usage is unknown and the flag is unset, the card asks for a plan", async (t) => {
+ const loading = { status: "loading", accountId: "acct" };
+ const { textContent } = await renderSection(t, { usageState: loading, subscribedFlag: false });
+ assert.match(textContent, /connectors\.email\.proRequired/);
+});
+
+test("free users see that a paid plan is required and a View Plans button", async (t) => {
+ const container = await renderSection(t, { usageState: usage(false) });
+ // Matches the API card pattern (IntegrationsView.tsx): the description says
+ // a paid plan is required, and the CTA is the primary/filled button.
+ assert.match(container.textContent, /connectors\.email\.proRequired/);
+ assert.doesNotMatch(container.textContent, /connectors\.email\.description/);
+ assert.doesNotMatch(container.textContent, /connectors\.email\.targets\.gmail/);
+ const button = findElement(container, (node) => node.tagName === "BUTTON");
+ assert.match(button.textContent, /integrations\.api\.viewPlans/);
+ assert.equal(button.getAttribute("variant"), null);
+});
+
+test("an org that turned connectors off sees why, under the card's header", async (t) => {
+ const { textContent } = await renderSection(t, { usageState: usage(true), blocked: true });
+ assert.match(textContent, /connectors\.email\.title/);
+ assert.match(textContent, /connectors\.policyOff/);
+ assert.doesNotMatch(textContent, /connectors\.email\.targets/);
+ assert.doesNotMatch(textContent, /integrations\.api\.viewPlans/);
+});
+
+test("while the policy is unresolved, the card says drafts are unavailable", async (t) => {
+ let fetches = 0;
+ const container = await renderSection(
+ t,
+ { usageState: usage(true), allowed: false },
+ {
+ connectorRecentActions: async () => {
+ fetches += 1;
+ return [receipt("a", "[email protected]")];
+ },
+ }
+ );
+ assert.match(container.textContent, /connectors\.email\.unavailable/);
+ assert.doesNotMatch(container.textContent, /connectors\.email\.description/);
+ assert.doesNotMatch(container.textContent, /connectors\.email\.targets/);
+ assert.doesNotMatch(container.textContent, /connectors\.policyOff/);
+ assert.doesNotMatch(container.textContent, /integrations\.api\.viewPlans/);
+ assert.equal(fetches, 0);
+});
+
+test("an unresolved policy doesn't hide the upsell from a free user", async (t) => {
+ const { textContent } = await renderSection(t, { usageState: usage(false), allowed: false });
+ assert.match(textContent, /connectors\.email\.proRequired/);
+ assert.match(textContent, /integrations\.api\.viewPlans/);
+});
+
+test("a change of main's account scope clears and refetches the receipts", async (t) => {
+ let onScopeChanged = null;
+ let answerSecondFetch = null;
+ const answers = [
+ Promise.resolve([receipt("a", "[email protected]")]),
+ new Promise((resolve) => {
+ answerSecondFetch = resolve;
+ }),
+ ];
+ let fetches = 0;
+ const container = await renderSection(
+ t,
+ { usageState: usage(true) },
+ {
+ onActiveAccountScopeChanged: (callback) => {
+ onScopeChanged = callback;
+ return () => {
+ onScopeChanged = null;
+ };
+ },
+ connectorRecentActions: () => answers[fetches++],
+ }
+ );
+ assert.match(listItems(container).join(), /first@example\.com/);
+
+ assert.equal(typeof onScopeChanged, "function");
+ await React.act(async () => onScopeChanged({ accountId: "acct-b", authGeneration: 2 }));
+ assert.equal(fetches, 2);
+ assert.deepEqual(listItems(container), []);
+
+ await React.act(async () => answerSecondFetch([receipt("b", "[email protected]")]));
+ const items = listItems(container);
+ assert.equal(items.length, 1);
+ assert.match(items[0], /second@example\.com/);
+});
+
+test("recent receipts name the recipient, or the action when a quit cut it short", async (t) => {
+ const container = await renderSection(
+ t,
+ { usageState: usage(true) },
+ {
+ connectorRecentActions: async () => [
+ receipt("a", "[email protected]", "failed"),
+ receipt("b", null, "unknown"),
+ ],
+ }
+ );
+
+ const items = listItems(container);
+ assert.equal(items.length, 2);
+ assert.match(items[0], /^connectors\.recent\.actions\.email_draft/);
+ assert.match(items[1], /^connectors\.recent\.unlabeledActions\.email_draft/);
+});
diff --git a/test/components/fieldDirectionPolicy.test.js b/test/components/fieldDirectionPolicy.test.js
index 4e25f196a..5b237abad 100644
--- a/test/components/fieldDirectionPolicy.test.js
+++ b/test/components/fieldDirectionPolicy.test.js
@@ -91,6 +91,7 @@ const EXPECTED_NATIVE_FIELD_DIRECTIONS = {
"src/components/MemberPickList.tsx": ["auto"],
"src/components/ReferralDashboard.tsx": ["ltr"],
"src/components/SettingsPage.tsx": ["inherit"],
+ "src/components/chat/ApprovalCard.tsx": ["auto", "auto"],
"src/components/chat/ChatInput.tsx": ["auto"],
"src/components/notes/ActionManagerDialog.tsx": ["auto"],
"src/components/notes/AddNotesToFolderDialog.tsx": ["auto"],
diff --git a/test/helpers/accountOwnershipDatabase.test.js b/test/helpers/accountOwnershipDatabase.test.js
index b813578b3..362900818 100644
--- a/test/helpers/accountOwnershipDatabase.test.js
+++ b/test/helpers/accountOwnershipDatabase.test.js
@@ -94,6 +94,10 @@ function createDatabaseManager() {
account_id TEXT PRIMARY KEY,
cleared_through TEXT NOT NULL
);
+ CREATE TABLE connector_actions (
+ id TEXT PRIMARY KEY,
+ account_id TEXT
+ );
INSERT INTO spaces (id, kind) VALUES (1, 'private'), (2, 'team'), (3, 'team');
INSERT INTO space_accounts (space_id, account_id) VALUES
(2, 'account-a'),
@@ -105,6 +109,9 @@ function createDatabaseManager() {
INSERT INTO analytics_clear_requests (account_id, cleared_through) VALUES
('account-a', '2026-08-30T10:00:00.000Z'),
('account-b', '2026-08-30T10:00:00.000Z');
+ INSERT INTO connector_actions (id, account_id) VALUES
+ ('action-a', 'account-a'),
+ ('action-b', 'account-b');
`);
const manager = Object.create(DatabaseManager.prototype);
@@ -278,6 +285,13 @@ test("deleting one account removes only its personal rows and dependent private
.map((row) => row.account_id),
["account-b"]
);
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT id FROM connector_actions ORDER BY id")
+ .all()
+ .map((row) => row.id),
+ ["action-b"]
+ );
});
test("account deletion refuses to target an account outside the active scope", (t) => {
diff --git a/test/helpers/appleCalendarManager.test.js b/test/helpers/appleCalendarManager.test.js
index 91cc226b8..19d3b69a0 100644
--- a/test/helpers/appleCalendarManager.test.js
+++ b/test/helpers/appleCalendarManager.test.js
@@ -104,3 +104,73 @@ test("_mapEvent preserves EventKit availability and the current user's response"
assert.equal(mapped.availability_status, "free");
assert.equal(mapped.self_response_status, "declined");
});
+
+test("rooms and resources are flagged in attendees and kept, with the user, out of contacts", () => {
+ const AppleCalendarManager = loadManager();
+ const saved = [];
+ const synced = [];
+ const manager = new AppleCalendarManager(
+ {
+ saveAppleCalendars: () => {},
+ replaceAppleCalendarEvents: (events) => saved.push(...events),
+ syncCalendarContacts: (...args) => synced.push(args),
+ },
+ { reconcileProvider: () => {}, scheduleNextMeeting: () => {} }
+ );
+
+ manager._applySnapshot({
+ calendars: [{ id: "calendar-1" }],
+ events: [
+ {
+ id: "evt-room",
+ calendar_id: "calendar-1",
+ start: "2026-08-14T10:00:00Z",
+ end: "2026-08-14T10:30:00Z",
+ is_all_day: false,
+ status: "confirmed",
+ attendees: [
+ { email: "[email protected]", name: "Ana", status: "accepted", self: false },
+ {
+ email: "[email protected]",
+ name: "Boardroom",
+ status: "accepted",
+ self: false,
+ resource: true,
+ },
+ { email: "[email protected]", name: "Me", status: "accepted", self: true },
+ ],
+ },
+ ],
+ });
+
+ const attendees = JSON.parse(saved[0].attendees);
+ assert.equal(attendees[0].resource, undefined);
+ assert.equal(attendees[1].resource, true);
+ // Rows older builds stored for the room and the user are purged.
+ assert.deepEqual(synced, [
+ [
+ "apple",
+ null,
+ [{ email: "[email protected]", displayName: "Ana" }],
+ ],
+ ]);
+});
+
+test("_mapEvent drops the organizer address only when the user organized the event", () => {
+ const AppleCalendarManager = loadManager();
+ const manager = new AppleCalendarManager({}, {});
+ const event = {
+ id: "evt-organizer",
+ calendar_id: "calendar-1",
+ start: "2026-08-14T10:00:00Z",
+ end: "2026-08-14T10:30:00Z",
+ is_all_day: false,
+ status: "confirmed",
+ organizer_email: "[email protected]",
+ attendees: [{ email: "[email protected]", status: "accepted", self: false }],
+ };
+
+ assert.equal(manager._mapEvent({ ...event, organizer_self: true }).organizer_email, null);
+ assert.equal(manager._mapEvent(event).organizer_email, "[email protected]");
+});
diff --git a/test/helpers/assistantCommandOptions.test.js b/test/helpers/assistantCommandOptions.test.js
new file mode 100644
index 000000000..4611dedba
--- /dev/null
+++ b/test/helpers/assistantCommandOptions.test.js
@@ -0,0 +1,168 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/components/dictation/assistantCommandOptions.ts");
+
+const PASTE = {
+ mode: "paste",
+ sessionId: "s",
+ restoreClipboard: true,
+ allowClipboardFallback: false,
+};
+// Keep Transcription in Clipboard on: the caret delivery may leave the answer there.
+const PASTE_KEEPING_ANSWER = { ...PASTE, restoreClipboard: false };
+
+function handlers(deliverResult = { pasted: true, copied: false }) {
+ const calls = { opened: 0, delivered: [], copied: [] };
+ return {
+ calls,
+ value: {
+ onResponseContent: () => {
+ calls.opened += 1;
+ },
+ deliver: async (delivery, content) => {
+ calls.delivered.push({ delivery, content });
+ return delivery.mode === "paste" ? deliverResult : { pasted: false, copied: true };
+ },
+ confirmCopied: (content) => calls.copied.push(content),
+ },
+ };
+}
+
+test("a caret-delivered command pastes its answer when no approval was needed", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery: PASTE },
+ h.value
+ );
+
+ assert.equal(built.options.suppressResponseContent, true);
+ await built.options.onComplete({ assistantId: "a", content: "Answer" });
+
+ assert.equal(h.calls.delivered.length, 1);
+ assert.equal(built.wasDelivered(), true);
+});
+
+test("an approval opens the hidden panel and cancels caret delivery", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery: PASTE_KEEPING_ANSWER },
+ h.value
+ );
+
+ built.options.onApprovalRequested();
+ await built.options.onComplete({ assistantId: "a", content: "Posted to #eng" });
+
+ assert.equal(h.calls.opened, 1);
+ assert.deepEqual(h.calls.delivered, [
+ { delivery: { mode: "clipboard" }, content: "Posted to #eng" },
+ ]);
+ assert.equal(built.wasDelivered(), false);
+});
+
+test("a held answer stays in the panel and is copied instead of pasted", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ for (const delivery of [PASTE_KEEPING_ANSWER, { mode: "clipboard" }]) {
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery },
+ h.value
+ );
+
+ built.options.onHoldDelivery();
+ await built.options.onComplete({ assistantId: "a", content: "Dana is [email protected]." });
+
+ assert.equal(h.calls.opened, 1, delivery.mode);
+ assert.deepEqual(
+ h.calls.delivered,
+ [{ delivery: { mode: "clipboard" }, content: "Dana is [email protected]." }],
+ delivery.mode
+ );
+ assert.deepEqual(h.calls.copied, ["Dana is [email protected]."], delivery.mode);
+ assert.equal(built.wasDelivered(), false, delivery.mode);
+ }
+});
+
+test("a held caret answer leaves the clipboard alone when the delivery would restore it", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ for (const hold of ["onHoldDelivery", "onApprovalRequested"]) {
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery: PASTE },
+ h.value
+ );
+
+ built.options[hold]();
+ await built.options.onComplete({ assistantId: "a", content: "Which Dana did you mean?" });
+
+ assert.equal(h.calls.opened, 1, hold);
+ assert.equal(h.calls.delivered.length, 0, hold);
+ assert.equal(h.calls.copied.length, 0, hold);
+ assert.equal(built.wasDelivered(), false, hold);
+ }
+});
+
+test("the command's screenshot and selection ride along with the send", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ const attachment = { image: "base64", mediaType: "image/jpeg" };
+ const selectedContext = { text: "selected words", sourceMessageId: "m1" };
+ for (const delivery of [PASTE, { mode: "clipboard" }, null]) {
+ const built = buildAssistantCommandSendOptions(
+ { attachment, selectedContext, delivery },
+ handlers().value
+ );
+
+ assert.equal(built.options.attachment, attachment);
+ assert.equal(built.options.selectedContext, selectedContext);
+ }
+});
+
+test("a hold that preserves the clipboard neither pastes nor copies", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ for (const delivery of [PASTE, { mode: "clipboard" }]) {
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery },
+ h.value
+ );
+
+ // A later plain hold in the same turn must not undo the preserve.
+ built.options.onHoldDelivery({ preserveClipboard: true });
+ built.options.onHoldDelivery();
+ await built.options.onComplete({ assistantId: "a", content: "Draft opened; paste the body." });
+
+ assert.equal(h.calls.delivered.length, 0, delivery.mode);
+ assert.equal(h.calls.copied.length, 0, delivery.mode);
+ assert.equal(built.wasDelivered(), false, delivery.mode);
+ }
+});
+
+test("a caret answer that falls back to the clipboard confirms the copy", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ const h = handlers({ pasted: false, copied: true });
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery: PASTE },
+ h.value
+ );
+
+ await built.options.onComplete({ assistantId: "a", content: "Answer" });
+
+ assert.deepEqual(h.calls.copied, ["Answer"]);
+ assert.equal(built.wasDelivered(), false);
+});
+
+test("a panel command still opens for an approval and has no delivery hook", async () => {
+ const { buildAssistantCommandSendOptions } = await load();
+ const h = handlers();
+ const built = buildAssistantCommandSendOptions(
+ { attachment: null, selectedContext: null, delivery: null },
+ h.value
+ );
+
+ assert.equal(built.options.onComplete, undefined);
+ assert.equal(built.options.suppressResponseContent, false);
+ built.options.onApprovalRequested();
+ assert.equal(h.calls.opened, 1);
+});
diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.js
index 2f2159643..339d8aae6 100644
--- a/test/helpers/assistantPanel.test.js
+++ b/test/helpers/assistantPanel.test.js
@@ -13,16 +13,25 @@ const { installInteractiveDom, findElement } = require("../lib/interactiveDom");
async function renderAssistantPanel(
t,
messages,
- { initialConversationId = null, agentState = "idle", activeToolName = null, locale = "en" } = {}
+ {
+ initialConversationId = null,
+ agentState = "idle",
+ activeToolName = null,
+ locale = "en",
+ approvals = {},
+ } = {}
) {
installBrowserGlobals(t);
globalThis.__assistantPanelMessages = messages;
globalThis.__assistantPanelAgentState = agentState;
globalThis.__assistantPanelActiveToolName = activeToolName;
+ globalThis.__assistantPanelApprovals = approvals;
t.after(() => {
delete globalThis.__assistantPanelMessages;
delete globalThis.__assistantPanelAgentState;
delete globalThis.__assistantPanelActiveToolName;
+ delete globalThis.__assistantPanelApprovals;
+ delete globalThis.__assistantPanelStreamingOptions;
});
const vite = await createRendererServer(t, {
@@ -43,7 +52,8 @@ async function renderAssistantPanel(
}
`,
"/chat/useChatStreaming": `
- export function useChatStreaming() {
+ export function useChatStreaming(options) {
+ globalThis.__assistantPanelStreamingOptions = options;
return {
agentState: globalThis.__assistantPanelAgentState,
activeToolName: globalThis.__assistantPanelActiveToolName,
@@ -84,6 +94,17 @@ async function renderAssistantPanel(
"/ui/useToast": `
export function useToast() { return { toast() {} }; }
`,
+ "/stores/connectorApprovalStore": `
+ export function useConnectorApprovalStore(selector) {
+ return selector({ entries: globalThis.__assistantPanelApprovals || {} });
+ }
+ `,
+ "/chat/ApprovalCard": `
+ import React from "react";
+ export function ApprovalCard({ entry }) {
+ return React.createElement("div", { "data-approval-card": entry.toolCallId, "data-state": entry.state });
+ }
+ `,
},
});
const [{ default: viteI18next }, { initReactI18next }] = await Promise.all([
@@ -692,6 +713,102 @@ test("a follow-up into an open panel strips caret delivery and stays panel-first
assert.deepEqual(assistant.pendingCommand.delivery, delivery);
});
+test("spoken commands answer on the Voice Assistant scope with connector tools offered", async (t) => {
+ await renderAssistantPanel(t, []);
+
+ const options = globalThis.__assistantPanelStreamingOptions;
+ assert.equal(options.inferenceScope, "dictationAgent");
+ assert.equal(options.allowConnectors, true);
+});
+
+test("a pending approval shows in the panel and replaces the tool overlay", async (t) => {
+ const markup = await renderAssistantPanel(
+ t,
+ [
+ { id: "user-1", role: "user", content: "post the summary to eng", isStreaming: false },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "",
+ isStreaming: true,
+ toolCalls: [
+ { id: "call-1", name: "slack_send_message", arguments: "{}", status: "executing" },
+ ],
+ },
+ ],
+ {
+ agentState: "tool-executing",
+ activeToolName: "slack_send_message",
+ approvals: {
+ "call-1": {
+ toolCallId: "call-1",
+ actionId: "a1",
+ connectorId: "slack",
+ state: "pending",
+ preview: {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ body: "x",
+ },
+ },
+ },
+ }
+ );
+
+ assert.match(markup, /data-approval-card="call-1"/);
+ assert.doesNotMatch(markup, /data-tool-invocation=/);
+});
+
+test("an approval request opens the hidden panel of a caret-delivered command", async (t) => {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ });
+ installBrowserGlobals(t);
+ const container = installInteractiveDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-assistant-approval-open-test-",
+ });
+ const { useAssistantPanel } = await vite.ssrLoadModule("/hooks/useAssistantPanel.js");
+ const { createRoot } = require("react-dom/client");
+ let assistant;
+
+ function Harness() {
+ assistant = useAssistantPanel({
+ requestMainWindowSize: async () => ({ success: true }),
+ dictationErrorActionCount: 0,
+ recordingControlsRef: { current: null },
+ });
+ return null;
+ }
+
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Harness)));
+ await React.act(async () => {
+ assistant.handleCommand({
+ text: "post the summary to eng",
+ attachment: null,
+ selectedContext: null,
+ delivery: {
+ mode: "paste",
+ sessionId: "caret-session",
+ restoreClipboard: true,
+ allowClipboardFallback: false,
+ },
+ });
+ });
+ assert.equal(assistant.open, false);
+
+ // onApprovalRequested routes to the panel's onResponseContent handler.
+ await React.act(async () => {
+ assistant.handleResponseContent();
+ });
+
+ assert.equal(assistant.openRef.current, true);
+ assert.equal(assistant.thinking, false);
+});
+
test("only a plain-text caret delivery asks the model for plain prose", async (t) => {
let root = null;
t.after(async () => {
diff --git a/test/helpers/calendarDatabase.test.js b/test/helpers/calendarDatabase.test.js
index 89e490f08..a812a846e 100644
--- a/test/helpers/calendarDatabase.test.js
+++ b/test/helpers/calendarDatabase.test.js
@@ -248,7 +248,8 @@ test("reopening a pre-v2 database clears microsoft sync tokens once", (t) => {
.get();
assert.equal(calendar.sync_token, null);
assert.equal(calendar.sync_token_expires_at, null);
- assert.equal(reopened.db.pragma("user_version", { simple: true }), 2);
+ // Reopening runs every later migration too.
+ assert.equal(reopened.db.pragma("user_version", { simple: true }), 3);
reopened.db.close();
});
diff --git a/test/helpers/connectorActionsDatabase.test.js b/test/helpers/connectorActionsDatabase.test.js
new file mode 100644
index 000000000..a98714cc9
--- /dev/null
+++ b/test/helpers/connectorActionsDatabase.test.js
@@ -0,0 +1,621 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-connector-actions-db-"));
+const originalLoad = Module._load;
+
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: {
+ getPath: () => userDataDir,
+ getAppPath: () => process.cwd(),
+ isReady: () => false,
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+process.env.NODE_ENV = "test";
+
+const DatabaseManager = require("../../src/helpers/database.js");
+const { createActionLog } = require("../../src/helpers/connectors/actionLog.js");
+
+function isNativeBindingUnavailable(error) {
+ const message = String(error?.message || error);
+ return (
+ message.includes("NODE_MODULE_VERSION") ||
+ message.includes("Could not locate the bindings file")
+ );
+}
+
+function createDb(t) {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-connector-actions-db-"));
+ try {
+ const db = new DatabaseManager();
+ db.setActiveAccountId("account-a");
+ return db;
+ } catch (error) {
+ if (isNativeBindingUnavailable(error)) {
+ t.skip("better-sqlite3 native binding is not available for this Node runtime");
+ return null;
+ }
+ throw error;
+ }
+}
+
+test("an action row moves through its states and lists newest first", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+
+ log.insert({
+ id: "a1",
+ accountId: "account-a",
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ destinationLabel: "[email protected]",
+ state: "sent",
+ });
+ log.insert({
+ id: "a2",
+ accountId: "account-a",
+ connector: "slack",
+ action: "send_message",
+ kind: "approval",
+ destinationLabel: "#eng",
+ state: "pending",
+ });
+ log.update("a2", { state: "committing" });
+ log.update("a2", { state: "sent", resultUrl: "https://slack.test/p/1" });
+
+ const [row] = log.listRecent("slack", 10, "account-a");
+ assert.equal(row.id, "a2");
+ assert.equal(row.state, "sent");
+ assert.equal(row.resultUrl, "https://slack.test/p/1");
+ assert.equal(row.destinationLabel, "#eng");
+ assert.equal(log.listRecent("email", 10, "account-a")[0].kind, "direct");
+ db.db.close();
+});
+
+test("rows interrupted by a quit are reconciled on the next launch", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+ log.insert({
+ id: "p1",
+ accountId: "account-a",
+ connector: "slack",
+ action: "send_message",
+ kind: "approval",
+ state: "pending",
+ });
+ log.insert({
+ id: "c1",
+ accountId: "account-a",
+ connector: "slack",
+ action: "send_message",
+ kind: "approval",
+ state: "committing",
+ });
+ log.insert({
+ id: "s1",
+ accountId: "account-a",
+ connector: "slack",
+ action: "send_message",
+ kind: "approval",
+ state: "sent",
+ });
+
+ assert.deepEqual(log.reconcileInterrupted(), { unknown: 1, cancelled: 1, orphaned: 0 });
+
+ const states = Object.fromEntries(
+ log.listRecent("slack", 10, "account-a").map((row) => [row.id, row])
+ );
+ assert.equal(states.c1.state, "unknown");
+ assert.equal(states.c1.errorCode, "app_quit");
+ assert.equal(states.p1.state, "cancelled");
+ assert.equal(states.s1.state, "sent");
+ db.db.close();
+});
+
+test("a guarded update only moves a row out of the expected state", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+ log.insert({
+ id: "g1",
+ accountId: "account-a",
+ connector: "slack",
+ action: "send_message",
+ kind: "approval",
+ state: "pending",
+ });
+
+ assert.equal(log.update("g1", { state: "committing" }, "pending"), 1);
+ assert.equal(log.update("g1", { state: "committing" }, "pending"), 0);
+ assert.equal(log.update("missing", { state: "committing" }, "pending"), 0);
+ assert.equal(log.update("g1", { state: "sent" }), 1);
+ db.db.close();
+});
+
+test("a receipt belongs to the account it names, whatever the database scope says", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+ const draft = (id, accountId, destinationLabel) =>
+ log.insert({
+ id,
+ accountId,
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ destinationLabel,
+ state: "sent",
+ });
+
+ draft("a1", "account-a", "[email protected]");
+ // The A -> B gap: B's credential is in use, the database scope still says A.
+ draft("b1", "account-b", "[email protected]");
+ // The null-scope gap: signed in as B, database scope not synced yet.
+ db.setActiveAccountId(null);
+ draft("b2", "account-b", "[email protected]");
+
+ db.setActiveAccountId("account-a");
+ assert.deepEqual(
+ log.listRecent("email", 10, "account-a").map((row) => row.id),
+ ["a1"]
+ );
+ assert.deepEqual(
+ log.listRecent("email", 10, "account-b").map((row) => row.id),
+ ["b2", "b1"]
+ );
+ assert.deepEqual(log.listRecent("email", 10, null), []);
+
+ db.deleteAccountData("account-a");
+ assert.deepEqual(log.listRecent("email", 10, "account-a"), []);
+ assert.equal(log.listRecent("email", 10, "account-b").length, 2);
+ db.db.close();
+});
+
+test("receipts with no account are removed on launch", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+ log.insert({
+ id: "legacy",
+ accountId: null,
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ state: "sent",
+ });
+ log.insert({
+ id: "kept",
+ accountId: "account-a",
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ state: "sent",
+ });
+
+ assert.deepEqual(log.reconcileInterrupted(), { unknown: 0, cancelled: 0, orphaned: 1 });
+ assert.deepEqual(
+ db.db
+ .prepare("SELECT id FROM connector_actions")
+ .all()
+ .map((row) => row.id),
+ ["kept"]
+ );
+ db.db.close();
+});
+
+test("listRecent respects the limit", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const log = createActionLog(db);
+ for (let i = 0; i < 5; i += 1) {
+ log.insert({
+ id: `e${i}`,
+ accountId: "account-a",
+ connector: "email",
+ action: "draft",
+ kind: "direct",
+ state: "sent",
+ });
+ }
+ assert.equal(log.listRecent("email", 3, "account-a").length, 3);
+ db.db.close();
+});
+
+test("contact lookup sources cover meetings, synced contacts and the user's accounts", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const event = (id, startTime, organizer) => ({
+ id,
+ calendar_id: "primary",
+ provider: "google",
+ summary: "Lunch",
+ start_time: startTime,
+ end_time: startTime,
+ is_all_day: false,
+ status: "confirmed",
+ organizer_email: organizer,
+ attendees_count: 1,
+ attendees: JSON.stringify([{ email: organizer, displayName: "Someone", self: false }]),
+ });
+ const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString();
+ const later = new Date(Date.now() + 20 * 24 * 60 * 60 * 1000).toISOString();
+ db.upsertCalendarEvents([
+ event("evt-later", later, "[email protected]"),
+ event("evt-soon", soon, "[email protected]"),
+ // A meeting the user never had can't count as meeting anyone.
+ { ...event("evt-cancelled", soon, "[email protected]"), status: "cancelled" },
+ { ...event("evt-declined", soon, "[email protected]"), self_response_status: "declined" },
+ ]);
+ db.upsertContacts([{ email: "[email protected]", displayName: "Priya Shah" }], "manual");
+ db.saveGoogleCalendars(
+ [{ id: "primary", summary: "Chad", is_primary: true }],
+ );
+ db.saveMicrosoftCalendars([{ id: "work", summary: "Calendar" }], "[email protected]");
+
+ const sources = db.getContactLookupSources();
+
+ // The meetings nearest to now come first, so a limit keeps the relevant ones.
+ assert.deepEqual(
+ sources.meetings.map((row) => row.organizer_email),
+ );
+ assert.match(sources.meetings[0].attendees, /Someone/);
+ assert.deepEqual(sources.contacts, [{ email: "[email protected]", display_name: "Priya Shah" }]);
+ assert.deepEqual([...sources.excludedEmails].sort(), ["[email protected]", "[email protected]"]);
+ db.db.close();
+});
+
+test("contacts come most recently synced first, and a sync purges the addresses it keeps out", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveAppleCalendars([{ id: "a-cal", title: "Home" }]);
+ db.syncCalendarContacts(
+ "apple",
+ null,
+ [
+ { email: "[email protected]", displayName: "Josh Old" },
+ { email: "[email protected]", displayName: "Josh New" },
+ ],
+ []
+ );
+ db.db
+ .prepare("UPDATE contacts SET updated_at = '2020-01-01 00:00:00' WHERE email = ?")
+
+ assert.deepEqual(
+ db.getContactLookupSources().contacts.map((row) => row.email),
+ );
+ db.syncCalendarContacts("apple", null, [], ["[email protected]"]);
+ assert.deepEqual(
+ db.getContactLookupSources().contacts.map((row) => row.email),
+ );
+ db.db.close();
+});
+
+test("only meetings on the user's own selected calendars count", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars(
+ [
+ { id: "[email protected]", summary: "Me" },
+ { id: "[email protected]", summary: "Dana" },
+ { id: "[email protected]", summary: "Team" },
+ ],
+ );
+ db.updateCalendarSelection("[email protected]", false);
+ db.saveMicrosoftCalendars([{ id: "work", summary: "Calendar" }], "[email protected]");
+ db.saveAppleCalendars([{ id: "home", title: "Home" }]);
+ const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString();
+ const event = (id, provider, calendarId) => ({
+ id,
+ calendar_id: calendarId,
+ provider,
+ start_time: soon,
+ end_time: soon,
+ is_all_day: false,
+ status: "confirmed",
+ organizer_email: `${id}@example.com`,
+ attendees_count: 0,
+ attendees: null,
+ });
+ db.upsertCalendarEvents([
+ event("own", "google", "[email protected]"),
+ // A colleague's shared calendar: its people come through contacts.
+ event("shared", "google", "[email protected]"),
+ event("deselected", "google", "[email protected]"),
+ // Left behind by a sync that finished after its account was disconnected.
+ event("orphan", "google", "[email protected]"),
+ event("work", "microsoft", "work"),
+ event("home", "apple", "home"),
+ event("removed", "apple", "removed-calendar"),
+ ]);
+
+ assert.deepEqual(
+ db
+ .getContactLookupSources()
+ .meetings.map((row) => row.organizer_email)
+ .sort(),
+ );
+ db.db.close();
+});
+
+function storedContactEmails(db) {
+ return db.db
+ .prepare("SELECT email FROM contacts ORDER BY email")
+ .all()
+ .map((row) => row.email);
+}
+
+test("contact lookup only sees hand-added contacts and connected accounts' contacts", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars([{ id: "g-cal", summary: "Me" }], "[email protected]");
+ db.saveMicrosoftCalendars([{ id: "m-cal", summary: "Calendar" }], "[email protected]");
+ db.saveAppleCalendars([{ id: "a-cal", title: "Home" }]);
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("microsoft", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("apple", null, [{ email: "[email protected]" }], []);
+ db.upsertContacts([{ email: "[email protected]" }], "manual");
+ // Synced by both accounts.
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("microsoft", "[email protected]", [{ email: "[email protected]" }], []);
+ // Stored by an older build, before contacts had a source.
+ db.db
+ .prepare("INSERT INTO contacts (email, display_name) VALUES (?, ?)")
+ .run("[email protected]", "Lincoln Room");
+
+ const lookup = () =>
+ db
+ .getContactLookupSources()
+ .contacts.map((row) => row.email)
+ .sort();
+ assert.deepEqual(lookup(), [
+ ]);
+ // Note-participant autocomplete still offers the legacy row.
+ assert.equal(db.searchContacts("lincoln").length, 1);
+
+ const stored = () => storedContactEmails(db);
+ db.removeGoogleAccount("[email protected]");
+ assert.deepEqual(stored(), [
+ ]);
+ db.removeMicrosoftAccount("[email protected]");
+ db.clearAppleCalendarData();
+ assert.deepEqual(stored(), ["[email protected]", "[email protected]"]);
+ assert.deepEqual(lookup(), ["[email protected]"]);
+ // A snapshot that lands after the disconnect still isn't a connected account.
+ db.syncCalendarContacts("apple", null, [{ email: "[email protected]" }], []);
+ assert.deepEqual(lookup(), ["[email protected]"]);
+ db.db.close();
+});
+
+test("clearing a provider removes every one of its accounts' contacts", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("microsoft", "[email protected]", [{ email: "[email protected]" }], []);
+ db.syncCalendarContacts("microsoft", "[email protected]", [{ email: "[email protected]" }], []);
+ db.upsertContacts([{ email: "[email protected]" }], "manual");
+
+ db.clearGoogleCalendarData();
+ assert.deepEqual(storedContactEmails(db), [
+ ]);
+ db.clearMicrosoftCalendarData();
+ assert.deepEqual(storedContactEmails(db), ["[email protected]"]);
+ db.db.close();
+});
+
+test("a hand-added contact stays the user's when a calendar later syncs it", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars([{ id: "g-cal", summary: "Me" }], "[email protected]");
+ db.upsertContacts([{ email: "[email protected]" }], "manual");
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+
+ db.removeGoogleAccount("[email protected]");
+ assert.deepEqual(storedContactEmails(db), ["[email protected]"]);
+ assert.deepEqual(
+ db.getContactLookupSources().contacts.map((row) => row.email),
+ );
+ db.db.close();
+});
+
+test("a contact another source still has survives a disconnect", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars([{ id: "g-cal", summary: "Me" }], "[email protected]");
+ db.saveMicrosoftCalendars([{ id: "m-cal", summary: "Calendar" }], "[email protected]");
+ db.saveAppleCalendars([{ id: "a-cal", title: "Me (Google)" }]);
+ const josh = [{ email: "[email protected]", displayName: "Josh" }];
+ // Calendar.app mirrors the Google account, and a Microsoft account has him too.
+ db.syncCalendarContacts("google", "[email protected]", josh, []);
+ db.syncCalendarContacts("apple", null, josh, []);
+ db.syncCalendarContacts("microsoft", "[email protected]", josh, []);
+ const lookup = () => db.getContactLookupSources().contacts.map((row) => row.email);
+
+ db.clearAppleCalendarData();
+ assert.deepEqual(lookup(), ["[email protected]"]);
+ db.removeMicrosoftAccount("[email protected]");
+ assert.deepEqual(lookup(), ["[email protected]"]);
+ db.removeGoogleAccount("[email protected]");
+ assert.deepEqual(storedContactEmails(db), []);
+ db.db.close();
+});
+
+test("picking a stored contact for a note doesn't make it a hand-added one", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars([{ id: "g-cal", summary: "Me" }], "[email protected]");
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+ db.db
+ .prepare("INSERT INTO contacts (email, display_name) VALUES (?, ?)")
+ .run("[email protected]", "Legacy");
+
+ db.addManualContact({ email: "[email protected]", displayName: "Synced" });
+ db.addManualContact({ email: "[email protected]", displayName: null });
+ db.addManualContact({ email: "[email protected]", displayName: null });
+
+ const lookup = () =>
+ db
+ .getContactLookupSources()
+ .contacts.map((row) => row.email)
+ .sort();
+ assert.deepEqual(lookup(), ["[email protected]", "[email protected]"]);
+ db.removeGoogleAccount("[email protected]");
+ assert.deepEqual(storedContactEmails(db), ["[email protected]", "[email protected]"]);
+ assert.deepEqual(lookup(), ["[email protected]"]);
+ db.db.close();
+});
+
+test("a sync never purges a hand-added address", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.addManualContact({ email: "[email protected]", displayName: "Board" });
+ db.syncCalendarContacts("google", "[email protected]", [{ email: "[email protected]" }], []);
+
+ db.syncCalendarContacts("google", "[email protected]", [], ["[email protected]", "[email protected]"]);
+
+ assert.deepEqual(storedContactEmails(db), ["[email protected]"]);
+ db.db.close();
+});
+
+test("a room any stored event flags is excluded, even where it isn't flagged", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars(
+ [{ id: "[email protected]", summary: "Me", is_primary: true }],
+ );
+ const event = (id, attendees, extra = {}) => ({
+ id,
+ calendar_id: "[email protected]",
+ provider: "google",
+ start_time: new Date().toISOString(),
+ end_time: new Date().toISOString(),
+ is_all_day: false,
+ status: "confirmed",
+ attendees_count: attendees.length,
+ attendees: JSON.stringify(attendees),
+ ...extra,
+ });
+ db.upsertCalendarEvents([
+ // Stored by an older build, before rooms were flagged.
+ event("legacy", [{ email: "[email protected]", displayName: "Lincoln Room" }]),
+ event(
+ "declined",
+ [{ email: "[email protected]", displayName: "Lincoln Room", resource: true }],
+ { self_response_status: "declined" }
+ ),
+ ]);
+
+ assert.deepEqual(db.getContactLookupSources().excludedEmails, [
+ ]);
+
+ // One unreadable attendee list must not blank the whole lookup.
+ db.db.prepare("UPDATE calendar_events SET attendees = 'not json' WHERE id = 'legacy'").run();
+ assert.deepEqual(db.getContactLookupSources().excludedEmails, [
+ ]);
+ db.db.close();
+});
+
+test("a Microsoft account keeps its tenant and aliases until it's disconnected", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const tokens = {
+ microsoft_email: "[email protected]",
+ access_token: "access",
+ refresh_token: "refresh",
+ expires_at: Date.now() + 60_000,
+ scope: "scope",
+ };
+ db.saveMicrosoftTokens({ ...tokens, tenant_id: "tenant-1" });
+ // A refresh without an id_token carries no tenant.
+ db.saveMicrosoftTokens(tokens);
+ db.saveMicrosoftOwnAddresses("[email protected]", ["[email protected]"]);
+ db.saveMicrosoftCalendars([{ id: "m-cal", summary: "Calendar" }], "[email protected]");
+
+ assert.deepEqual(db.getMicrosoftAccounts(), [{ email: "[email protected]", tenantId: "tenant-1" }]);
+ assert.deepEqual(db.getMicrosoftOwnAddresses("[email protected]"), ["[email protected]"]);
+ assert.deepEqual(db.getContactLookupSources().excludedEmails, [
+ ]);
+ db.removeMicrosoftAccount("[email protected]");
+ assert.deepEqual(db.getContactLookupSources().excludedEmails, []);
+ db.db.close();
+});
+
+test("contact sources from pre-release builds move to contact_sources", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.db.exec("ALTER TABLE contacts ADD COLUMN source TEXT");
+ db.db
+ .prepare("INSERT INTO contacts (email, display_name, source) VALUES (?, ?, ?)")
+ .run("[email protected]", "Josh", "google:[email protected]");
+ db.db.close();
+
+ const reopened = new DatabaseManager();
+ assert.deepEqual(reopened.db.prepare("SELECT email, source FROM contact_sources").all(), [
+ { email: "[email protected]", source: "google:[email protected]" },
+ ]);
+ assert.equal(reopened.db.prepare("SELECT source FROM contacts").get().source, null);
+ reopened.db.close();
+});
+
+test("upgrading to user_version 3 forces a full calendar re-sync", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ db.saveGoogleCalendars([{ id: "primary", summary: "Chad" }], "[email protected]");
+ db.saveMicrosoftCalendars([{ id: "work", summary: "Calendar" }], "[email protected]");
+ db.updateCalendarSyncToken("primary", "google-token", Date.now() + 60_000);
+ db.updateMicrosoftCalendarSyncToken("work", "microsoft-token", Date.now() + 60_000);
+ db.db.pragma("user_version = 2");
+ db.db.close();
+
+ // Same user data directory: the next launch runs the migration.
+ const reopened = new DatabaseManager();
+ const tokens = reopened.db
+ .prepare(
+ "SELECT sync_token FROM google_calendars UNION ALL SELECT sync_token FROM microsoft_calendars"
+ )
+ .all();
+ assert.deepEqual(tokens, [{ sync_token: null }, { sync_token: null }]);
+ assert.equal(reopened.db.pragma("user_version", { simple: true }), 3);
+ reopened.db.close();
+});
diff --git a/test/helpers/connectors/connectorIpc.test.js b/test/helpers/connectors/connectorIpc.test.js
new file mode 100644
index 000000000..f41011c6d
--- /dev/null
+++ b/test/helpers/connectors/connectorIpc.test.js
@@ -0,0 +1,439 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../../src/helpers/connectors/connectorIpc.js");
+
+const SCOPE = { accountId: "account-a", authGeneration: 3 };
+const ALLOWED = { policyState: "allowed", accountId: "account-a" };
+
+function fakeIpcMain() {
+ const handlers = new Map();
+ return { handlers, handle: (channel, handler) => handlers.set(channel, handler) };
+}
+
+function fakeManager() {
+ const calls = [];
+ const record =
+ (name) =>
+ (...args) => {
+ calls.push({ name, args });
+ return { ok: name };
+ };
+ return {
+ calls,
+ status: record("status"),
+ prepare: record("prepare"),
+ commit: record("commit"),
+ cancel: (...args) => {
+ calls.push({ name: "cancel", args });
+ return { cancelled: false };
+ },
+ runDirect: record("runDirect"),
+ recentActions: record("recentActions"),
+ };
+}
+
+test("each channel reaches the manager, with policy only where something can leave", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ const policyCalls = [];
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: async (event) => {
+ policyCalls.push(event);
+ return "allowed";
+ },
+ getAccountScope: () => SCOPE,
+ });
+ const event = { sender: "renderer-1" };
+ const h = (channel) => ipcMain.handlers.get(channel);
+
+ await h("connector-status")(event);
+ await h("connector-prepare")(event, "slack", "send_message", { text: "hi" });
+ await h("connector-commit")(event, "action-1", { body: "hi!" });
+ await h("connector-cancel")(event, "action-1", "cancelled_by_user");
+ await h("connector-run-direct")(event, "email", "draft", { to: ["[email protected]"] });
+ await h("connector-recent-actions")(event, "email", 5);
+
+ assert.deepEqual(
+ manager.calls.map((call) => call.name),
+ ["status", "prepare", "commit", "cancel", "runDirect", "recentActions"]
+ );
+ assert.deepEqual(manager.calls[1].args, ["slack", "send_message", { text: "hi" }, ALLOWED]);
+ assert.deepEqual(manager.calls[2].args, ["action-1", { body: "hi!" }, ALLOWED]);
+ const [connectorId, action, args, auth, runtime] = manager.calls[4].args;
+ assert.deepEqual(
+ [connectorId, action, args, auth],
+ ["email", "draft", { to: ["[email protected]"] }, ALLOWED]
+ );
+ assert.equal(runtime.webContents, "renderer-1");
+ assert.equal(runtime.signal.aborted, false);
+ assert.deepEqual(manager.calls[5].args, ["email", 5, "account-a"]);
+ assert.equal(policyCalls.length, 3);
+});
+
+test("a cancel that lands while a direct run waits on policy stops it", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ const policyWaits = [];
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: () => new Promise((resolve) => policyWaits.push(resolve)),
+ getAccountScope: () => SCOPE,
+ });
+ const h = (channel) => ipcMain.handlers.get(channel);
+
+ const cancelledRun = h("connector-run-direct")({}, "email", "draft", { to: ["[email protected]"] }, "run-1");
+ assert.deepEqual(await h("connector-cancel")({}, "run-1", "cancelled_by_user"), {
+ cancelled: true,
+ });
+ policyWaits.shift()("allowed");
+ assert.deepEqual(await cancelledRun, { state: "not_sent", reason: "cancelled" });
+
+ // Once the run finishes it is no longer tracked, so a later cancel with the
+ // same id is only an ordinary (pending approval) cancel.
+ const run = h("connector-run-direct")({}, "email", "draft", { to: ["[email protected]"] }, "run-2");
+ policyWaits.shift()("allowed");
+ await run;
+ assert.deepEqual(await h("connector-cancel")({}, "run-2", "cancelled_by_user"), {
+ cancelled: false,
+ });
+
+ assert.deepEqual(
+ manager.calls.map((call) => call.name),
+ ["cancel", "runDirect", "cancel"]
+ );
+});
+
+test("malformed arguments never reach the manager", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: async () => "allowed",
+ getAccountScope: () => SCOPE,
+ });
+ const h = (channel) => ipcMain.handlers.get(channel);
+
+ const prepared = await h("connector-prepare")({}, 42, "send_message", null);
+ const committed = await h("connector-commit")({}, null, {});
+
+ assert.deepEqual(prepared, { status: "unavailable", reason: "invalid_request" });
+ assert.deepEqual(committed, { state: "not_sent", reason: "invalid_request" });
+ for (const [connectorId, action, args] of [
+ ["email", "draft", ["[email protected]"]],
+ ["email", "draft", null],
+ ["email", "", {}],
+ [7, "draft", {}],
+ ]) {
+ assert.deepEqual(await h("connector-run-direct")({}, connectorId, action, args, "run-1"), {
+ state: "unavailable",
+ reason: "invalid_request",
+ });
+ }
+ assert.equal(manager.calls.length, 0);
+});
+
+test("the policy resolver allows signed-out users and maps snapshots", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ const signedOut = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({}),
+ getPolicy: async () => {
+ throw new Error("must not be called");
+ },
+ getAuthGeneration: () => 1,
+ });
+ assert.equal(await signedOut({}), "allowed");
+
+ const blocked = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Authorization: "Bearer t" }),
+ getPolicy: async () => ({
+ success: true,
+ managed: true,
+ policy: { features: { connectorsEnabled: false } },
+ }),
+ getAuthGeneration: () => 1,
+ });
+ assert.equal(await blocked({}), "blocked");
+});
+
+test("a policy lookup that hangs or throws fails closed", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ const hanging = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Authorization: "Bearer t" }),
+ getPolicy: () => new Promise(() => {}),
+ getAuthGeneration: () => 1,
+ timeoutMs: 20,
+ });
+ const started = Date.now();
+ assert.equal(await hanging({}), "unavailable");
+ assert.ok(Date.now() - started < 1000);
+
+ const throwing = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Cookie: "session=1" }),
+ getPolicy: async () => {
+ throw new Error("offline");
+ },
+ getAuthGeneration: () => 1,
+ });
+ assert.equal(await throwing({}), "unavailable");
+
+ const throttled = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Authorization: "Bearer t" }),
+ getPolicy: async () => ({ success: false, status: "error", code: "POLICY_RETRY_THROTTLED" }),
+ getAuthGeneration: () => 1,
+ });
+ assert.equal(await throttled({}), "unavailable");
+});
+
+test("a slow refresh falls back to the verdict already held for the account", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ const peeked = [];
+ const slowRefresh = (held) =>
+ createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Authorization: "Bearer t" }),
+ getPolicy: () => new Promise(() => {}),
+ peekPolicy: (request) => {
+ peeked.push(request);
+ return held;
+ },
+ getAuthGeneration: () => 7,
+ timeoutMs: 20,
+ });
+
+ assert.equal(await slowRefresh({ success: true, managed: false, policy: null })({}), "allowed");
+ assert.equal(
+ await slowRefresh({
+ success: true,
+ managed: true,
+ policy: { features: { connectorsEnabled: false } },
+ })({}),
+ "blocked"
+ );
+ // Nothing held yet (the session's first lookup): still fails closed.
+ assert.equal(await slowRefresh(null)({}), "unavailable");
+ assert.deepEqual(peeked[0], {
+ expectedAuthGeneration: 7,
+ authHeaders: { Authorization: "Bearer t" },
+ });
+});
+
+test("the auth generation is read before the header lookup", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ let generation = 4;
+ const requests = [];
+ const resolver = createConnectorPolicyResolver({
+ getAuthHeader: async () => {
+ // A sign-in lands while the cookie lookup is in flight.
+ generation = 5;
+ return { Cookie: "session=old" };
+ },
+ getPolicy: async (request) => {
+ requests.push(request);
+ return { success: false, status: "error", code: "AUTH_CONTEXT_CHANGED" };
+ },
+ getAuthGeneration: () => generation,
+ });
+
+ assert.equal(await resolver({}), "unavailable");
+ assert.equal(requests[0].expectedAuthGeneration, 4);
+});
+
+test("the deadline covers the auth-header lookup too", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ const hangingAuth = createConnectorPolicyResolver({
+ getAuthHeader: () => new Promise(() => {}),
+ getPolicy: async () => {
+ throw new Error("must not be called");
+ },
+ getAuthGeneration: () => 1,
+ timeoutMs: 20,
+ });
+ const started = Date.now();
+ assert.equal(await hangingAuth({}), "unavailable");
+ assert.ok(Date.now() - started < 1000);
+
+ const throwingAuth = createConnectorPolicyResolver({
+ getAuthHeader: async () => {
+ throw new Error("window destroyed");
+ },
+ getPolicy: async () => ({ success: true, managed: false, policy: null }),
+ getAuthGeneration: () => {
+ throw new Error("token store unavailable");
+ },
+ });
+ assert.equal(await throwingAuth({}), "unavailable");
+});
+
+test("contact lookup trims the query and returns nothing the org policy doesn't allow", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const queries = [];
+ const policies = ["allowed", "blocked", "unavailable"];
+ registerConnectorIpc({
+ ipcMain,
+ manager: fakeManager(),
+ getPolicyState: async () => policies.shift(),
+ getAccountScope: () => SCOPE,
+ findContacts: (query) => {
+ queries.push(query);
+ return {
+ contacts: [{ name: "Gabe", email: "[email protected]", lastMet: null }],
+ hasMore: false,
+ };
+ },
+ });
+ const handler = ipcMain.handlers.get("connector-find-contacts");
+ assert.deepEqual(await handler({}, " Gabe "), {
+ contacts: [{ name: "Gabe", email: "[email protected]", lastMet: null }],
+ hasMore: false,
+ });
+ assert.deepEqual(await handler({}, "Gabe"), {
+ contacts: [],
+ unavailableReason: "policy_blocked",
+ });
+ assert.deepEqual(await handler({}, "Gabe"), {
+ contacts: [],
+ unavailableReason: "policy_unavailable",
+ });
+ // Malformed or oversized queries never reach the policy lookup or the search.
+ assert.deepEqual(await handler({}, 42), { contacts: [] });
+ assert.deepEqual(await handler({}, "a".repeat(201)), { contacts: [] });
+ assert.deepEqual(queries, ["Gabe"]);
+ assert.equal(policies.length, 0);
+});
+
+test("an action runs under the account bound to its credential, or none if it changed", async () => {
+ const { registerConnectorIpc } = await load();
+ const cases = [
+ // A stable scope.
+ [SCOPE, SCOPE, "account-a"],
+ // Signed out, or signed in but not yet scoped (the null-scope gap).
+ [null, null, null],
+ // A sign-in lands during the policy wait.
+ [null, SCOPE, null],
+ // A → B: another account's credential arrives during the wait.
+ [SCOPE, { accountId: "account-b", authGeneration: 4 }, null],
+ // Same account, rotated credential.
+ [SCOPE, { ...SCOPE, authGeneration: 4 }, null],
+ ];
+ for (const [before, after, accountId] of cases) {
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ let scope = before;
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: async () => {
+ scope = after;
+ return "allowed";
+ },
+ getAccountScope: () => scope,
+ });
+ await ipcMain.handlers.get("connector-run-direct")({}, "email", "draft", {});
+ assert.deepEqual(manager.calls[0].args[3], { policyState: "allowed", accountId });
+ }
+});
+
+test("recent actions are read for the account bound to the credential", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ let scope = null;
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: async () => "allowed",
+ getAccountScope: () => scope,
+ });
+ const recent = ipcMain.handlers.get("connector-recent-actions");
+ await recent({}, "email", 5);
+ scope = SCOPE;
+ await recent({}, "email", 5);
+ assert.deepEqual(
+ manager.calls.map((call) => call.args),
+ [
+ ["email", 5, null],
+ ["email", 5, "account-a"],
+ ]
+ );
+});
+
+test("a cancel after policy resolves still reaches the running action's signal", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const gate = [];
+ let runtimeSeen = null;
+ const manager = {
+ ...fakeManager(),
+ runDirect: (connectorId, action, args, auth, runtime) => {
+ runtimeSeen = runtime;
+ return new Promise((resolve) => gate.push(resolve));
+ },
+ };
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: async () => "allowed",
+ getAccountScope: () => SCOPE,
+ });
+ const h = (channel) => ipcMain.handlers.get(channel);
+
+ const run = h("connector-run-direct")({}, "email", "draft", {}, "run-1");
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(runtimeSeen.signal.aborted, false);
+ assert.deepEqual(await h("connector-cancel")({}, "run-1", "cancelled_by_user"), {
+ cancelled: true,
+ });
+ assert.equal(runtimeSeen.signal.aborted, true);
+ gate.shift()({ state: "not_sent", reason: "cancelled" });
+ assert.deepEqual(await run, { state: "not_sent", reason: "cancelled" });
+});
+
+test("a run id can't hijack a live run or swallow an approval's cancel", async () => {
+ const { registerConnectorIpc } = await load();
+ const ipcMain = fakeIpcMain();
+ const manager = fakeManager();
+ const policyWaits = [];
+ registerConnectorIpc({
+ ipcMain,
+ manager,
+ getPolicyState: () => new Promise((resolve) => policyWaits.push(resolve)),
+ getAccountScope: () => SCOPE,
+ });
+ const h = (channel) => ipcMain.handlers.get(channel);
+
+ const first = h("connector-run-direct")({}, "email", "draft", {}, "action-1");
+ assert.deepEqual(await h("connector-run-direct")({}, "email", "draft", {}, "action-1"), {
+ state: "unavailable",
+ reason: "invalid_request",
+ });
+
+ // "action-1" is also a pending approval's id: its cancel still reaches main.
+ await h("connector-cancel")({}, "action-1", "cancelled_by_user");
+ assert.deepEqual(manager.calls[0], { name: "cancel", args: ["action-1", "cancelled_by_user"] });
+
+ policyWaits.shift()("allowed");
+ assert.deepEqual(await first, { state: "not_sent", reason: "cancelled" });
+ assert.equal(policyWaits.length, 0);
+});
+
+test("a held verdict that throws on the deadline fallback fails closed", async () => {
+ const { createConnectorPolicyResolver } = await load();
+ const resolver = createConnectorPolicyResolver({
+ getAuthHeader: async () => ({ Authorization: "Bearer t" }),
+ getPolicy: () => new Promise(() => {}),
+ peekPolicy: () => {
+ throw new Error("cache corrupted");
+ },
+ getAuthGeneration: () => 1,
+ timeoutMs: 20,
+ });
+ assert.equal(await resolver({}), "unavailable");
+});
diff --git a/test/helpers/connectors/connectorManager.test.js b/test/helpers/connectors/connectorManager.test.js
new file mode 100644
index 000000000..4cad196c0
--- /dev/null
+++ b/test/helpers/connectors/connectorManager.test.js
@@ -0,0 +1,876 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const loadManager = () => import("../../../src/helpers/connectors/connectorManager.js");
+const loadPending = () => import("../../../src/helpers/connectors/pendingActions.js");
+
+const silentLogger = { info() {}, warn() {}, error() {} };
+
+const ACCOUNT = "account-a";
+const ALLOWED = { policyState: "allowed", accountId: ACCOUNT };
+
+function deferred() {
+ let resolve;
+ const promise = new Promise((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+// better-sqlite3 throws when asked to bind anything but a primitive, which
+// would leave a receipt stuck in its last state.
+function assertBindable(values) {
+ for (const value of Object.values(values)) {
+ if (value !== null && value !== undefined && typeof value === "object") {
+ throw new TypeError("SQLite3 can only bind numbers, strings, bigints, buffers, and null");
+ }
+ }
+}
+
+function fakeLog({ failInsert = false, failTransition = false, failFinal = false } = {}) {
+ const rows = new Map();
+ let reconciled = 0;
+ return {
+ rows,
+ reconciledCount: () => reconciled,
+ insert: (row) => {
+ if (failInsert) throw new Error("disk full");
+ assertBindable(row);
+ rows.set(row.id, { ...row });
+ },
+ // Mirrors updateConnectorActionState: a guarded update only moves a row
+ // still in fromState and reports how many rows changed.
+ update: (id, patch, fromState) => {
+ const row = rows.get(id);
+ if (!row) return 0;
+ if (fromState !== undefined && row.state !== fromState) return 0;
+ if (fromState !== undefined && failTransition) throw new Error("disk full");
+ if (fromState === undefined && failFinal) throw new Error("disk full");
+ assertBindable(patch);
+ rows.set(id, { ...row, ...patch });
+ return 1;
+ },
+ listRecent: (connector, limit, accountId) =>
+ [...rows.values()]
+ .filter((row) => row.connector === connector && row.accountId === accountId)
+ .slice(0, limit),
+ reconcileInterrupted: () => {
+ reconciled += 1;
+ return { unknown: 0, cancelled: 0 };
+ },
+ };
+}
+
+function fakeConnector(overrides = {}) {
+ const calls = { prepare: [], commit: [], runDirect: [] };
+ let binding = { accountId: "U1", workspaceId: "T1", generation: 1 };
+ const connector = {
+ id: "fake",
+ actions: { post: { kind: "approval" }, draft: { kind: "direct" } },
+ async getStatus() {
+ return { connected: true, accountLabel: "chad" };
+ },
+ async getBinding() {
+ return binding;
+ },
+ async prepare(action, args) {
+ calls.prepare.push({ action, args });
+ return {
+ status: "ready",
+ payload: { channel: "C1", text: args.text },
+ preview: {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ body: args.text,
+ },
+ };
+ },
+ async commit(action, payload, edits) {
+ calls.commit.push({ action, payload, edits });
+ return { state: "sent", url: "https://example.test/p/1" };
+ },
+ async runDirect(action, args, runtime) {
+ calls.runDirect.push({ action, args, runtime });
+ return { state: "sent", destinationLabel: "[email protected]" };
+ },
+ ...overrides,
+ };
+ return {
+ connector,
+ calls,
+ setBinding: (next) => {
+ binding = next;
+ },
+ };
+}
+
+async function setup(connectorOverrides, logOptions, pendingOptions) {
+ const [{ createConnectorManager }, { createPendingActions }] = await Promise.all([
+ loadManager(),
+ loadPending(),
+ ]);
+ const fake = fakeConnector(connectorOverrides);
+ const log = fakeLog(logOptions);
+ const manager = createConnectorManager({
+ connectors: [fake.connector],
+ pendingActions: createPendingActions(pendingOptions),
+ actionLog: log,
+ logger: silentLogger,
+ });
+ return { manager, fake, log };
+}
+
+test("creating the manager reconciles interrupted rows", async () => {
+ const { log } = await setup();
+ assert.equal(log.reconciledCount(), 1);
+});
+
+test("prepare then commit sends once and records every state", async () => {
+ const { manager, fake, log } = await setup();
+
+ const prepared = await manager.prepare("fake", "post", { text: "hello" }, ALLOWED);
+ assert.equal(prepared.status, "ready");
+ assert.equal(log.rows.get(prepared.actionId).state, "pending");
+
+ const result = await manager.commit(prepared.actionId, { body: "hello!" }, ALLOWED);
+
+ assert.deepEqual(result, { state: "sent", url: "https://example.test/p/1" });
+ assert.deepEqual(fake.calls.commit[0].edits, { body: "hello!" });
+ assert.equal(log.rows.get(prepared.actionId).state, "sent");
+ assert.equal(log.rows.get(prepared.actionId).resultUrl, "https://example.test/p/1");
+});
+
+test("a second commit while the first is in flight never sends twice", async () => {
+ const gate = deferred();
+ const { manager, fake } = await setup({
+ async commit(action, payload, edits) {
+ fake.calls.commit.push({ action, payload, edits });
+ await gate.promise;
+ return { state: "sent" };
+ },
+ });
+ const { actionId } = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);
+
+ const first = manager.commit(actionId, {}, ALLOWED);
+ const second = await manager.commit(actionId, {}, ALLOWED);
+ gate.resolve();
+
+ assert.deepEqual(second, { state: "not_sent", reason: "not_pending" });
+ assert.deepEqual(await first, { state: "sent" });
+ assert.equal(fake.calls.commit.length, 1);
+});
+
+test("a blocked or unavailable policy refuses prepare, commit and runDirect", async () => {
+ const { manager, fake, log } = await setup();
+
+ assert.deepEqual(
+ await manager.prepare(
+ "fake",
+ "post",
+ { text: "x" },
+ { policyState: "blocked", accountId: ACCOUNT }
+ ),
+ {
+ status: "unavailable",
+ reason: "policy_blocked",
+ }
+ );
+ assert.equal(fake.calls.prepare.length, 0);
+
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.deepEqual(
+ await manager.commit(actionId, {}, { policyState: "unavailable", accountId: ACCOUNT }),
+ {
+ state: "not_sent",
+ reason: "policy_unavailable",
+ }
+ );
+ assert.equal(fake.calls.commit.length, 0);
+ assert.equal(log.rows.get(actionId).state, "cancelled");
+
+ assert.deepEqual(
+ await manager.runDirect(
+ "fake",
+ "draft",
+ {},
+ { policyState: "unavailable", accountId: ACCOUNT },
+ {}
+ ),
+ {
+ state: "unavailable",
+ reason: "policy_unavailable",
+ }
+ );
+});
+
+test("a connection change between prepare and commit refuses the send", async () => {
+ const { manager, fake, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ fake.setBinding({ accountId: "U2", workspaceId: "T1", generation: 2 });
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "connection_changed",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+ assert.equal(log.rows.get(actionId).errorCode, "connection_changed");
+});
+
+test("a connector that throws during commit is recorded as unknown", async () => {
+ const { manager, log } = await setup({
+ async commit() {
+ throw new Error("socket closed");
+ },
+ });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), { state: "unknown" });
+ assert.equal(log.rows.get(actionId).state, "unknown");
+});
+
+test("a connector commit resolving undefined is recorded as unknown and never orphans the entry", async () => {
+ const { manager, log } = await setup({
+ async commit() {
+ return undefined;
+ },
+ });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), { state: "unknown" });
+ assert.equal(log.rows.get(actionId).state, "unknown");
+ // The entry must not be orphaned in "committing": a second commit finds no pending action.
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "not_found",
+ });
+});
+
+test("a connector commit resolving an unrecognized state is recorded as unknown", async () => {
+ const { manager, log } = await setup({
+ async commit() {
+ return { state: "banana" };
+ },
+ });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), { state: "unknown" });
+ assert.equal(log.rows.get(actionId).state, "unknown");
+});
+
+test("a runDirect that throws or resolves malformed is recorded as unknown, never failed", async () => {
+ // Either may come after the side effect, so "failed" would invite a duplicate retry.
+ for (const [runDirect, errorCode] of [
+ [async () => undefined, "invalid_result"],
+ [async () => ({ state: "banana" }), "invalid_result"],
+ [
+ async () => {
+ throw new Error("clipboard unavailable");
+ },
+ "direct_failed",
+ ],
+ ]) {
+ const { manager, log } = await setup({ runDirect });
+
+ const result = await manager.runDirect("fake", "draft", {}, ALLOWED, {});
+
+ assert.equal(result.state, "unknown");
+ assert.equal(result.errorCode, errorCode);
+ assert.match(result.message, /may have gone through/);
+ const [row] = [...log.rows.values()];
+ assert.equal(row.state, "unknown");
+ }
+});
+
+test("clarification and prepare failures create no pending action", async () => {
+ const { manager, log } = await setup({
+ async prepare() {
+ return {
+ status: "needs_clarification",
+ message: "Which #eng?",
+ candidates: ["#eng-web", "#eng-ios"],
+ };
+ },
+ });
+ const result = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.equal(result.status, "needs_clarification");
+ assert.equal(log.rows.size, 0);
+});
+
+test("prepare passes on only the fields each connector result defines", async () => {
+ const cases = [
+ [
+ undefined,
+ { status: "failed", errorCode: "invalid_result", message: "Couldn't prepare that action." },
+ ],
+ [
+ { status: "sent", body: "secret text" },
+ { status: "failed", errorCode: "invalid_result", message: "Couldn't prepare that action." },
+ ],
+ [
+ { status: "ready", payload: { text: "x" } },
+ { status: "failed", errorCode: "invalid_result", message: "Couldn't prepare that action." },
+ ],
+ [
+ {
+ status: "needs_clarification",
+ message: "Which #eng?",
+ candidates: ["#eng-web", 7],
+ body: "secret text",
+ },
+ { status: "needs_clarification", message: "Which #eng?", candidates: ["#eng-web"] },
+ ],
+ [
+ {
+ status: "failed",
+ errorCode: "channel_archived",
+ message: "That channel is archived.",
+ body: "secret text",
+ },
+ { status: "failed", errorCode: "channel_archived", message: "That channel is archived." },
+ ],
+ ];
+ for (const [prepared, expected] of cases) {
+ const { manager, log } = await setup({ prepare: async () => prepared });
+ assert.deepEqual(await manager.prepare("fake", "post", { text: "x" }, ALLOWED), expected);
+ assert.equal(log.rows.size, 0);
+ }
+
+ const { manager } = await setup({
+ async prepare() {
+ throw new Error("token=abc123 rejected");
+ },
+ });
+ assert.deepEqual(await manager.prepare("fake", "post", { text: "x" }, ALLOWED), {
+ status: "failed",
+ errorCode: "prepare_failed",
+ message: "Couldn't prepare that action.",
+ });
+});
+
+test("a connector lookup that throws never hands its error to the renderer", async () => {
+ const leaky = new Error("token=abc123 rejected");
+ const bindingThrows = await setup({
+ async getBinding() {
+ throw leaky;
+ },
+ async getStatus() {
+ throw leaky;
+ },
+ });
+ assert.deepEqual(await bindingThrows.manager.prepare("fake", "post", { text: "x" }, ALLOWED), {
+ status: "unavailable",
+ reason: "not_connected",
+ });
+ assert.deepEqual(await bindingThrows.manager.status(), [
+ { id: "fake", connected: false, accountLabel: null },
+ ]);
+
+ const { manager, fake, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ fake.connector.getBinding = async () => {
+ throw leaky;
+ };
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "connection_changed",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+ assert.equal(log.rows.get(actionId).state, "cancelled");
+});
+
+test("expired pending actions are swept and recorded as expired on the next call", async () => {
+ const { PENDING_TTL_MS } = await loadPending();
+ let clock = 1_000;
+ const { manager, log } = await setup({}, {}, { now: () => clock });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ clock += PENDING_TTL_MS + 1;
+ manager.recentActions("fake", 10, ACCOUNT);
+
+ assert.equal(log.rows.get(actionId).state, "expired");
+ assert.equal(log.rows.get(actionId).errorCode, "expired");
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "not_found",
+ });
+});
+
+test("cancel withdraws only pending actions and records the reason", async () => {
+ const { manager, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(manager.cancel(actionId, "conversation_ended"), { cancelled: true });
+ assert.equal(log.rows.get(actionId).state, "cancelled");
+ assert.equal(log.rows.get(actionId).errorCode, "conversation_ended");
+ assert.deepEqual(manager.cancel(actionId, "cancelled_by_user"), { cancelled: false });
+
+ const expiring = await manager.prepare("fake", "post", { text: "y" }, ALLOWED);
+ manager.cancel(expiring.actionId, "expired");
+ assert.equal(log.rows.get(expiring.actionId).state, "expired");
+});
+
+test("runDirect runs direct actions with the runtime and logs a receipt", async () => {
+ const { manager, fake, log } = await setup();
+ const runtime = { webContents: "sender" };
+
+ const result = await manager.runDirect("fake", "draft", { to: ["[email protected]"] }, ALLOWED, runtime);
+
+ assert.deepEqual(result, { state: "sent", destinationLabel: "[email protected]" });
+ assert.equal(fake.calls.runDirect[0].runtime, runtime);
+ const [row] = [...log.rows.values()];
+ assert.equal(row.kind, "direct");
+ assert.equal(row.state, "sent");
+});
+
+test("an action is only reachable through its own kind", async () => {
+ const { manager } = await setup();
+ assert.deepEqual(await manager.runDirect("fake", "post", {}, ALLOWED, {}), {
+ state: "unavailable",
+ reason: "unknown_action",
+ });
+ assert.deepEqual(await manager.prepare("fake", "draft", {}, ALLOWED), {
+ status: "unavailable",
+ reason: "unknown_action",
+ });
+ assert.deepEqual(await manager.prepare("nope", "post", {}, ALLOWED), {
+ status: "unavailable",
+ reason: "unknown_connector",
+ });
+});
+
+test("edits are reduced to string title and body", async () => {
+ const { manager, fake } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ await manager.commit(actionId, { body: "b", title: 5, channel: "C999" }, ALLOWED);
+ assert.deepEqual(fake.calls.commit[0].edits, { body: "b" });
+});
+
+test("invalidate cancels pending actions for that connector", async () => {
+ const { manager, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.deepEqual(manager.invalidate("fake"), [actionId]);
+ assert.equal(log.rows.get(actionId).errorCode, "connection_changed");
+});
+
+test("a pending row that can't be written means no card and no pending action", async () => {
+ const { manager, log } = await setup({}, { failInsert: true });
+ const result = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.equal(result.status, "failed");
+ assert.equal(result.errorCode, "receipt_unavailable");
+ assert.equal(log.rows.size, 0);
+});
+
+test("the send never starts unless committing was durably recorded", async () => {
+ const { manager, fake } = await setup({}, { failTransition: true });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "receipt_unavailable",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "not_found",
+ });
+});
+
+test("the send never starts when the committing write moves no row", async () => {
+ const { manager, fake, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ log.rows.delete(actionId);
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "receipt_unavailable",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+});
+
+test("a failed final write still reports the real outcome and leaves the row committing", async () => {
+ const { manager, log } = await setup({}, { failFinal: true });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "sent",
+ url: "https://example.test/p/1",
+ });
+ // Reconciliation turns this into "unknown" on the next launch: conservative, never "cancelled".
+ assert.equal(log.rows.get(actionId).state, "committing");
+});
+
+test("a direct action is recorded as committing before it runs", async () => {
+ let statesSeenByConnector = null;
+ let logRef = null;
+ const { manager, log } = await setup({
+ async runDirect() {
+ statesSeenByConnector = [...logRef.rows.values()].map((row) => row.state);
+ return { state: "sent", destinationLabel: "[email protected]" };
+ },
+ });
+ logRef = log;
+
+ await manager.runDirect("fake", "draft", {}, ALLOWED, {});
+
+ assert.deepEqual(statesSeenByConnector, ["committing"]);
+ const [row] = [...log.rows.values()];
+ assert.equal(row.state, "sent");
+ assert.equal(row.destinationLabel, "[email protected]");
+});
+
+test("a direct action whose record can't be written never runs", async () => {
+ const { manager, fake } = await setup({}, { failInsert: true });
+ assert.deepEqual(await manager.runDirect("fake", "draft", {}, ALLOWED, {}), {
+ state: "unavailable",
+ reason: "receipt_unavailable",
+ });
+ assert.equal(fake.calls.runDirect.length, 0);
+});
+
+test("concurrent commits where second loses the race never overwrites sent receipt", async () => {
+ const gate = deferred();
+ let bindingCalls = 0;
+ const { manager, fake, log } = await setup({
+ async getBinding() {
+ bindingCalls += 1;
+ if (bindingCalls === 3) await gate.promise;
+ return { accountId: "U1", workspaceId: "T1", generation: 1 };
+ },
+ });
+
+ const { actionId } = await manager.prepare("fake", "post", { text: "hello" }, ALLOWED);
+
+ // Start both commits concurrently (no await between them)
+ const first = manager.commit(actionId, {}, ALLOWED);
+ const second = manager.commit(actionId, {}, ALLOWED);
+
+ // First commit should complete as sent
+ assert.deepEqual(await first, { state: "sent", url: "https://example.test/p/1" });
+
+ // Now release the gate for second commit's getBinding
+ gate.resolve();
+
+ // Second commit should fail with not_found without overwriting the receipt
+ assert.deepEqual(await second, { state: "not_sent", reason: "not_found" });
+ assert.equal(fake.calls.commit.length, 1);
+
+ const row = log.rows.get(actionId);
+ assert.equal(row.state, "sent");
+ assert.equal(row.resultUrl, "https://example.test/p/1");
+});
+
+test("invalidate during a gated commit cancels the action without overwriting it", async () => {
+ const gate = deferred();
+ let bindingCalls = 0;
+ const { manager, fake, log } = await setup({
+ async getBinding() {
+ bindingCalls += 1;
+ if (bindingCalls === 2) await gate.promise;
+ return { accountId: "U1", workspaceId: "T1", generation: 1 };
+ },
+ });
+
+ const { actionId } = await manager.prepare("fake", "post", { text: "hello" }, ALLOWED);
+
+ // Start commit (will be gated at call 2)
+ const committing = manager.commit(actionId, {}, ALLOWED);
+
+ // While commit is awaiting getBinding, invalidate the connector
+ assert.deepEqual(manager.invalidate("fake"), [actionId]);
+
+ // Release the gate
+ gate.resolve();
+
+ // Commit should fail with not_found (entry was removed/cancelled by invalidate)
+ assert.deepEqual(await committing, { state: "not_sent", reason: "not_found" });
+ assert.equal(fake.calls.commit.length, 0);
+
+ // Row should be cancelled with connection_changed from invalidate
+ const row = log.rows.get(actionId);
+ assert.equal(row.state, "cancelled");
+ assert.equal(row.errorCode, "connection_changed");
+});
+
+test("an action with no resolvable account is refused before any receipt or side effect", async () => {
+ const { manager, fake, log } = await setup();
+ const signedOut = { policyState: "allowed", accountId: null };
+
+ assert.deepEqual(await manager.prepare("fake", "post", { text: "x" }, signedOut), {
+ status: "failed",
+ errorCode: "receipt_unavailable",
+ message: "Couldn't record this action, so nothing was prepared.",
+ });
+ assert.deepEqual(await manager.runDirect("fake", "draft", {}, signedOut, {}), {
+ state: "unavailable",
+ reason: "receipt_unavailable",
+ });
+ assert.equal(fake.calls.prepare.length, 0);
+ assert.equal(fake.calls.runDirect.length, 0);
+ assert.equal(log.rows.size, 0);
+});
+
+test("receipts carry the account the action ran under, and only it sees them", async () => {
+ const { manager, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ await manager.runDirect(
+ "fake",
+ "draft",
+ {},
+ { policyState: "allowed", accountId: "account-b" },
+ {}
+ );
+
+ const rows = [...log.rows.values()];
+ assert.equal(log.rows.get(actionId).accountId, ACCOUNT);
+ assert.equal(rows.find((row) => row.kind === "direct").accountId, "account-b");
+ assert.deepEqual(
+ manager.recentActions("fake", 10, ACCOUNT).map((row) => row.id),
+ [actionId]
+ );
+ assert.deepEqual(manager.recentActions("fake", 10, null), []);
+});
+
+test("an approval prepared by one account can't be sent by another", async () => {
+ for (const accountId of ["account-b", null]) {
+ const { manager, fake, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+
+ assert.deepEqual(await manager.commit(actionId, {}, { policyState: "allowed", accountId }), {
+ state: "not_sent",
+ reason: "account_changed",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+ assert.equal(log.rows.get(actionId).state, "cancelled");
+ assert.equal(log.rows.get(actionId).errorCode, "account_changed");
+ // Withdrawn, so its own account can't send it later either.
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "not_found",
+ });
+ }
+});
+
+test("a commit refused by policy withdraws the action for good", async () => {
+ const { manager, fake } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ await manager.commit(actionId, {}, { policyState: "blocked", accountId: ACCOUNT });
+
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {
+ state: "not_sent",
+ reason: "not_found",
+ });
+ assert.equal(fake.calls.commit.length, 0);
+});
+
+test("prepare and commit each sweep other expired actions", async () => {
+ const { PENDING_TTL_MS } = await loadPending();
+ let clock = 1_000;
+ const { manager, log } = await setup({}, {}, { now: () => clock });
+
+ const stale = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ clock += PENDING_TTL_MS + 1;
+ await manager.prepare("fake", "post", { text: "y" }, ALLOWED);
+ assert.equal(log.rows.get(stale.actionId).state, "expired");
+
+ const older = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ clock += PENDING_TTL_MS - 1_000;
+ const fresh = await manager.prepare("fake", "post", { text: "y" }, ALLOWED);
+ clock += 2_000;
+ assert.equal(log.rows.get(older.actionId).state, "pending");
+ assert.equal((await manager.commit(fresh.actionId, {}, ALLOWED)).state, "sent");
+ assert.equal(log.rows.get(older.actionId).state, "expired");
+});
+
+test("a cancel reason outside the known set is recorded as the user's cancel", async () => {
+ const { manager, log } = await setup();
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ manager.cancel(actionId, "<img src=x>");
+ assert.equal(log.rows.get(actionId).errorCode, "cancelled_by_user");
+});
+
+test("recent actions asks for at most 50 rows and defaults to 10", async () => {
+ const { manager, log } = await setup();
+ const limits = [];
+ log.listRecent = (connector, limit) => {
+ limits.push(limit);
+ return [];
+ };
+ manager.recentActions("fake", 500, ACCOUNT);
+ manager.recentActions("fake", -1, ACCOUNT);
+ manager.recentActions("fake", "5", ACCOUNT);
+ manager.recentActions("fake", 5, ACCOUNT);
+ assert.deepEqual(limits, [50, 10, 10, 5]);
+});
+
+test("a commit result keeps only its state's fields, typed, and its receipt still lands", async () => {
+ const cases = [
+ [{ state: "sent", url: { href: "x" }, raw: "LEAK" }, { state: "sent" }],
+ [
+ { state: "sent", url: "https://example.test/p/2", token: "xoxb" },
+ { state: "sent", url: "https://example.test/p/2" },
+ ],
+ [
+ { state: "failed", errorCode: 5, message: { text: "raw" }, headers: "Bearer abc" },
+ { state: "failed", errorCode: "action_failed", message: "That action didn't go through." },
+ ],
+ [{ state: "unknown", checkUrl: ["x"] }, { state: "unknown" }],
+ [{ state: "not_sent", reason: "cancelled" }, { state: "unknown" }],
+ ];
+ for (const [committed, expected] of cases) {
+ const { manager, log } = await setup({ commit: async () => committed });
+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), expected);
+ assert.equal(log.rows.get(actionId).state, expected.state);
+ }
+});
+
+test("a direct result keeps only its state's fields, typed, and its receipt still lands", async () => {
+ const cases = [
+ [
+ {
+ state: "sent",
+ destinationLabel: ["[email protected]"],
+ bodyCopied: "yes",
+ copyFailed: true,
+ url: "https://mail.test/?body=secret",
+ },
+ { state: "sent", destinationLabel: "", copyFailed: true },
+ "sent",
+ ],
+ [
+ { state: "failed", errorCode: "open_failed", message: "Couldn't open.", debug: { a: 1 } },
+ { state: "failed", errorCode: "open_failed", message: "Couldn't open." },
+ "failed",
+ ],
+ [
+ { state: "failed", errorCode: { code: 1 }, destinationLabel: "[email protected]" },
+ {
+ state: "failed",
+ errorCode: "action_failed",
+ message: "That action didn't go through.",
+ destinationLabel: "[email protected]",
+ },
+ "failed",
+ ],
+ [
+ { state: "not_sent", reason: "cancelled", extra: 1 },
+ { state: "not_sent", reason: "cancelled" },
+ "cancelled",
+ ],
+ ];
+ for (const [ran, expected, receiptState] of cases) {
+ const { manager, log } = await setup({ runDirect: async () => ran });
+ assert.deepEqual(await manager.runDirect("fake", "draft", {}, ALLOWED, {}), expected);
+ assert.equal([...log.rows.values()][0].state, receiptState);
+ }
+});
+
+test("a connector can't claim a direct outcome only main may report", async () => {
+ for (const state of ["unavailable", "unknown", "committing"]) {
+ const { manager, log } = await setup({ runDirect: async () => ({ state, reason: "x" }) });
+ const result = await manager.runDirect("fake", "draft", {}, ALLOWED, {});
+ assert.equal(result.state, "unknown");
+ assert.equal(result.errorCode, "invalid_result");
+ assert.equal([...log.rows.values()][0].state, "unknown");
+ }
+});
+
+test("a prepare failure with a non-string code or message falls back to the defaults", async () => {
+ const { manager } = await setup({
+ prepare: async () => ({ status: "failed", errorCode: { raw: "x" }, message: 42 }),
+ });
+ assert.deepEqual(await manager.prepare("fake", "post", { text: "x" }, ALLOWED), {
+ status: "failed",
+ errorCode: "prepare_failed",
+ message: "Couldn't prepare that action.",
+ });
+});
+
+test("a preview reaches the card with only its defined, typed fields", async () => {
+ const preview = {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ workspaceLabel: 7,
+ title: "Standup",
+ body: "hi",
+ internal: "LEAK",
+ notes: [{ key: "thread", values: { name: "x", token: {} }, raw: 1 }, { key: 3 }, null],
+ };
+ const { manager } = await setup({
+ prepare: async () => ({ status: "ready", payload: {}, preview }),
+ });
+ const prepared = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.deepEqual(prepared.preview, {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ title: "Standup",
+ body: "hi",
+ notes: [{ key: "thread", values: { name: "x" } }],
+ });
+
+ for (const field of ["verbKey", "destinationLabel", "accountLabel", "body"]) {
+ const broken = await setup({
+ prepare: async () => ({
+ status: "ready",
+ payload: {},
+ preview: { ...preview, [field]: { toString: () => "x" } },
+ }),
+ });
+ const result = await broken.manager.prepare("fake", "post", { text: "x" }, ALLOWED);
+ assert.equal(result.errorCode, "invalid_result", field);
+ assert.equal(broken.log.rows.size, 0);
+ }
+});
+
+test("Esc during the Linux mail-app probe stops the draft before it opens or copies", async () => {
+ const [{ createConnectorManager }, { createPendingActions }, { createEmailConnector }] =
+ await Promise.all([
+ loadManager(),
+ loadPending(),
+ import("../../../src/helpers/connectors/emailConnector.js"),
+ ]);
+ const controller = new AbortController();
+ const opened = [];
+ const copied = [];
+ const email = createEmailConnector({
+ platform: "linux",
+ openExternal: async (url) => opened.push(url),
+ writeClipboard: async (text) => copied.push(text),
+ // The user presses Esc while xdg-mime is still answering.
+ hasMailtoHandler: async () => {
+ controller.abort();
+ return true;
+ },
+ });
+ const log = fakeLog();
+ const manager = createConnectorManager({
+ connectors: [email],
+ pendingActions: createPendingActions(),
+ actionLog: log,
+ logger: silentLogger,
+ });
+
+ const result = await manager.runDirect(
+ "email",
+ "draft",
+ {
+ target: "mailto",
+ subject: "Notes",
+ body: "x".repeat(5_000),
+ clipboardReserved: true,
+ },
+ ALLOWED,
+ { webContents: null, signal: controller.signal }
+ );
+
+ assert.deepEqual(result, { state: "not_sent", reason: "cancelled" });
+ assert.deepEqual(opened, []);
+ assert.deepEqual(copied, []);
+ const [row] = [...log.rows.values()];
+ assert.equal(row.state, "cancelled");
+ assert.equal(row.errorCode, "cancelled");
+});
diff --git a/test/helpers/connectors/connectorPolicy.test.js b/test/helpers/connectors/connectorPolicy.test.js
new file mode 100644
index 000000000..76c5977e2
--- /dev/null
+++ b/test/helpers/connectors/connectorPolicy.test.js
@@ -0,0 +1,143 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const loadState = () => import("../../../src/helpers/connectors/connectorPolicy.js");
+const loadValidation = () => import("../../../src/helpers/policyValidation.js");
+const loadRules = () => import("../../../src/stores/policyRules.ts");
+
+function policy(features) {
+ return {
+ version: 1,
+ transcription: { allowedModes: ["local"], allowedByokProviders: [] },
+ llm: { allowedModes: ["local"], allowedByokProviders: [], allowedEnterpriseProviders: [] },
+ features: { agentEnabled: true, webSearchEnabled: true, ...features },
+ sharing: { externalLinkSharing: "allowed" },
+ dataRetention: {
+ audioRetentionMaxDays: null,
+ localHistoryMode: "user_choice",
+ cloudBackupAllowed: true,
+ },
+ minAppVersion: null,
+ };
+}
+
+test("every failed or malformed snapshot fails closed", async () => {
+ const { connectorPolicyState } = await loadState();
+ // Every code workspacePolicyManager.js can return with success: false, plus
+ // a code it may gain later: none of them may allow an action.
+ for (const code of [
+ "POLICY_UNRESOLVABLE",
+ "POLICY_UNAVAILABLE",
+ "AUTH_CONTEXT_CHANGED",
+ "POLICY_RETRY_THROTTLED",
+ "SOME_FUTURE_CODE",
+ ]) {
+ assert.equal(
+ connectorPolicyState({ success: false, status: "error", code }),
+ "unavailable",
+ code
+ );
+ }
+ assert.equal(connectorPolicyState(null), "unavailable");
+ assert.equal(connectorPolicyState(undefined), "unavailable");
+ assert.equal(connectorPolicyState({ success: true }), "unavailable");
+ assert.equal(connectorPolicyState({ managed: false, policy: null }), "unavailable");
+ assert.equal(
+ connectorPolicyState({ success: true, managed: "yes", policy: null }),
+ "unavailable"
+ );
+ assert.equal(connectorPolicyState({ success: true, managed: true, policy: null }), "unavailable");
+ assert.equal(
+ connectorPolicyState({ success: true, managed: true, policy: { features: null } }),
+ "unavailable"
+ );
+});
+
+test("a valid snapshot allows unless a managed policy turns connectors off", async () => {
+ const { connectorPolicyState } = await loadState();
+ assert.equal(
+ connectorPolicyState({
+ success: true,
+ managed: true,
+ policy: policy({ connectorsEnabled: false }),
+ }),
+ "blocked"
+ );
+ assert.equal(
+ connectorPolicyState({
+ success: true,
+ managed: true,
+ policy: policy({ connectorsEnabled: true }),
+ }),
+ "allowed"
+ );
+ assert.equal(
+ connectorPolicyState({ success: true, managed: true, policy: policy({}) }),
+ "allowed"
+ );
+ assert.equal(connectorPolicyState({ success: true, managed: false, policy: null }), "allowed");
+ assert.equal(
+ connectorPolicyState({ success: true, status: "cached", managed: true, policy: policy({}) }),
+ "allowed"
+ );
+});
+
+test("turning off the agent turns connectors off too", async () => {
+ const { connectorPolicyState } = await loadState();
+ assert.equal(
+ connectorPolicyState({ success: true, managed: true, policy: policy({ agentEnabled: false }) }),
+ "blocked"
+ );
+});
+
+test("the desktop validator accepts the field when absent or boolean, and rejects other types", async () => {
+ const { isValidPolicyShape } = await loadValidation();
+ assert.equal(isValidPolicyShape(policy({})), true);
+ assert.equal(isValidPolicyShape(policy({ connectorsEnabled: false })), true);
+ assert.equal(isValidPolicyShape(policy({ connectorsEnabled: "no" })), false);
+});
+
+test("the renderer rule mirrors the switch", async () => {
+ const { isConnectorsAllowed } = await loadRules();
+ const managed = (features) => ({
+ status: "managed",
+ appVersion: "1.10.0",
+ policy: policy(features),
+ });
+ assert.equal(isConnectorsAllowed(managed({ connectorsEnabled: false })), false);
+ assert.equal(isConnectorsAllowed(managed({})), true);
+ assert.equal(isConnectorsAllowed(managed({ agentEnabled: false })), false);
+ assert.equal(
+ isConnectorsAllowed({ status: "unmanaged", appVersion: "1.10.0", policy: null }),
+ true
+ );
+});
+
+test("only a resolved managed policy reports connectors as turned off by the org", async () => {
+ const { isConnectorsBlockedByOrg } = await loadRules();
+ const managed = (features) => ({
+ status: "managed",
+ appVersion: "1.10.0",
+ policy: policy(features),
+ });
+ assert.equal(isConnectorsBlockedByOrg(managed({ connectorsEnabled: false })), true);
+ assert.equal(isConnectorsBlockedByOrg(managed({ agentEnabled: false })), true);
+ assert.equal(isConnectorsBlockedByOrg(managed({})), false);
+ // Still loading, or the fetch failed: actions fail closed, but nothing says
+ // an organization turned anything off.
+ for (const status of ["idle", "loading", "error", "unmanaged"]) {
+ assert.equal(
+ isConnectorsBlockedByOrg({ status, appVersion: "1.10.0", policy: null }),
+ false,
+ status
+ );
+ }
+ // An org that only requires a newer build hasn't turned connectors off; the
+ // update banner explains why they're unavailable.
+ const outdated = {
+ status: "managed",
+ appVersion: "1.10.0",
+ policy: { ...policy({}), minAppVersion: "1.11.0" },
+ };
+ assert.equal(isConnectorsBlockedByOrg(outdated), false);
+});
diff --git a/test/helpers/connectors/contactSearch.test.js b/test/helpers/connectors/contactSearch.test.js
new file mode 100644
index 000000000..d8115a43b
--- /dev/null
+++ b/test/helpers/connectors/contactSearch.test.js
@@ -0,0 +1,208 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../../src/helpers/connectors/contactSearch.js");
+
+const NOW = Date.parse("2026-09-24T12:00:00Z");
+
+function meeting(startTime, attendees, organizer = null) {
+ return {
+ start_time: startTime,
+ organizer_email: organizer,
+ attendees: JSON.stringify(attendees),
+ };
+}
+
+const ME = { email: "[email protected]", displayName: "Chad", self: true };
+
+const SOURCES = {
+ meetings: [
+ meeting("2026-09-20T10:00:00Z", [
+ ME,
+ { email: "[email protected]", displayName: "Gabe Torres" },
+ ]),
+ meeting("2026-10-20T10:00:00-07:00", [
+ ME,
+ { email: "[email protected]", displayName: "Gabe Torres" },
+ ]),
+ meeting("2026-09-10T10:00:00Z", [
+ ME,
+ { email: "[email protected]", displayName: "Gabriel Stone" },
+ ]),
+ meeting(
+ "2026-09-01T10:00:00Z",
+ [ME, { email: "[email protected]", displayName: null }],
+ ),
+ meeting("2026-10-01T09:00:00Z", [ME, { email: "[email protected]", displayName: "Nora New" }]),
+ meeting("2026-09-23T15:00:00Z", [ME, { email: "[email protected]", displayName: null }]),
+ meeting("2026-08-01T10:00:00Z", [
+ ME,
+ { email: "[email protected]", displayName: "Room 4" },
+ { email: "[email protected]", displayName: "Boardroom", resource: true },
+ ]),
+ meeting("2026-07-01T10:00:00Z", [
+ ME,
+ { email: "zoë.mü[email protected]", displayName: "Zoë Müller" },
+ ]),
+ // The user's own solo event: they are only the organizer, never flagged self.
+ meeting("2026-09-22T10:00:00Z", [], "[email protected]"),
+ meeting("2026-12-25T00:00:00Z", [
+ {
+ email: "en.usa#[email protected]",
+ displayName: "Holidays in United States",
+ },
+ ]),
+ // Addresses outside the account table: an Apple account, a Google alias.
+ meeting("2026-09-24T08:00:00Z", [
+ { email: "[email protected]", displayName: "Chad", self: true },
+ ]),
+ meeting("2026-09-24T09:00:00Z", [
+ { email: "[email protected]", displayName: "Chad", self: true },
+ ]),
+ { start_time: "2026-06-01T10:00:00Z", organizer_email: null, attendees: "not json" },
+ ],
+ contacts: [
+ // Met months ago: the meeting has aged out of the calendar cache.
+ { email: "[email protected]", display_name: "Priya Shah" },
+ { email: "[email protected]", display_name: "Gabe Torres" },
+ { email: "[email protected]", display_name: "Jean-Luc Picard" },
+ { email: "[email protected]", display_name: "Miles O'Brien" },
+ { email: "[email protected]", display_name: "Boardroom" },
+ // The owner of a colleague's shared Google calendar, synced from its events.
+ { email: "[email protected]", display_name: "Dana Wu" },
+ ],
+ // The user's addresses and a room some stored event flags.
+};
+
+const search = async (query, options = {}) => {
+ const { searchContacts } = await load();
+ return searchContacts(SOURCES, query, { now: NOW, ...options }).contacts;
+};
+
+test("a first name finds every matching person, the nearest meeting first", async () => {
+ const results = await search("gab");
+ assert.deepEqual(
+ results.map((person) => person.email),
+ );
+ assert.equal(results[0].name, "Gabe Torres");
+});
+
+test("lastMet is the most recent past meeting, never an upcoming one", async () => {
+ assert.equal((await search("gabe"))[0].lastMet, "2026-09-20T10:00:00Z");
+ assert.equal((await search("nora"))[0].lastMet, null);
+});
+
+test("people whose meetings aged out of the calendar are still found", async () => {
+ const [priya] = await search("priya");
+ assert.deepEqual(priya, { name: "Priya Shah", email: "[email protected]", lastMet: null });
+});
+
+test("a full name ranks the exact person first", async () => {
+ assert.equal((await search("Gabriel Stone"))[0].email, "[email protected]");
+});
+
+test("the owner of a colleague's shared calendar is still a contact", async () => {
+ assert.equal((await search("dana"))[0]?.email, "[email protected]");
+});
+
+test("the user, rooms, resources and holiday calendars never appear", async () => {
+ assert.deepEqual(await search("chad"), []);
+ assert.deepEqual(await search("room"), []);
+ assert.deepEqual(await search("holidays"), []);
+});
+
+test("accents, email local parts and spoken name forms match", async () => {
+ assert.equal((await search("zoe"))[0].name, "Zoë Müller");
+ assert.equal((await search("zoe muller"))[0].name, "Zoë Müller");
+ assert.equal((await search("boss"))[0].email, "[email protected]");
+ assert.equal((await search("sam lee"))[0].email, "[email protected]");
+ assert.equal((await search("jean luc"))[0].name, "Jean-Luc Picard");
+ assert.equal((await search("miles o brien"))[0].name, "Miles O'Brien");
+ assert.equal((await search("obrien"))[0].name, "Miles O'Brien");
+});
+
+test("an empty query and the limit are respected, and a cut-off list says so", async () => {
+ const { searchContacts } = await load();
+ assert.deepEqual(searchContacts(SOURCES, " ", { now: NOW }), { contacts: [], hasMore: false });
+ assert.deepEqual(searchContacts(SOURCES, "@", { now: NOW }), { contacts: [], hasMore: false });
+ const limited = searchContacts(SOURCES, "gab", { now: NOW, limit: 1 });
+ assert.equal(limited.contacts.length, 1);
+ assert.equal(limited.hasMore, true);
+ assert.equal(searchContacts(SOURCES, "priya", { now: NOW }).hasMore, false);
+});
+
+test("people seen only in contacts keep the most recently synced first", async () => {
+ const { searchContacts } = await load();
+ // getContactLookupSources returns contacts newest first.
+ const sources = {
+ contacts: [
+ { email: "[email protected]", display_name: "Josh Recent" },
+ { email: "[email protected]", display_name: "Josh Old" },
+ ],
+ };
+ assert.deepEqual(
+ searchContacts(sources, "josh", { now: NOW }).contacts.map((person) => person.email),
+ );
+});
+
+test("an all-day meeting starts at local midnight, not UTC midnight", async () => {
+ const { searchContacts } = await load();
+ const tomorrow = new Date(2026, 8, 25);
+ const tomorrowDate = "2026-09-25";
+ const sources = {
+ meetings: [
+ {
+ provider: "google",
+ start_time: tomorrowDate,
+ is_all_day: 1,
+ attendees: JSON.stringify([{ email: "[email protected]", displayName: "Offsite Host" }]),
+ },
+ ],
+ };
+ // An hour before it starts locally it hasn't happened yet, whatever the zone.
+ const [host] = searchContacts(sources, "offsite", {
+ now: tomorrow.getTime() - 60 * 60 * 1000,
+ }).contacts;
+ assert.equal(host.lastMet, null);
+ const [later] = searchContacts(sources, "offsite", {
+ now: tomorrow.getTime() + 60 * 60 * 1000,
+ }).contacts;
+ assert.equal(later.lastMet, tomorrowDate);
+});
+
+test("a typed address ranks its owner first", async () => {
+ const { searchContacts } = await load();
+ const sources = {
+ meetings: [meeting("2026-09-24T11:00:00Z", [{ email: "[email protected]", displayName: "Sal Z" }])],
+ contacts: [{ email: "[email protected]", display_name: "Al Gore" }],
+ };
+ const { contacts } = searchContacts(sources, "[email protected]", { now: NOW });
+ assert.equal(contacts[0].email, "[email protected]");
+});
+
+test("the domain only matches once the query has an @", async () => {
+ const sources = { contacts: [{ email: "[email protected]", display_name: "Chad" }] };
+ const { searchContacts } = await load();
+ assert.deepEqual(searchContacts(sources, "al", { now: NOW }).contacts, []);
+ assert.equal(searchContacts(sources, "chad@alias", { now: NOW }).contacts.length, 1);
+});
+
+test("equal matches rank the nearest meeting first, whatever order they were seen in", async () => {
+ const { searchContacts } = await load();
+ const sources = {
+ meetings: [
+ meeting("2026-08-01T10:00:00Z", [{ email: "[email protected]", displayName: "Josh Far" }]),
+ meeting("2026-09-25T10:00:00Z", [
+ { email: "[email protected]", displayName: "Josh Near" },
+ ]),
+ ],
+ };
+ assert.deepEqual(
+ searchContacts(sources, "josh", { now: NOW }).contacts.map((person) => person.email),
+ );
+});
diff --git a/test/helpers/connectors/emailCompose.test.js b/test/helpers/connectors/emailCompose.test.js
new file mode 100644
index 000000000..7fce0339d
--- /dev/null
+++ b/test/helpers/connectors/emailCompose.test.js
@@ -0,0 +1,298 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../../src/helpers/connectors/emailCompose.js");
+
+const TRICKY = {
+ cc: ["o'[email protected]"],
+ subject: "Lunch 🍜 & plans #1 — 50% off?",
+ body: "Hi Gabe,\n\nمرحبا — a+b=c & 100% sure? #yes\nSee you!",
+};
+
+test("web targets round-trip every field exactly", async () => {
+ const { buildComposeRequest } = await load();
+ const expected = {
+ gmail: { host: "mail.google.com", subjectKey: "su" },
+ outlookWork: { host: "outlook.office.com", subjectKey: "subject" },
+ outlookPersonal: { host: "outlook.live.com", subjectKey: "subject" },
+ };
+ for (const [target, { host, subjectKey }] of Object.entries(expected)) {
+ const { url, clipboardText } = buildComposeRequest({ target, ...TRICKY });
+ const parsed = new URL(url);
+ assert.equal(parsed.host, host, target);
+ assert.equal(parsed.searchParams.get("to"), TRICKY.to.join(","), target);
+ assert.equal(parsed.searchParams.get("cc"), TRICKY.cc.join(","), target);
+ assert.equal(parsed.searchParams.get(subjectKey), TRICKY.subject, target);
+ assert.equal(parsed.searchParams.get("body"), TRICKY.body, target);
+ assert.equal(clipboardText, null, target);
+ }
+});
+
+test("mailto keeps addresses readable and uses CRLF line breaks", async () => {
+ const { buildComposeRequest } = await load();
+ const { url } = buildComposeRequest({ target: "mailto", ...TRICKY });
+ const parsed = new URL(url);
+ assert.equal(parsed.protocol, "mailto:");
+ assert.equal(decodeURIComponent(parsed.pathname), TRICKY.to.join(","));
+ assert.equal(parsed.searchParams.get("subject"), TRICKY.subject);
+ assert.equal(parsed.searchParams.get("body"), TRICKY.body.replace(/\n/g, "\r\n"));
+ assert.match(url, /^mailto:gabe%2Blunch@example\.com,dana@example\.org\?/);
+});
+
+test("mailto turns every kind of line break into CRLF and keeps the subject on one line", async () => {
+ const { buildComposeRequest } = await load();
+ const { url } = buildComposeRequest({
+ target: "mailto",
+ subject: "Hi\r\nBcc: [email protected]",
+ body: "one\rtwo\nthree\r\nfour",
+ });
+ const parsed = new URL(url);
+ assert.equal(parsed.searchParams.get("subject"), "Hi Bcc: [email protected]");
+ assert.equal(parsed.searchParams.get("body"), "one\r\ntwo\r\nthree\r\nfour");
+});
+
+test("empty fields are left out of the URL", async () => {
+ const { buildComposeRequest } = await load();
+ const { url } = buildComposeRequest({ target: "outlookWork", to: ["[email protected]"] });
+ assert.equal(url, "https://outlook.office.com/mail/deeplink/[email protected]");
+});
+
+test("a body that would push the URL past the limit moves to the clipboard", async () => {
+ const { buildComposeRequest } = await load();
+ const body = "é".repeat(400);
+ const { url, clipboardText, bodyCopied } = buildComposeRequest({
+ target: "gmail",
+ subject: "Notes",
+ body,
+ });
+ assert.equal(clipboardText, body);
+ assert.equal(bodyCopied, true);
+ assert.equal(new URL(url).searchParams.get("body"), null);
+ assert.equal(new URL(url).searchParams.get("su"), "Notes");
+ assert.ok(url.length <= 2000);
+});
+
+test("a body that fits stays in the URL", async () => {
+ const { buildComposeRequest } = await load();
+ const body = "x".repeat(1500);
+ const { url, clipboardText } = buildComposeRequest({
+ target: "mailto",
+ body,
+ });
+ assert.equal(clipboardText, null);
+ assert.equal(new URL(url).searchParams.get("body"), body);
+});
+
+test("a subject too long for any link moves to the clipboard, even with no body", async () => {
+ const { buildComposeRequest } = await load();
+ const subject = "Quarterly planning ".repeat(120).trim();
+ for (const body of ["", "See the agenda below."]) {
+ const result = buildComposeRequest({
+ target: "outlookWork",
+ subject,
+ body,
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.subjectCopied, true);
+ assert.equal(result.clipboardText, body ? `${subject}\n\n${body}` : subject);
+ assert.equal(result.bodyCopied, Boolean(body));
+ assert.equal(new URL(result.url).searchParams.get("subject"), null);
+ assert.ok(result.url.length <= 2000);
+ }
+});
+
+test("recipients too long for any link are refused instead of opening a broken link", async () => {
+ const { buildComposeRequest } = await load();
+ const to = Array.from({ length: 120 }, (_, i) => `teammate.number.${i}@example.com`);
+ assert.deepEqual(buildComposeRequest({ target: "mailto", to, subject: "Hi", body: "Hello" }), {
+ ok: false,
+ reason: "too_long",
+ });
+});
+
+test("no returned link ever exceeds the limit", async () => {
+ const { buildComposeRequest, COMPOSE_TARGETS, maxComposeUrlLength } = await load();
+ for (const platform of ["darwin", "linux", "win32"]) {
+ for (const target of COMPOSE_TARGETS) {
+ const limit = maxComposeUrlLength(target, platform);
+ for (const recipients of [1, 10, 40, 80]) {
+ for (const subjectLength of [0, 50, 900, 2500]) {
+ for (const bodyLength of [0, 300, 1900, 5000]) {
+ const result = buildComposeRequest({
+ target,
+ to: Array.from({ length: recipients }, (_, i) => `person${i}@example.com`),
+ subject: "ü".repeat(subjectLength),
+ body: "é ".repeat(bodyLength),
+ platform,
+ });
+ if (result.ok) {
+ assert.ok(
+ result.url.length <= limit,
+ `${platform} ${target} ${recipients}/${subjectLength}/${bodyLength}: ${result.url.length}`
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+});
+
+test("Gmail on macOS and Linux keeps a longer non-ASCII body in the link", async () => {
+ const { buildComposeRequest, maxComposeUrlLength } = await load();
+ // ~500 Cyrillic characters encode to ~5,000 URL characters.
+ const body = "Привет, это письмо. ".repeat(25);
+ const request = (target, platform) =>
+ buildComposeRequest({ target, to: ["[email protected]"], subject: "Notes", body, platform });
+
+ for (const platform of ["darwin", "linux"]) {
+ const { url, clipboardText } = request("gmail", platform);
+ assert.equal(clipboardText, null, platform);
+ assert.equal(new URL(url).searchParams.get("body"), body, platform);
+ assert.ok(url.length <= maxComposeUrlLength("gmail", platform));
+ }
+ // Windows caps every opened URL near 2,081; the other targets are unmeasured.
+ assert.equal(request("gmail", "win32").clipboardText, body);
+ assert.equal(request("outlookWork", "darwin").clipboardText, body);
+ assert.equal(request("mailto", "linux").clipboardText, body);
+ assert.equal(maxComposeUrlLength("gmail", undefined), 2000);
+});
+
+test("email address validation", async () => {
+ const { isValidEmailAddress } = await load();
+ for (const good of [
+ "josé@münchen.de",
+ "info@пример.рф",
+ "a@παράδειγμα.gr",
+ // Scripts that spell words with combining marks after a label's first letter.
+ "a@उदाहरण.भारत",
+ "उपयोगकर्ता@उदाहरण.कॉम",
+ "a@ตัวอย่าง.ไทย",
+ "a@مِثال.com",
+ "a@উদাহরণ.বাংলা",
+ "a@இந்தியா.இந்தியா",
+ "jo\u0308rg@mu\u0308ller.de",
+ "山田@例え.jp",
+ "用户@例子.广告",
+ "사용자@예시.한국",
+ "משתמש@דוגמה.ישראל",
+ "a@ምሳሌ.et",
+ "a@straße.de",
+ "a@2гис.рф",
+ ]) {
+ assert.equal(isValidEmailAddress(good), true, good);
+ }
+ for (const bad of [
+ "Gabe",
+ "gabe@",
+ "@example.com",
+ "a@b",
+ "",
+ null,
+ ]) {
+ assert.equal(isValidEmailAddress(bad), false, String(bad));
+ }
+});
+
+test("addresses that could disguise the recipient or carry URL junk are refused", async () => {
+ const { isValidEmailAddress } = await load();
+ for (const bad of [
+ "‮[email protected]", // right-to-left override: displays as [email protected]
+ "[email protected]​.evil.io", // zero-width space
+ "alice‍@corp.com", // zero-width joiner
+ "[email protected]?subject=x",
+ "alice@corp\u3164.com", // Hangul filler: a letter that renders as nothing
+ "alice\[email protected]", // combining grapheme joiner
+ "alice@corp\u2060.com", // word joiner
+ "alice@c\u043Erp.com", // Cyrillic о inside a Latin label
+ "alice@\u03B1pple.com", // Greek α inside a Latin label
+ "alice@\u0585rp.com", // Armenian օ inside a Latin label
+ "a@я\u043D\u0434екс-mail.ru",
+ "alice\[email protected]", // lone surrogate
+ "alice@corp\u200C.com", // zero-width non-joiner
+ "a\[email protected]", // variation selector
+ "a\[email protected]", // soft hyphen
+ "[email protected]", // no domain has an all-numeric top level
+ ]) {
+ assert.equal(isValidEmailAddress(bad), false, JSON.stringify(bad));
+ }
+});
+
+test("a display-name form keeps only the address inside the brackets", async () => {
+ const { bareEmailAddress } = await load();
+ assert.equal(bareEmailAddress("Josh Lee <[email protected]>"), "[email protected]");
+ assert.equal(bareEmailAddress(' "Lee, Josh" < [email protected] > '), "[email protected]");
+ assert.equal(bareEmailAddress(" [email protected] "), "[email protected]");
+ // Anything else is left for the validator to refuse.
+ assert.equal(
+ bareEmailAddress("Josh <[email protected]> <[email protected]>"),
+ );
+ assert.equal(bareEmailAddress("Josh"), "Josh");
+ // A decomposed umlaut becomes the same address as the composed one.
+ assert.equal(bareEmailAddress("jo\u0308rg@mu\u0308ller.de"), "jörg@müller.de");
+});
+
+test("a recipient with a non-ASCII domain is labelled with the ASCII form it routes to", async () => {
+ const { recipientLabel } = await load();
+ assert.equal(recipientLabel("[email protected]"), "[email protected]");
+ assert.equal(recipientLabel("jö[email protected]"), "jö[email protected]");
+ // A whole-script look-alike of apple.com.
+ assert.equal(recipientLabel("a@аррӏе.com"), "a@аррӏе.com (xn--80ak6aa92e.com)");
+ assert.equal(recipientLabel("a@müller.de"), "a@müller.de (xn--mller-kva.de)");
+ assert.equal(recipientLabel("a@example.com"), "a@example.com (example.com)");
+ assert.equal(recipientLabel("a@उदाहरण.भारत"), "a@उदाहरण.भारत (xn--p1b6ci4b4b3a.xn--h2brj9c)");
+});
+
+test("half an emoji in the subject or body can't break the link", async () => {
+ const { buildComposeRequest } = await load();
+ for (const target of ["gmail", "mailto"]) {
+ const { url } = buildComposeRequest({
+ target,
+ subject: "Hi \uD83D",
+ body: "\uDC00 done",
+ platform: "darwin",
+ });
+ const params = new URL(url).searchParams;
+ assert.equal(params.get(target === "gmail" ? "su" : "subject"), "Hi \uFFFD");
+ assert.equal(params.get("body").replace(/\r/g, ""), "\uFFFD done");
+ }
+ // An overflowing body keeps the replacement on the clipboard too.
+ const { clipboardText } = buildComposeRequest({
+ target: "mailto",
+ body: `${"word ".repeat(600)}\uD83D`,
+ platform: "win32",
+ });
+ assert.ok(clipboardText.endsWith("\uFFFD"));
+});
+
+test("an unknown target is rejected", async () => {
+ const { buildComposeRequest } = await load();
+ assert.throws(
+ () => buildComposeRequest({ target: "yahoo", to: ["[email protected]"] }),
+ /Unknown compose target/
+ );
+});
diff --git a/test/helpers/connectors/emailConnector.test.js b/test/helpers/connectors/emailConnector.test.js
new file mode 100644
index 000000000..01da35c4d
--- /dev/null
+++ b/test/helpers/connectors/emailConnector.test.js
@@ -0,0 +1,341 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../../src/helpers/connectors/emailConnector.js");
+
+// Stands in for child_process.execFile: answers with an exit code and stdout.
+function fakeExecFile(code, stdout, calls = []) {
+ return (file, args, _options, callback) => {
+ calls.push([file, ...args]);
+ const error = code === 0 ? null : Object.assign(new Error("xdg-mime failed"), { code });
+ callback(error, stdout, "");
+ };
+}
+
+function fakes() {
+ const calls = { opened: [], copied: [] };
+ return {
+ calls,
+ deps: {
+ openExternal: async (url) => calls.opened.push(url),
+ writeClipboard: async (text, webContents) => calls.copied.push({ text, webContents }),
+ // The strictest link limit (2,000 for every target).
+ platform: "win32",
+ },
+ };
+}
+
+test("a draft opens the compose URL and never returns it", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const connector = createEmailConnector(deps);
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "gmail", to: ["[email protected]"], cc: [], subject: "Lunch", body: "Tomorrow at 1?" },
+ { webContents: "sender" }
+ );
+
+ assert.deepEqual(result, {
+ state: "sent",
+ destinationLabel: "[email protected]",
+ bodyCopied: false,
+ subjectCopied: false,
+ copyFailed: false,
+ });
+ assert.equal(calls.opened.length, 1);
+ assert.match(calls.opened[0], /^https:\/\/mail\.google\.com\//);
+ assert.equal(calls.copied.length, 0);
+});
+
+test("a long body goes to the clipboard through the caller's window", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const connector = createEmailConnector(deps);
+ const body = "word ".repeat(600);
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"], subject: "Notes", body, clipboardReserved: true },
+ { webContents: "sender" }
+ );
+
+ assert.equal(result.bodyCopied, true);
+ assert.equal(result.subjectCopied, false);
+ assert.deepEqual(calls.copied, [{ text: body, webContents: "sender" }]);
+ assert.doesNotMatch(calls.opened[0], /body=/);
+});
+
+test("a subject too long for a link goes to the clipboard with the body", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const subject = "Planning ".repeat(300).trim();
+
+ const result = await createEmailConnector(deps).runDirect(
+ "draft",
+ { target: "gmail", to: ["[email protected]"], subject, body: "Agenda", clipboardReserved: true },
+ { webContents: "sender" }
+ );
+
+ assert.equal(result.subjectCopied, true);
+ assert.equal(result.bodyCopied, true);
+ assert.deepEqual(calls.copied, [{ text: `${subject}\n\nAgenda`, webContents: "sender" }]);
+ assert.ok(calls.opened[0].length <= 2000);
+});
+
+test("a subject too long for a link with no body copies only the subject", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const subject = "Planning ".repeat(300).trim();
+
+ const result = await createEmailConnector(deps).runDirect(
+ "draft",
+ { target: "gmail", to: ["[email protected]"], subject, clipboardReserved: true },
+ {}
+ );
+
+ assert.equal(result.subjectCopied, true);
+ assert.equal(result.bodyCopied, false);
+ assert.deepEqual(calls.copied, [{ text: subject, webContents: null }]);
+});
+
+test("a draft that needs the clipboard opens nothing unless the turn reserved it", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+
+ const result = await createEmailConnector(deps).runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"], subject: "Notes", body: "word ".repeat(600) },
+ {}
+ );
+
+ assert.equal(result.state, "failed");
+ assert.equal(result.errorCode, "clipboard_unreserved");
+ assert.equal(calls.opened.length, 0);
+ assert.equal(calls.copied.length, 0);
+});
+
+test("a clipboard write that fails still reports the opened draft, without the text", async () => {
+ const { createEmailConnector } = await load();
+ const opened = [];
+ const connector = createEmailConnector({
+ openExternal: async (url) => opened.push(url),
+ writeClipboard: async () => {
+ throw new Error("clipboard locked");
+ },
+ platform: "win32",
+ });
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"], body: "word ".repeat(600), clipboardReserved: true },
+ {}
+ );
+
+ assert.equal(opened.length, 1);
+ assert.deepEqual(result, {
+ state: "sent",
+ destinationLabel: "[email protected]",
+ bodyCopied: false,
+ subjectCopied: false,
+ copyFailed: true,
+ });
+});
+
+test("a clipboard writer that reports failure counts as a failed copy", async () => {
+ const { createEmailConnector } = await load();
+ const connector = createEmailConnector({
+ openExternal: async () => {},
+ writeClipboard: async () => ({ success: false }),
+ platform: "win32",
+ });
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"], body: "word ".repeat(600), clipboardReserved: true },
+ {}
+ );
+
+ assert.equal(result.copyFailed, true);
+ assert.equal(result.bodyCopied, false);
+});
+
+test("a recipient with a non-ASCII domain is labelled with its punycode", async () => {
+ const { createEmailConnector } = await load();
+ const result = await createEmailConnector(fakes().deps).runDirect(
+ "draft",
+ { target: "gmail", to: ["a@аррӏе.com", "[email protected]"] },
+ {}
+ );
+ assert.equal(result.destinationLabel, "a@аррӏе.com (xn--80ak6aa92e.com), [email protected]");
+});
+
+test("the Linux mail-app probe refuses only a clear 'no default'", async () => {
+ const { hasLinuxMailtoHandler } = await load();
+ const probe = (code, stdout, env = {}) =>
+ hasLinuxMailtoHandler({ execFile: fakeExecFile(code, stdout), env });
+
+ assert.equal(await probe(0, "thunderbird.desktop\n"), true);
+ assert.equal(await probe(0, "\n"), false);
+ // KDE 5's xdg-mime exits 4 with nothing to say when no default is set.
+ assert.equal(await probe(4, ""), false);
+ // Any other failure (xdg-mime missing, a timeout, a syntax error) lets the
+ // open go ahead and report itself.
+ assert.equal(await probe("ENOENT", ""), true);
+ assert.equal(await probe(null, ""), true);
+ assert.equal(await probe(1, ""), true);
+});
+
+test("inside Flatpak the probe doesn't ask xdg-mime", async () => {
+ const { hasLinuxMailtoHandler } = await load();
+ const calls = [];
+ const result = await hasLinuxMailtoHandler({
+ execFile: fakeExecFile(0, "", calls),
+ env: { FLATPAK_ID: "com.openwhispr.App" },
+ });
+ assert.equal(result, true);
+ assert.deepEqual(calls, []);
+
+ await hasLinuxMailtoHandler({ execFile: fakeExecFile(0, "", calls), env: {} });
+ assert.deepEqual(calls, [["xdg-mime", "query", "default", "x-scheme-handler/mailto"]]);
+});
+
+test("on Linux, a mailto draft with no default mail app opens nothing", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ let queried = 0;
+ const connector = createEmailConnector({
+ ...deps,
+ platform: "linux",
+ hasMailtoHandler: async () => {
+ queried += 1;
+ return false;
+ },
+ });
+ const draft = { to: ["[email protected]"], body: "word ".repeat(600), clipboardReserved: true };
+
+ const result = await connector.runDirect("draft", { ...draft, target: "mailto" }, {});
+ assert.equal(result.errorCode, "open_failed");
+ assert.match(result.message, /default email app/);
+ assert.equal(calls.opened.length, 0);
+ assert.equal(calls.copied.length, 0);
+
+ // Web targets don't need a local mail app.
+ await connector.runDirect("draft", { ...draft, target: "gmail" }, {});
+ assert.equal(queried, 1);
+ assert.equal(calls.opened.length, 1);
+});
+
+test("on Linux, a mailto draft opens when a mail app handles mailto", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const connector = createEmailConnector({
+ ...deps,
+ platform: "linux",
+ hasMailtoHandler: async () => true,
+ });
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"] },
+ {}
+ );
+
+ assert.equal(result.state, "sent");
+ assert.match(calls.opened[0], /^mailto:/);
+});
+
+test("too many recipients for any link opens nothing", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const to = Array.from({ length: 120 }, (_, i) => `teammate.number.${i}@example.com`);
+
+ const result = await createEmailConnector(deps).runDirect(
+ "draft",
+ { target: "mailto", to, subject: "Hi" },
+ {}
+ );
+
+ assert.equal(result.state, "failed");
+ assert.equal(result.errorCode, "draft_too_long");
+ assert.equal(calls.opened.length, 0);
+ assert.equal(calls.copied.length, 0);
+});
+
+test("a name instead of an address is refused before anything opens", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ const connector = createEmailConnector(deps);
+
+ const result = await connector.runDirect(
+ "draft",
+ { target: "gmail", to: ["Gabe"], subject: "x", body: "y" },
+ {}
+ );
+
+ assert.equal(result.state, "failed");
+ assert.equal(result.errorCode, "invalid_address");
+ assert.equal(calls.opened.length, 0);
+});
+
+test("an unknown target falls back to the default mail app", async () => {
+ const { createEmailConnector } = await load();
+ const { calls, deps } = fakes();
+ await createEmailConnector(deps).runDirect(
+ "draft",
+ { target: "yahoo", to: ["[email protected]"] },
+ {}
+ );
+ assert.match(calls.opened[0], /^mailto:/);
+});
+
+test("a failure to open the mail app is reported, not thrown", async () => {
+ const { createEmailConnector } = await load();
+ const connector = createEmailConnector({
+ openExternal: async () => {
+ throw new Error("no handler");
+ },
+ writeClipboard: async () => {},
+ platform: "win32",
+ });
+ const result = await connector.runDirect(
+ "draft",
+ { target: "mailto", to: ["[email protected]"] },
+ {}
+ );
+ assert.equal(result.errorCode, "open_failed");
+ // The receipt still says whose draft didn't open.
+ assert.equal(result.destinationLabel, "[email protected]");
+});
+
+test("a draft that fails to open leaves the user's clipboard alone", async () => {
+ const { createEmailConnector } = await load();
+ const copied = [];
+ const connector = createEmailConnector({
+ openExternal: async () => {
+ throw new Error("no handler");
+ },
+ writeClipboard: async (text) => copied.push(text),
+ platform: "win32",
+ });
+ const result = await connector.runDirect(
+ "draft",
+ {
+ target: "mailto",
+ subject: "Notes",
+ body: "word ".repeat(600),
+ clipboardReserved: true,
+ },
+ {}
+ );
+ assert.equal(result.errorCode, "open_failed");
+ assert.deepEqual(copied, []);
+});
+
+test("the email connector is always connected and has no approval actions", async () => {
+ const { createEmailConnector } = await load();
+ const connector = createEmailConnector(fakes().deps);
+ assert.deepEqual(await connector.getStatus(), { connected: true, accountLabel: null });
+ assert.deepEqual(connector.actions, { draft: { kind: "direct" } });
+});
diff --git a/test/helpers/connectors/pendingActions.test.js b/test/helpers/connectors/pendingActions.test.js
new file mode 100644
index 000000000..6ceec0fce
--- /dev/null
+++ b/test/helpers/connectors/pendingActions.test.js
@@ -0,0 +1,135 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../../src/helpers/connectors/pendingActions.js");
+
+const BINDING = { accountId: "U1", workspaceId: "T1", generation: 1 };
+
+function makeStore(overrides = {}) {
+ let clock = 1_000;
+ let counter = 0;
+ return load().then(({ createPendingActions }) => ({
+ store: createPendingActions({
+ now: () => clock,
+ randomId: () => `action-${++counter}`,
+ ...overrides,
+ }),
+ advance: (ms) => {
+ clock += ms;
+ },
+ }));
+}
+
+function prepareOne(store, connectorId = "slack") {
+ return store.create({
+ connectorId,
+ action: "send_message",
+ binding: BINDING,
+ payload: { channel: "C1" },
+ preview: { destinationLabel: "#eng" },
+ });
+}
+
+test("a created action is pending and readable", async () => {
+ const { store } = await makeStore();
+ const actionId = prepareOne(store);
+ assert.equal(actionId, "action-1");
+ assert.equal(store.get(actionId).state, "pending");
+ assert.deepEqual(store.get(actionId).payload, { channel: "C1" });
+});
+
+test("beginCommit moves a pending action to committing exactly once", async () => {
+ const { store } = await makeStore();
+ const actionId = prepareOne(store);
+
+ const first = store.beginCommit(actionId, { ...BINDING });
+ const second = store.beginCommit(actionId, { ...BINDING });
+
+ assert.equal(first.ok, true);
+ assert.equal(first.entry.state, "committing");
+ assert.deepEqual(second, { ok: false, reason: "not_pending" });
+});
+
+test("cancel is refused once an action is committing", async () => {
+ const { store } = await makeStore();
+ const actionId = prepareOne(store);
+ store.beginCommit(actionId, { ...BINDING });
+
+ assert.equal(store.cancel(actionId), false);
+ assert.equal(store.get(actionId).state, "committing");
+});
+
+test("finish only settles committing actions and then forgets them", async () => {
+ const { store } = await makeStore();
+ const actionId = prepareOne(store);
+ assert.equal(store.finish(actionId), false);
+
+ store.beginCommit(actionId, { ...BINDING });
+ assert.equal(store.finish(actionId), true);
+ assert.equal(store.get(actionId), null);
+ assert.deepEqual(store.beginCommit(actionId, BINDING), { ok: false, reason: "not_found" });
+});
+
+test("a pending action expires after the TTL", async () => {
+ const { PENDING_TTL_MS } = await load();
+ const { store, advance } = await makeStore();
+ const actionId = prepareOne(store);
+
+ advance(PENDING_TTL_MS + 1);
+
+ assert.deepEqual(store.beginCommit(actionId, BINDING), { ok: false, reason: "expired" });
+ assert.equal(store.get(actionId), null);
+});
+
+test("sweepExpired drops only expired pending actions", async () => {
+ const { PENDING_TTL_MS } = await load();
+ const { store, advance } = await makeStore();
+ const stale = prepareOne(store);
+ const committing = prepareOne(store);
+ store.beginCommit(committing, BINDING);
+ advance(PENDING_TTL_MS + 1);
+ const fresh = prepareOne(store);
+
+ assert.deepEqual(store.sweepExpired(), [stale]);
+ assert.equal(store.get(stale), null);
+ assert.equal(store.get(committing).state, "committing");
+ assert.equal(store.get(fresh).state, "pending");
+});
+
+test("a changed account, workspace or generation refuses the commit", async () => {
+ const { store } = await makeStore();
+ for (const changed of [
+ { ...BINDING, accountId: "U2" },
+ { ...BINDING, workspaceId: "T2" },
+ { ...BINDING, generation: 2 },
+ null,
+ ]) {
+ const actionId = prepareOne(store);
+ assert.deepEqual(store.beginCommit(actionId, changed), {
+ ok: false,
+ reason: "connection_changed",
+ });
+ assert.equal(store.get(actionId), null);
+ }
+});
+
+test("invalidateConnector cancels only that connector's pending actions", async () => {
+ const { store } = await makeStore();
+ const slackPending = prepareOne(store, "slack");
+ const slackCommitting = prepareOne(store, "slack");
+ const linearPending = prepareOne(store, "linear");
+ store.beginCommit(slackCommitting, BINDING);
+
+ assert.deepEqual(store.invalidateConnector("slack"), [slackPending]);
+ assert.equal(store.get(slackPending), null);
+ assert.equal(store.get(slackCommitting).state, "committing");
+ assert.equal(store.get(linearPending).state, "pending");
+});
+
+test("the default id generator returns distinct 128-bit hex ids", async () => {
+ const { createPendingActions } = await load();
+ const store = createPendingActions();
+ const ids = new Set(Array.from({ length: 50 }, () => prepareOne(store)));
+ assert.equal(ids.size, 50);
+ for (const id of ids) assert.match(id, /^[0-9a-f]{32}$/);
+});
diff --git a/test/helpers/googleCalendarManager.test.js b/test/helpers/googleCalendarManager.test.js
index dfc32b102..a2f6ac52b 100644
--- a/test/helpers/googleCalendarManager.test.js
+++ b/test/helpers/googleCalendarManager.test.js
@@ -39,7 +39,7 @@ test("_syncCalendar fetches all pages when nextPageToken is returned", async ()
updateCalendarSyncToken: (calendarId, syncToken) => {
savedSyncToken = syncToken;
},
- upsertContacts: () => {},
+ syncCalendarContacts: () => {},
};
const reminderScheduler = {
@@ -113,7 +113,7 @@ test("_syncCalendar preserves incremental sync parameters across pages", async (
upsertCalendarEvents: () => {},
removeCalendarEvents: () => {},
updateCalendarSyncToken: () => {},
- upsertContacts: () => {},
+ syncCalendarContacts: () => {},
};
const reminderScheduler = {
scheduleNextMeeting: () => {},
@@ -158,7 +158,7 @@ test("_syncCalendar discards an expired sync token and re-runs a full window syn
updateCalendarSyncToken: (calendarId, syncToken, expiresAt) => {
savedToken = { calendarId, syncToken, expiresAt };
},
- upsertContacts: () => {},
+ syncCalendarContacts: () => {},
};
const reminderScheduler = { scheduleNextMeeting: () => {}, reset: () => {} };
const manager = new GoogleCalendarManager(databaseManager, null, reminderScheduler);
@@ -200,7 +200,7 @@ test("_syncCalendar keeps the stored expiry when an incremental sync reuses the
updateCalendarSyncToken: (calendarId, syncToken, expiresAt) => {
savedToken = { calendarId, syncToken, expiresAt };
},
- upsertContacts: () => {},
+ syncCalendarContacts: () => {},
};
const reminderScheduler = { scheduleNextMeeting: () => {}, reset: () => {} };
const manager = new GoogleCalendarManager(databaseManager, null, reminderScheduler);
@@ -235,7 +235,7 @@ test("_syncCalendar preserves meeting links from Google event location and descr
},
removeCalendarEvents: () => {},
updateCalendarSyncToken: () => {},
- upsertContacts: () => {},
+ syncCalendarContacts: () => {},
};
const reminderScheduler = {
scheduleNextMeeting: () => {},
@@ -287,3 +287,93 @@ test("_syncCalendar preserves meeting links from Google event location and descr
]
);
});
+
+test("_syncCalendar flags rooms and resources and keeps them and the user out of contacts", async () => {
+ const GoogleCalendarManager = loadManagerModule();
+ const upsertedEvents = [];
+ const synced = [];
+ const databaseManager = {
+ getGoogleAccounts: () => [],
+ removeStaleCalendarEvents: () => {},
+ upsertCalendarEvents: (events) => upsertedEvents.push(...events),
+ removeCalendarEvents: () => {},
+ updateCalendarSyncToken: () => {},
+ syncCalendarContacts: (...args) => synced.push(args),
+ };
+ const manager = new GoogleCalendarManager(databaseManager, null, {
+ scheduleNextMeeting: () => {},
+ reset: () => {},
+ });
+ manager._apiGet = async () => ({
+ items: [
+ {
+ id: "event-room",
+ summary: "Planning",
+ start: { dateTime: "2026-08-12T10:00:00Z" },
+ attendees: [
+ { email: "[email protected]", displayName: "Ana", responseStatus: "accepted" },
+ { email: "[email protected]", displayName: "Boardroom", resource: true },
+ { email: "[email protected]", displayName: "Me", self: true },
+ ],
+ },
+ ],
+ nextSyncToken: "sync-token",
+ });
+
+ await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });
+
+ const attendees = JSON.parse(upsertedEvents[0].attendees);
+ assert.equal(attendees[0].resource, undefined);
+ assert.equal(attendees[1].resource, true);
+ // Rows older builds stored for the room and the user are purged.
+ assert.deepEqual(synced, [
+ [
+ "google",
+ [{ email: "[email protected]", displayName: "Ana" }],
+ ],
+ ]);
+});
+
+test("_syncCalendar trusts self as the user only on the account's primary calendar", async () => {
+ const GoogleCalendarManager = loadManagerModule();
+ const synced = [];
+ const manager = new GoogleCalendarManager(
+ {
+ getGoogleAccounts: () => [],
+ removeStaleCalendarEvents: () => {},
+ upsertCalendarEvents: () => {},
+ removeCalendarEvents: () => {},
+ updateCalendarSyncToken: () => {},
+ syncCalendarContacts: (...args) => synced.push(args),
+ },
+ null,
+ { scheduleNextMeeting: () => {}, reset: () => {} }
+ );
+ manager._apiGet = async () => ({
+ items: [
+ {
+ id: "event-1",
+ start: { dateTime: "2026-08-12T10:00:00Z" },
+ // Self on the user's primary calendar is them (under an alias here);
+ // on a colleague's shared calendar it is that colleague.
+ attendees: [{ email: "[email protected]", self: true }],
+ },
+ ],
+ nextSyncToken: "sync-token",
+ });
+
+ await manager._syncCalendar({ id: "[email protected]", account_email: "[email protected]" });
+ await manager._syncCalendar({ id: "cal-2", account_email: "[email protected]", is_primary: 1 });
+ await manager._syncCalendar({ id: "[email protected]", account_email: "[email protected]" });
+
+ assert.deepEqual(
+ synced.map(([, , contacts, notContacts]) => [contacts.length, notContacts]),
+ [
+ [0, ["[email protected]"]],
+ [0, ["[email protected]"]],
+ [1, []],
+ ]
+ );
+});
diff --git a/test/helpers/microsoftCalendarManager.test.js b/test/helpers/microsoftCalendarManager.test.js
index a04946f2d..87c893be1 100644
--- a/test/helpers/microsoftCalendarManager.test.js
+++ b/test/helpers/microsoftCalendarManager.test.js
@@ -144,8 +144,9 @@ function createManager(MicrosoftCalendarManager, upserted, contacts = [], overri
upsertCalendarEvents: (events) => upserted.push(...events),
removeCalendarEvents: () => {},
updateMicrosoftCalendarSyncToken: () => {},
- upsertContacts: (rows) => contacts.push(...rows),
+ syncCalendarContacts: (_provider, _accountEmail, rows) => contacts.push(...rows),
getCalendarEventById: () => null,
+ getMicrosoftOwnAddresses: () => [],
...overrides,
},
{}
@@ -201,7 +202,7 @@ test("_syncCalendar backfills stripped recurring occurrences from their series m
organizer: { emailAddress: { address: "[email protected]" } },
attendees: [
{
- emailAddress: { address: "[email protected]", name: "Me" },
+ emailAddress: { address: "[email protected]", name: "Teammate" },
status: { response: "accepted" },
},
],
@@ -221,7 +222,7 @@ test("_syncCalendar backfills stripped recurring occurrences from their series m
assert.equal(occurrence.attendees_count, 1);
assert.equal(upserted.find((event) => event.id === "occ-2").summary, "Standup");
assert.equal(upserted.find((event) => event.id === "evt-1").summary, "One-off");
- assert.ok(contacts.some((contact) => contact.email === "[email protected]"));
+ assert.ok(contacts.some((contact) => contact.email === "[email protected]"));
assert.ok(tokenWrites[0].expiresAt > Date.now() + 6 * 24 * 60 * 60 * 1000);
});
@@ -308,3 +309,141 @@ test("_syncCalendar keeps the stored row when a stripped occurrence's master fet
);
assert.deepEqual(staleKeepLists, [["occ-1", "evt-1"]]);
});
+
+test("_syncCalendar flags rooms and resources and keeps them and the user out of contacts", async () => {
+ const MicrosoftCalendarManager = loadManagerModule();
+ const upserted = [];
+ const synced = [];
+ const manager = createManager(MicrosoftCalendarManager, upserted, [], {
+ syncCalendarContacts: (...args) => synced.push(args),
+ });
+ manager._apiGet = async () => ({
+ "@odata.deltaLink": "delta-link",
+ value: [
+ {
+ id: "evt-room",
+ subject: "Planning",
+ start: { dateTime: "2026-07-20T17:00:00.0000000" },
+ end: { dateTime: "2026-07-20T17:30:00.0000000" },
+ attendees: [
+ {
+ type: "required",
+ emailAddress: { address: "[email protected]", name: "Ana" },
+ status: { response: "accepted" },
+ },
+ {
+ type: "resource",
+ emailAddress: { address: "[email protected]", name: "Boardroom" },
+ status: { response: "accepted" },
+ },
+ {
+ type: "required",
+ emailAddress: { address: "[email protected]", name: "Me" },
+ status: { response: "organizer" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });
+
+ const attendees = JSON.parse(upserted[0].attendees);
+ assert.equal(attendees[0].resource, undefined);
+ assert.equal(attendees[1].resource, true);
+ // Rows older builds stored for the room and the user are purged.
+ assert.deepEqual(synced, [
+ [
+ "microsoft",
+ [{ email: "[email protected]", displayName: "Ana" }],
+ ],
+ ]);
+});
+
+test("_syncCalendar keeps the user's other Microsoft addresses out of contacts", async () => {
+ const MicrosoftCalendarManager = loadManagerModule();
+ const synced = [];
+ const manager = createManager(MicrosoftCalendarManager, [], [], {
+ getMicrosoftOwnAddresses: (email) =>
+ email === "[email protected]" ? ["[email protected]"] : [],
+ syncCalendarContacts: (...args) => synced.push(args),
+ });
+ manager._apiGet = async () => ({
+ "@odata.deltaLink": "delta-link",
+ value: [
+ {
+ id: "evt-1",
+ subject: "Planning",
+ start: { dateTime: "2026-07-20T17:00:00.0000000" },
+ end: { dateTime: "2026-07-20T17:30:00.0000000" },
+ attendees: [
+ { type: "required", emailAddress: { address: "[email protected]", name: "Ana" } },
+ { type: "required", emailAddress: { address: "[email protected]", name: "Chad" } },
+ ],
+ },
+ ],
+ });
+
+ await manager._syncCalendar({ id: "cal-1", account_email: "[email protected]" });
+
+ assert.deepEqual(synced[0].slice(2), [
+ [{ email: "[email protected]", displayName: "Ana" }],
+ ]);
+});
+
+test("fetchCalendars stores the account's mail, sign-in name and SMTP aliases", async () => {
+ const MicrosoftCalendarManager = loadManagerModule();
+ const saved = [];
+ const manager = new MicrosoftCalendarManager(
+ {
+ saveMicrosoftCalendars: () => {},
+ saveMicrosoftOwnAddresses: (email, addresses) => saved.push([email, addresses]),
+ applyMicrosoftPrimaryOnlyToSelection: () => {},
+ removeEventsFromDeselectedCalendars: () => {},
+ },
+ {}
+ );
+ const paths = [];
+ manager._apiGet = async (path) => {
+ paths.push(path);
+ if (path.startsWith("/me/calendars")) return { value: [] };
+ return {
+ userPrincipalName: "[email protected]",
+ proxyAddresses: ["SMTP:[email protected]", "smtp:[email protected]", "SIP:[email protected]"],
+ };
+ };
+
+ await manager.fetchCalendars("[email protected]");
+
+ assert.deepEqual(saved, [
+ ]);
+ assert.ok(paths.includes("/me?$select=mail,userPrincipalName,proxyAddresses"));
+});
+
+test("fetchCalendars still saves the calendars when the address lookup fails", async () => {
+ const MicrosoftCalendarManager = loadManagerModule();
+ const savedCalendars = [];
+ const manager = new MicrosoftCalendarManager(
+ {
+ saveMicrosoftCalendars: (calendars) => savedCalendars.push(...calendars),
+ saveMicrosoftOwnAddresses: () => assert.fail("nothing to save"),
+ applyMicrosoftPrimaryOnlyToSelection: () => {},
+ removeEventsFromDeselectedCalendars: () => {},
+ },
+ {}
+ );
+ manager._apiGet = async (path) => {
+ if (path.startsWith("/me?")) throw new Error("API error 400");
+ return { value: [{ id: "cal-1", name: "Calendar", isDefaultCalendar: true }] };
+ };
+
+ const calendars = await manager.fetchCalendars("[email protected]");
+
+ assert.equal(calendars.length, 1);
+ assert.equal(savedCalendars.length, 1);
+});
diff --git a/test/helpers/microsoftCalendarOAuth.test.js b/test/helpers/microsoftCalendarOAuth.test.js
new file mode 100644
index 000000000..4add76676
--- /dev/null
+++ b/test/helpers/microsoftCalendarOAuth.test.js
@@ -0,0 +1,84 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+const oauthModulePath = require.resolve("../../src/helpers/microsoftCalendarOAuth.js");
+const originalLoad = Module._load;
+let flowOptions = null;
+
+function loadOAuth() {
+ delete require.cache[oauthModulePath];
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "electron") return { net: {} };
+ if (request === "./oauthLoopbackFlow") {
+ return {
+ runOAuthLoopbackFlow: (options) => {
+ flowOptions = options;
+ return options;
+ },
+ OAuthFlowError: Error,
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ try {
+ return require(oauthModulePath);
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+const idToken = (claims) =>
+ ["header", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".");
+
+function createOAuth(saved) {
+ const MicrosoftCalendarOAuth = loadOAuth();
+ return new MicrosoftCalendarOAuth({ saveMicrosoftTokens: (tokens) => saved.push(tokens) });
+}
+
+test("signing in stores and returns the id_token's tenant", async () => {
+ const saved = [];
+ const oauth = createOAuth(saved);
+ oauth.getClientId = () => "client-id";
+ oauth.startOAuthFlow();
+ oauth.exchangeCodeForTokens = async () => ({
+ access_token: "access",
+ refresh_token: "refresh",
+ expires_in: 3600,
+ id_token: idToken({ email: "[email protected]", tid: "tenant-1" }),
+ });
+
+ const result = await flowOptions.handleCallback("code", "http://127.0.0.1/cb", "verifier");
+
+ assert.deepEqual(result, { success: true, email: "[email protected]", tenantId: "tenant-1" });
+ assert.equal(saved[0].tenant_id, "tenant-1");
+});
+
+test("a refresh without an id_token saves no tenant, so the stored one is kept", async () => {
+ const saved = [];
+ const oauth = createOAuth(saved);
+ oauth.refreshAccessToken = async () => ({ access_token: "new", expires_in: 3600 });
+
+ await oauth._refreshAndSaveTokens({
+ microsoft_email: "[email protected]",
+ refresh_token: "refresh",
+ scope: "scope",
+ });
+
+ assert.equal(saved[0].tenant_id, null);
+ assert.equal(saved[0].refresh_token, "refresh");
+});
+
+test("a refresh with an id_token saves its tenant", async () => {
+ const saved = [];
+ const oauth = createOAuth(saved);
+ oauth.refreshAccessToken = async () => ({
+ access_token: "new",
+ expires_in: 3600,
+ id_token: idToken({ tid: "tenant-2" }),
+ });
+
+ await oauth._refreshAndSaveTokens({ microsoft_email: "[email protected]", refresh_token: "r" });
+
+ assert.equal(saved[0].tenant_id, "tenant-2");
+});
diff --git a/test/helpers/settingsStoreMicrosoftAccounts.test.js b/test/helpers/settingsStoreMicrosoftAccounts.test.js
new file mode 100644
index 000000000..fb1f9df15
--- /dev/null
+++ b/test/helpers/settingsStoreMicrosoftAccounts.test.js
@@ -0,0 +1,87 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const SAVED_ACCOUNTS = [{ email: "[email protected]" }];
+
+async function startSettings(t, { mcalGetConnectionStatus, storageListeners = [] }) {
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage: {
+ mcalAccounts: JSON.stringify(SAVED_ACCOUNTS),
+ // Already holds the agent name, so startup writes no dictionary and
+ // starts no cloud sync that would outlive the test's module server.
+ customDictionary: '["OpenWhispr"]',
+ },
+ window: {
+ addEventListener(type, listener) {
+ if (type === "storage") storageListeners.push(listener);
+ },
+ electronAPI: {
+ getOpenAIKey: async () => "",
+ setDictionary: async () => {},
+ mcalGetConnectionStatus,
+ },
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-settings-mcal-accounts-test-",
+ });
+ const { initializeSettings, useSettingsStore } = await vite.ssrLoadModule(
+ "/stores/settingsStore.ts"
+ );
+ try {
+ await initializeSettings();
+ } finally {
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("en");
+ }
+ return { storage, useSettingsStore };
+}
+
+test("startup replaces the saved Microsoft accounts with main's, tenant ids included", async (t) => {
+ const accounts = [
+ { email: "[email protected]", tenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47" },
+ { email: "[email protected]", tenantId: null },
+ ];
+ const { storage, useSettingsStore } = await startSettings(t, {
+ mcalGetConnectionStatus: async () => ({ connected: true, accounts }),
+ });
+ assert.deepEqual(useSettingsStore.getState().mcalAccounts, accounts);
+ assert.equal(useSettingsStore.getState().mcalConnected, true);
+ assert.deepEqual(JSON.parse(storage.getItem("mcalAccounts")), accounts);
+});
+
+test("an empty answer leaves the saved Microsoft accounts alone", async (t) => {
+ const { storage, useSettingsStore } = await startSettings(t, {
+ mcalGetConnectionStatus: async () => ({ connected: false, accounts: [] }),
+ });
+ assert.deepEqual(useSettingsStore.getState().mcalAccounts, SAVED_ACCOUNTS);
+ assert.deepEqual(JSON.parse(storage.getItem("mcalAccounts")), SAVED_ACCOUNTS);
+});
+
+test("a failed read leaves the saved Microsoft accounts alone", async (t) => {
+ const { storage, useSettingsStore } = await startSettings(t, {
+ mcalGetConnectionStatus: async () => {
+ throw new Error("ipc down");
+ },
+ });
+ assert.deepEqual(useSettingsStore.getState().mcalAccounts, SAVED_ACCOUNTS);
+ assert.deepEqual(JSON.parse(storage.getItem("mcalAccounts")), SAVED_ACCOUNTS);
+});
+
+test("a draft target synced from another window is normalised", async (t) => {
+ const storageListeners = [];
+ const { storage, useSettingsStore } = await startSettings(t, {
+ mcalGetConnectionStatus: async () => ({ connected: false, accounts: [] }),
+ storageListeners,
+ });
+ const sync = (newValue) =>
+ storageListeners.forEach((listener) =>
+ listener({ key: "emailDraftTarget", newValue, storageArea: storage })
+ );
+
+ sync("gmail");
+ assert.equal(useSettingsStore.getState().emailDraftTarget, "gmail");
+ sync("yahoo");
+ assert.equal(useSettingsStore.getState().emailDraftTarget, "auto");
+});
diff --git a/test/helpers/useChatStreamingTools.test.js b/test/helpers/useChatStreamingTools.test.js
new file mode 100644
index 000000000..db43d7cea
--- /dev/null
+++ b/test/helpers/useChatStreamingTools.test.js
@@ -0,0 +1,394 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const React = require("react");
+const { renderToStaticMarkup } = require("react-dom/server");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// Drives the real useChatStreaming hook (one synchronous render, then its
+// sendToAI closure; see useChatStreamingCancellation.test.js) on the
+// OpenWhispr Cloud path, with the stream itself stubbed so the test can see
+// which tools a send offers the model.
+async function renderChatStreaming(
+ t,
+ hookOptions = {},
+ { settings = {}, electronAPI = {}, subscribed = true } = {}
+) {
+ installBrowserGlobals(t, {
+ initialStorage: { isSubscribed: String(subscribed) },
+ window: { electronAPI },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-chat-streaming-tools-test-",
+ });
+ const [{ default: viteI18next }, { initReactI18next }] = await Promise.all([
+ vite.ssrLoadModule("i18next"),
+ vite.ssrLoadModule("react-i18next"),
+ ]);
+ if (!viteI18next.isInitialized) {
+ const translation = JSON.parse(
+ fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")
+ );
+ await viteI18next.use(initReactI18next).init({
+ lng: "en",
+ resources: { en: { translation } },
+ interpolation: { escapeValue: false },
+ });
+ }
+
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });
+ useSettingsStore.setState({ chatAgentMode: "openwhispr", isSignedIn: true, ...settings });
+
+ const { useChatStreaming } = await vite.ssrLoadModule("/components/chat/useChatStreaming.ts");
+ // The app's i18n module (loaded with the tools) follows the machine's locale.
+ await (await vite.ssrLoadModule("/i18n.ts")).default.changeLanguage("en");
+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
+ t.after(() => reasoningService.destroy());
+
+ const offeredTools = [];
+ const endStream = async function* () {
+ yield { type: "done", finishReason: "stop" };
+ };
+ t.mock.method(reasoningService, "processTextStreamingCloud", (_messages, config) => {
+ offeredTools.push((config.tools ?? []).map((tool) => tool.name));
+ return endStream();
+ });
+ t.mock.method(
+ reasoningService,
+ "processTextStreamingAI",
+ (_messages, _model, _provider, _config, tools) => {
+ offeredTools.push(Object.keys(tools ?? {}));
+ return endStream();
+ }
+ );
+
+ let messages = [];
+ const setMessages = (updater) => {
+ messages = typeof updater === "function" ? updater(messages) : updater;
+ };
+ let captured = null;
+ function Harness() {
+ captured = useChatStreaming({ messages, setMessages, ...hookOptions });
+ return null;
+ }
+ renderToStaticMarkup(React.createElement(Harness));
+ return { captured, offeredTools, reasoningService, usePolicyStore, getMessages: () => messages };
+}
+
+// Typed chat and the voice panel opt in; every other surface leaves it off.
+const CONNECTOR_SURFACE = { allowConnectors: true };
+const BYOK_SETTINGS = {
+ chatAgentMode: "providers",
+ chatAgentProvider: "openai",
+ chatAgentModel: "gpt-5-mini",
+};
+const MANAGED_POLICY = {
+ version: 1,
+ transcription: { allowedModes: ["openwhispr"], allowedByokProviders: [] },
+ llm: { allowedModes: ["openwhispr"], allowedByokProviders: [], allowedEnterpriseProviders: [] },
+ features: { agentEnabled: true, webSearchEnabled: true, connectorsEnabled: true },
+ sharing: { externalLinkSharing: "disabled" },
+ dataRetention: {
+ audioRetentionMaxDays: null,
+ localHistoryMode: "user_choice",
+ cloudBackupAllowed: true,
+ },
+ minAppVersion: null,
+};
+
+function offersConnectors(tools) {
+ return tools.includes("email_draft") || tools.includes("find_contact");
+}
+
+test("a paid, signed-in chat offers the connector tools", async (t) => {
+ const { captured, offeredTools } = await renderChatStreaming(t, CONNECTOR_SURFACE);
+ await captured.sendToAI("Email Josh", []);
+ assert.ok(offeredTools[0].includes("email_draft"));
+ assert.ok(offeredTools[0].includes("find_contact"));
+});
+
+test("a surface that doesn't opt in (note or container chat) never offers them", async (t) => {
+ const { captured, offeredTools } = await renderChatStreaming(t);
+ await captured.sendToAI("Reply to Maria", []);
+ assert.ok(offeredTools[0].length > 0);
+ assert.equal(offersConnectors(offeredTools[0]), false);
+});
+
+test("a signed-out chat never offers them", async (t) => {
+ const { captured, offeredTools } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ settings: { ...BYOK_SETTINGS, isSignedIn: false },
+ });
+ await captured.sendToAI("Email Josh", []);
+ assert.ok(offeredTools[0].length > 0);
+ assert.equal(offersConnectors(offeredTools[0]), false);
+});
+
+test("a free plan never offers them", async (t) => {
+ const { captured, offeredTools } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ subscribed: false,
+ });
+ await captured.sendToAI("Email Josh", []);
+ assert.ok(offeredTools[0].length > 0);
+ assert.equal(offersConnectors(offeredTools[0]), false);
+});
+
+test("an org that turns connectors off mid-session removes them from the next send", async (t) => {
+ const { captured, offeredTools, usePolicyStore } = await renderChatStreaming(
+ t,
+ CONNECTOR_SURFACE
+ );
+ usePolicyStore.setState({ status: "managed", appVersion: "1.10.0", policy: MANAGED_POLICY });
+ await captured.sendToAI("Email Josh", []);
+ usePolicyStore.setState({
+ policy: {
+ ...MANAGED_POLICY,
+ features: { ...MANAGED_POLICY.features, connectorsEnabled: false },
+ },
+ });
+ await captured.sendToAI("Email Josh again", []);
+
+ assert.equal(offersConnectors(offeredTools[0]), true);
+ assert.ok(offeredTools[1].length > 0);
+ assert.equal(offersConnectors(offeredTools[1]), false);
+});
+
+test("on the AI SDK path a tool step shows the tool's own text, not a bare Done", async (t) => {
+ const { captured, reasoningService, getMessages } = await renderChatStreaming(
+ t,
+ CONNECTOR_SURFACE,
+ {
+ settings: BYOK_SETTINGS,
+ electronAPI: {
+ connectorFindContacts: async () => ({
+ contacts: [
+ { name: "Gabe Torres", email: "[email protected]", lastMet: null },
+ { name: "Gabriel Stone", email: "[email protected]", lastMet: null },
+ ],
+ }),
+ },
+ }
+ );
+ reasoningService.processTextStreamingAI.mock.mockImplementation(
+ (_messages, _model, _provider, _config, tools) =>
+ (async function* () {
+ yield {
+ type: "tool_calls",
+ calls: [{ id: "call-1", name: "find_contact", arguments: "{}" }],
+ };
+ await tools.find_contact.execute({ name: "Gab" }, { toolCallId: "call-1", messages: [] });
+ // What ReasoningService yields for any object output.
+ yield {
+ type: "tool_result",
+ callId: "call-1",
+ toolName: "find_contact",
+ displayText: "Done",
+ };
+ yield { type: "done", finishReason: "stop" };
+ })()
+ );
+
+ let holds = 0;
+ await captured.sendToAI("Who is Gab?", [], { onHoldDelivery: () => (holds += 1) });
+
+ const assistant = getMessages().find((message) => message.role === "assistant");
+ assert.equal(assistant.toolCalls[0].result, "Contacts found: 2");
+ // The AI SDK tools carry the turn's scope, so a tool's hold reaches the caller.
+ assert.equal(holds, 1);
+});
+
+test("on the cloud path a tool's hold reaches the caller through the turn's scope", async (t) => {
+ const { captured, reasoningService } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ electronAPI: { connectorFindContacts: async () => ({ contacts: [] }) },
+ });
+ reasoningService.processTextStreamingCloud.mock.mockImplementation((_messages, config) =>
+ (async function* () {
+ yield {
+ type: "tool_calls",
+ calls: [{ id: "srv-1", name: "find_contact", arguments: '{"name":"Zed"}' }],
+ };
+ const result = await config.executeToolCall("find_contact", '{"name":"Zed"}', "srv-1");
+ yield {
+ type: "tool_result",
+ callId: "srv-1",
+ toolName: "find_contact",
+ displayText: result.displayText,
+ };
+ yield { type: "done", finishReason: "stop" };
+ })()
+ );
+
+ let holds = 0;
+ await captured.sendToAI("Who is Zed?", [], { onHoldDelivery: () => (holds += 1) });
+
+ assert.equal(holds, 1);
+});
+
+test("Esc settles a send whose tool never finishes, and a late result is dropped", async (t) => {
+ let finishLookup;
+ const { captured, reasoningService } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ electronAPI: {
+ connectorFindContacts: () =>
+ new Promise((resolve) => {
+ finishLookup = resolve;
+ }),
+ },
+ });
+ let toolResult;
+ reasoningService.processTextStreamingCloud.mock.mockImplementation((_messages, config) =>
+ (async function* () {
+ yield {
+ type: "tool_calls",
+ calls: [{ id: "srv-2", name: "find_contact", arguments: '{"name":"Zed"}' }],
+ };
+ toolResult = await config.executeToolCall("find_contact", '{"name":"Zed"}', "srv-2");
+ yield { type: "done", finishReason: "stop" };
+ })()
+ );
+
+ const sending = captured.sendToAI("Who is Zed?", []);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ captured.cancelStream();
+ const outcome = await Promise.race([
+ sending.then(() => "settled"),
+ new Promise((resolve) => setTimeout(() => resolve("still waiting on the tool"), 1000)),
+ ]);
+ finishLookup({ contacts: [{ name: "Zed", email: "[email protected]", lastMet: null }] });
+
+ assert.equal(outcome, "settled");
+ assert.equal(toolResult.displayText, "");
+});
+
+test("an error before the stream starts still rejects the send and adds no messages", async (t) => {
+ const { captured, getMessages } = await renderChatStreaming(
+ t,
+ {},
+ {
+ // Snippet triggers are read while the tool registry is built, before any stream.
+ settings: { snippets: null },
+ }
+ );
+ await assert.rejects(() => captured.sendToAI("hi", []), TypeError);
+ assert.equal(getMessages().length, 0);
+});
+
+// A draft still waiting on main when its turn ends is released through the
+// turn's signal (the cancel names its run), however the send ended.
+const STREAM_ENDINGS = {
+ completes: () => [{ type: "done", finishReason: "stop" }],
+ fails: () => {
+ throw new Error("stream dropped");
+ },
+};
+for (const [ending, finishStream] of Object.entries(STREAM_ENDINGS)) {
+ test(`a send that ${ending} releases a tool still running in its turn`, async (t) => {
+ const cancels = [];
+ const { captured, reasoningService } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ electronAPI: {
+ connectorRunDirect: () => new Promise(() => {}),
+ connectorCancel: async (runId, reason) => cancels.push(reason),
+ },
+ });
+ reasoningService.processTextStreamingCloud.mock.mockImplementation((_messages, config) =>
+ (async function* () {
+ void config.executeToolCall(
+ "email_draft",
+ JSON.stringify({ to: ["[email protected]"], subject: "Hi", body: "Hello" }),
+ "srv-3"
+ );
+ yield* finishStream();
+ })()
+ );
+
+ await captured.sendToAI("Email Zed", []);
+
+ assert.deepEqual(cancels, ["cancelled_by_user"]);
+ });
+}
+
+// Sends that each wait on an email draft main never finishes, so a turn only
+// ends once its tool scope is aborted. Returns the run ids main was asked to
+// open and to cancel, in order.
+async function renderDraftTurns(t, streamForSend) {
+ const opened = [];
+ const cancelled = [];
+ let notifyOpened = () => {};
+ const { captured, reasoningService } = await renderChatStreaming(t, CONNECTOR_SURFACE, {
+ electronAPI: {
+ connectorRunDirect: (_connector, _action, _draft, runId) => {
+ opened.push(runId);
+ notifyOpened();
+ return new Promise(() => {});
+ },
+ connectorCancel: async (runId) => cancelled.push(runId),
+ },
+ });
+ let sends = 0;
+ reasoningService.processTextStreamingCloud.mock.mockImplementation((_messages, config) =>
+ streamForSend(sends++, config)
+ );
+ const nextDraftOpened = () =>
+ new Promise((resolve) => {
+ notifyOpened = resolve;
+ });
+ return { captured, opened, cancelled, nextDraftOpened };
+}
+
+function awaitDraft(config, callId) {
+ return (async function* () {
+ await config.executeToolCall(
+ "email_draft",
+ JSON.stringify({ to: ["[email protected]"], subject: "Hi", body: "Hello" }),
+ callId
+ );
+ yield { type: "done", finishReason: "stop" };
+ })();
+}
+
+const settlesWithin = (promise, ms = 1000) =>
+ Promise.race([
+ promise.then(() => "settled"),
+ new Promise((resolve) => setTimeout(() => resolve("still waiting"), ms)),
+ ]);
+
+test("a newer send releases the tools of the send it replaces", async (t) => {
+ const { captured, opened, cancelled, nextDraftOpened } = await renderDraftTurns(
+ t,
+ (send, config) =>
+ send === 0
+ ? awaitDraft(config, "srv-old")
+ : (async function* () {
+ yield { type: "done", finishReason: "stop" };
+ })()
+ );
+
+ const draftOpened = nextDraftOpened();
+ const first = captured.sendToAI("Email Zed", []);
+ await draftOpened;
+ await captured.sendToAI("Never mind", []);
+
+ assert.equal(await settlesWithin(first), "settled");
+ assert.deepEqual(cancelled, opened);
+});
+
+test("a replaced send that ends leaves the newer send cancellable", async (t) => {
+ const { captured, opened, cancelled, nextDraftOpened } = await renderDraftTurns(
+ t,
+ (send, config) => awaitDraft(config, `srv-${send}`)
+ );
+
+ let draftOpened = nextDraftOpened();
+ const first = captured.sendToAI("Email Zed", []);
+ await draftOpened;
+ draftOpened = nextDraftOpened();
+ const second = captured.sendToAI("Email Zed again", []);
+ await draftOpened;
+ // The first send's cleanup runs now; it must not drop the second's scope.
+ assert.equal(await settlesWithin(first), "settled");
+ captured.cancelStream();
+
+ assert.equal(await settlesWithin(second), "settled");
+ assert.deepEqual(cancelled, opened);
+});
diff --git a/test/helpers/workspacePolicyManager.test.js b/test/helpers/workspacePolicyManager.test.js
index 6a800b247..71361a715 100644
--- a/test/helpers/workspacePolicyManager.test.js
+++ b/test/helpers/workspacePolicyManager.test.js
@@ -790,6 +790,65 @@ test("a stale-but-successful refresh still counts toward the refresh TTL", async
assert.equal(fetches, 2, "a lagging server must not defeat the refresh TTL");
});
+test("peekPolicy returns the verdict held in memory without a refresh", async (t) => {
+ let fetches = 0;
+ const context = setup(async () => {
+ fetches += 1;
+ return response(200, validPolicy());
+ });
+ t.after(context.cleanup);
+
+ assert.equal(context.manager.peekPolicy({ expectedAuthGeneration: 1 }), null);
+ await context.manager.getPolicy({ expectedAuthGeneration: 1 });
+ const held = context.manager.peekPolicy({ expectedAuthGeneration: 1 });
+
+ assert.equal(fetches, 1);
+ assert.equal(held.success, true);
+ assert.equal(held.status, "cached");
+ assert.equal(held.managed, true);
+
+ context.tokenState.generation = 2;
+ assert.equal(context.manager.peekPolicy({ expectedAuthGeneration: 1 }), null);
+});
+
+test("peekPolicy never offers one account's verdict to another", async (t) => {
+ const context = setup(async (_url, init) =>
+ init.headers.Authorization === "Bearer token-a"
+ ? response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } })
+ : response(200, validPolicy())
+ );
+ t.after(context.cleanup);
+
+ await context.manager.getPolicy({ expectedAuthGeneration: 1 });
+ assert.equal(context.manager.peekPolicy({ expectedAuthGeneration: 1 }).managed, false);
+
+ context.tokenState.token = "token-b";
+ context.tokenState.generation = 2;
+ assert.equal(context.manager.peekPolicy({ expectedAuthGeneration: 2 }), null);
+
+ await context.manager.getPolicy({ expectedAuthGeneration: 2 });
+ assert.equal(context.manager.peekPolicy({ expectedAuthGeneration: 2 }).managed, true);
+});
+
+test("peekPolicy never offers an unmanaged verdict once the org policy is unresolvable", async (t) => {
+ const responses = [
+ response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } }),
+ response(503, {
+ error: "Organization policy could not be resolved.",
+ code: "POLICY_UNRESOLVABLE",
+ }),
+ ];
+ const context = setup(async () => responses.shift());
+ t.after(context.cleanup);
+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };
+
+ await context.manager.getPolicy(request);
+ assert.equal(context.manager.peekPolicy(request)?.managed, false);
+ await context.manager.getPolicy(request);
+
+ assert.equal(context.manager.peekPolicy(request), null);
+});
+
test("a policy request without a validated auth generation fails closed", async (t) => {
const context = setup(async () => response(200, { data: validPolicy().data }));
t.after(context.cleanup);
diff --git a/test/services/connectorToolOutcome.test.js b/test/services/connectorToolOutcome.test.js
new file mode 100644
index 000000000..6bfdf986f
--- /dev/null
+++ b/test/services/connectorToolOutcome.test.js
@@ -0,0 +1,123 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const loadOutcome = () => import("../../src/services/tools/connectors/toolOutcome.ts");
+// tsx loads the ESM default export of src/i18n.ts through CommonJS interop.
+const loadI18n = async () => {
+ const mod = await import("../../src/i18n.ts");
+ return mod.default.default ?? mod.default;
+};
+const loadRun = () => import("../../src/services/tools/connectors/runApprovalAction.ts");
+const loadStore = () => import("../../src/stores/connectorApprovalStore.ts");
+
+test("every approval outcome tells the model what happened and whether to retry", async () => {
+ const { approvalOutcomeResult } = await loadOutcome();
+
+ assert.deepEqual(approvalOutcomeResult({ state: "sent", url: "u", finalText: "edited" }, "#eng").data, {
+ status: "sent",
+ url: "u",
+ destination: "#eng",
+ finalText: "edited",
+ });
+ assert.equal(approvalOutcomeResult({ state: "cancelled" }, "#eng").data.status, "cancelled_by_user");
+ assert.match(approvalOutcomeResult({ state: "cancelled" }, "#eng").data.guidance, /Do not retry/);
+ assert.deepEqual(approvalOutcomeResult({ state: "not_sent", reason: "expired" }, "#eng").data.reason, "expired");
+ assert.equal(
+ approvalOutcomeResult({ state: "failed", errorCode: "not_in_channel", message: "Not a member" }, "#eng").data.error,
+ "Not a member"
+ );
+ const unknown = approvalOutcomeResult({ state: "unknown" }, "#eng").data;
+ assert.equal(unknown.status, "unknown");
+ assert.match(unknown.guidance, /may or may not have been sent/);
+ assert.match(unknown.guidance, /#eng/);
+});
+
+test("runApprovalAction without a chat context refuses to prepare", async (t) => {
+ let prepared = 0;
+ installBrowserGlobals(t, {
+ window: { electronAPI: { connectorPrepare: async () => { prepared += 1; } } },
+ });
+ const { runApprovalAction } = await loadRun();
+ const result = await runApprovalAction(undefined, "slack", "send_message", {});
+ assert.equal(result.data.status, "unavailable");
+ assert.equal(prepared, 0);
+});
+
+test("runApprovalAction passes clarifications straight back to the model", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorPrepare: async () => ({
+ status: "needs_clarification",
+ message: "Which channel?",
+ candidates: ["#eng-web", "#eng-ios"],
+ }),
+ },
+ },
+ });
+ const { runApprovalAction } = await loadRun();
+ const controller = new AbortController();
+ const result = await runApprovalAction(
+ { toolCallId: "call-1", signal: controller.signal, onApprovalRequested() {} },
+ "slack",
+ "send_message",
+ { destination: "#eng" }
+ );
+ assert.deepEqual(result.data, {
+ status: "needs_clarification",
+ message: "Which channel?",
+ candidates: ["#eng-web", "#eng-ios"],
+ });
+});
+
+test("runApprovalAction waits for the card and returns the send", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorPrepare: async () => ({
+ status: "ready",
+ actionId: "a1",
+ preview: { verbKey: "default", destinationLabel: "#eng", accountLabel: "chad", body: "hi" },
+ }),
+ connectorCommit: async () => ({ state: "sent", url: "https://slack.test/p/9" }),
+ connectorCancel: async () => ({ cancelled: true }),
+ },
+ },
+ });
+ const { runApprovalAction } = await loadRun();
+ const { approveAction, useConnectorApprovalStore } = await loadStore();
+ useConnectorApprovalStore.setState({ entries: {} });
+ const controller = new AbortController();
+
+ const pending = runApprovalAction(
+ { toolCallId: "call-2", signal: controller.signal, onApprovalRequested() {} },
+ "slack",
+ "send_message",
+ { destination: "#eng", text: "hi" }
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+ await approveAction("call-2");
+
+ const result = await pending;
+ assert.equal(result.data.status, "sent");
+ assert.equal(result.data.url, "https://slack.test/p/9");
+});
+
+test("tool steps show the user plain, localized outcomes instead of codes", async () => {
+ const { unavailableResult, failedResult, needsClarificationResult, notSentResult, approvalOutcomeResult } =
+ await loadOutcome();
+ // The UI language otherwise follows the machine's locale.
+ await (await loadI18n()).changeLanguage("en");
+
+ assert.equal(unavailableResult("policy_blocked").displayText, "Connectors are turned off by your organization.");
+ assert.equal(unavailableResult("policy_unavailable").displayText, "Connectors aren't available right now.");
+ assert.equal(failedResult("open_failed", "Couldn't open your email app.").displayText, "Couldn't open your email app.");
+ assert.equal(failedResult("not_in_channel", "raw provider text").displayText, "That didn't work.");
+ assert.equal(needsClarificationResult("Call find_contact first.").displayText, "Needs more details.");
+ assert.equal(notSentResult("cancelled").displayText, "Not sent.");
+ assert.equal(approvalOutcomeResult({ state: "sent", url: "u" }, "#eng").displayText, "Sent to #eng.");
+ // The model still gets the precise codes and guidance.
+ assert.equal(unavailableResult("policy_blocked").data.reason, "policy_blocked");
+ assert.equal(needsClarificationResult("Call find_contact first.").data.message, "Call find_contact first.");
+});
diff --git a/test/services/connectorTools.test.js b/test/services/connectorTools.test.js
new file mode 100644
index 000000000..523784cc4
--- /dev/null
+++ b/test/services/connectorTools.test.js
@@ -0,0 +1,686 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals, createRendererServer } = require("../lib/rendererTestHarness");
+
+const loadEmail = () => import("../../src/services/tools/connectors/emailDraftTool.ts");
+const loadContact = () => import("../../src/services/tools/connectors/findContactTool.ts");
+const loadEligibility = () => import("../../src/utils/connectorEligibility.ts");
+const loadRegistry = () => import("../../src/services/tools/index.ts");
+// Tool-step text is localized; the UI language otherwise follows the machine's locale.
+// (tsx loads its ESM default export through CommonJS interop.)
+const useEnglish = async () => {
+ const mod = await import("../../src/i18n.ts");
+ await (mod.default.default ?? mod.default).changeLanguage("en");
+};
+
+test("email_draft opens a draft through the main process", async (t) => {
+ const calls = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (...args) => {
+ calls.push(args);
+ return { state: "sent", destinationLabel: "[email protected]", bodyCopied: false };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const result = await createEmailDraftTool("gmail").execute({
+ subject: "Lunch",
+ body: "Tomorrow at 1?",
+ });
+
+ assert.equal(calls.length, 1);
+ assert.deepEqual(calls[0].slice(0, 3), [
+ "email",
+ "draft",
+ {
+ target: "gmail",
+ cc: [],
+ subject: "Lunch",
+ body: "Tomorrow at 1?",
+ clipboardReserved: false,
+ },
+ ]);
+ assert.equal(typeof calls[0][3], "string");
+ assert.equal(result.data.status, "draft_opened");
+ assert.equal(result.data.bodyCopied, false);
+});
+
+test("email_draft cancels its run in main when the turn is cancelled mid-call", async (t) => {
+ const cancels = [];
+ let finishRun;
+ let runId;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: (_connector, _action, _args, id) => {
+ runId = id;
+ return new Promise((resolve) => {
+ finishRun = resolve;
+ });
+ },
+ connectorCancel: async (...args) => {
+ cancels.push(args);
+ return { cancelled: true };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const controller = new AbortController();
+
+ const pending = createEmailDraftTool("gmail").execute(
+ { to: ["[email protected]"], subject: "s", body: "b" },
+ countingContext(controller.signal)
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+ controller.abort();
+ finishRun({ state: "not_sent", reason: "cancelled" });
+ const result = await pending;
+
+ assert.deepEqual(cancels, [[runId, "cancelled_by_user"]]);
+ assert.equal(result.data.status, "not_sent");
+});
+
+test("email_draft asks for addresses instead of guessing", async (t) => {
+ let ran = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => {
+ ran += 1;
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+
+ const result = await createEmailDraftTool("gmail").execute({
+ to: ["Gabe"],
+ subject: "x",
+ body: "y",
+ });
+
+ assert.equal(result.data.status, "needs_clarification");
+ // No one to choose between: the model fixes the call itself.
+ assert.deepEqual(result.data.candidates, []);
+ assert.match(result.data.message, /"Gabe"/);
+ assert.match(result.data.message, /find_contact/);
+ assert.equal(ran, 0);
+});
+
+test("email_draft keeps only the address from a display-name recipient", async (t) => {
+ const calls = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (_connector, _action, args) => {
+ calls.push(args);
+ return { state: "sent", destinationLabel: args.to.join(", ") };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+
+ const result = await createEmailDraftTool("gmail").execute({
+ to: ["Gabe Torres <[email protected]>"],
+ cc: [" Dana <[email protected]> "],
+ subject: "x",
+ body: "y",
+ });
+
+ assert.equal(result.data.status, "draft_opened");
+ assert.deepEqual(calls[0].to, ["[email protected]"]);
+ assert.deepEqual(calls[0].cc, ["[email protected]"]);
+});
+
+function countingContext(signal = new AbortController().signal) {
+ const context = {
+ holds: 0,
+ preservesClipboard: false,
+ toolCallId: "call-1",
+ signal,
+ onApprovalRequested() {},
+ onHoldDelivery(options) {
+ context.holds += 1;
+ if (options?.preserveClipboard) context.preservesClipboard = true;
+ },
+ claimTurnSlot: () => true,
+ releaseTurnSlot() {},
+ };
+ return context;
+}
+
+const loadScope = () => import("../../src/components/chat/toolExecutionScope.ts");
+
+test("email_draft opens at most three drafts per turn", async (t) => {
+ let opened = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => {
+ opened += 1;
+ return { state: "sent", destinationLabel: "[email protected]", bodyCopied: false };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const tool = createEmailDraftTool("gmail");
+ const draft = (id) =>
+ tool.execute({ to: ["[email protected]"], subject: "s", body: "b" }, scope.createContext(id));
+
+ // The AI SDK runs a step's tool calls in parallel.
+ const results = await Promise.all(["1", "2", "3", "4"].map(draft));
+
+ assert.equal(opened, 3);
+ assert.deepEqual(
+ results.map((result) => result.data.status),
+ ["draft_opened", "draft_opened", "draft_opened", "not_sent"]
+ );
+ assert.equal(results[3].data.reason, "draft_limit");
+ // A new turn starts over.
+ const next = createToolExecutionScope().createContext("5");
+ assert.equal(
+ (await tool.execute({ to: ["[email protected]"], subject: "s", body: "b" }, next)).data.status,
+ "draft_opened"
+ );
+});
+
+test("only one draft per turn may put its text on the clipboard", async (t) => {
+ const opened = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (_connector, _action, args) => {
+ opened.push(args.to[0]);
+ return {
+ state: "sent",
+ destinationLabel: args.to[0],
+ bodyCopied: args.body.length > 1000,
+ };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ // mailto keeps a 2,000-character link on every platform.
+ const tool = createEmailDraftTool("mailto");
+ const longBody = "word ".repeat(600);
+
+ const [first, second] = await Promise.all([
+ tool.execute(
+ { to: ["[email protected]"], subject: "Recap", body: longBody },
+ scope.createContext("1")
+ ),
+ tool.execute(
+ { to: ["[email protected]"], subject: "Recap", body: longBody },
+ scope.createContext("2")
+ ),
+ ]);
+ const short = (id, address) =>
+ tool.execute({ to: [address], subject: "Hi", body: "Short one." }, scope.createContext(id));
+ const third = await short("3", "[email protected]");
+ // The refused draft gave its draft slot back, so this is the third to open.
+ const fourth = await short("4", "[email protected]");
+
+ assert.equal(first.data.status, "draft_opened");
+ assert.equal(second.data.status, "not_sent");
+ assert.equal(second.data.reason, "clipboard_in_use");
+ assert.match(second.data.guidance, /paste/);
+ // A draft that fits its link needs no clipboard, so it still opens.
+ assert.equal(third.data.status, "draft_opened");
+ assert.equal(fourth.data.status, "draft_opened");
+ assert.deepEqual(opened, ["[email protected]", "[email protected]", "[email protected]"]);
+});
+
+test("a draft that didn't open gives back its draft and clipboard slots", async (t) => {
+ const outcomes = [
+ { state: "failed", errorCode: "open_failed", message: "Couldn't open your email app." },
+ { state: "not_sent", reason: "cancelled" },
+ { state: "unavailable", reason: "policy_blocked" },
+ { state: "sent", destinationLabel: "[email protected]", bodyCopied: true },
+ ];
+ const reserved = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (_connector, _action, args) => {
+ reserved.push(args.clipboardReserved);
+ return outcomes.shift();
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const draft = { to: ["[email protected]"], subject: "Recap", body: "word ".repeat(600) };
+
+ const statuses = [];
+ for (const id of ["1", "2", "3", "4"]) {
+ statuses.push(
+ (await createEmailDraftTool("mailto").execute(draft, scope.createContext(id))).data.status
+ );
+ }
+
+ // Three draft slots would be gone, and the clipboard slot after the first.
+ assert.deepEqual(statuses, ["failed", "not_sent", "unavailable", "draft_opened"]);
+ assert.deepEqual(reserved, [true, true, true, true]);
+});
+
+test("a draft whose outcome is unknown says so, and keeps the clipboard claimed", async (t) => {
+ let runs = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => {
+ runs += 1;
+ return {
+ state: "unknown",
+ errorCode: "direct_failed",
+ message: "That action didn't complete.",
+ };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const tool = createEmailDraftTool("mailto");
+ const draft = { to: ["[email protected]"], subject: "Recap", body: "word ".repeat(600) };
+
+ const first = await tool.execute(draft, scope.createContext("1"));
+ const second = await tool.execute(draft, scope.createContext("2"));
+
+ assert.equal(first.data.status, "unknown");
+ assert.match(first.data.guidance, /The draft to josh@example\.com may or may not have opened/);
+ assert.match(first.data.guidance, /Do not retry/);
+ // It may have put its text on the clipboard; another draft must not replace it.
+ assert.equal(second.data.reason, "clipboard_in_use");
+ assert.equal(runs, 1);
+});
+
+test("email_draft tells the model when content went to the clipboard", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => ({
+ state: "sent",
+ destinationLabel: "[email protected]",
+ bodyCopied: true,
+ subjectCopied: true,
+ }),
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ await useEnglish();
+
+ const result = await createEmailDraftTool("mailto").execute(
+ { to: ["[email protected]"], subject: "s", body: "b" },
+ countingContext()
+ );
+
+ assert.equal(result.data.bodyCopied, true);
+ assert.equal(result.data.subjectCopied, true);
+ assert.match(result.data.guidance, /clipboard/);
+ assert.match(result.data.guidance, /subject/i);
+ // The tool step tells the user too, in case the model doesn't.
+ assert.equal(
+ result.displayText,
+ "Opened a draft to [email protected]. The subject and body are on your clipboard."
+ );
+});
+
+test("email_draft guidance names exactly what went to the clipboard", async (t) => {
+ const results = [{ subjectCopied: true, bodyCopied: false }, { copyFailed: true }];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => ({
+ state: "sent",
+ destinationLabel: "[email protected]",
+ ...results.shift(),
+ }),
+ },
+ },
+ });
+ const tool = (await loadEmail()).createEmailDraftTool("mailto");
+
+ const subjectOnly = await tool.execute(
+ { to: ["[email protected]"], subject: "s", body: "b" },
+ countingContext()
+ );
+ assert.match(subjectOnly.data.guidance, /subject was too long/);
+ assert.doesNotMatch(subjectOnly.data.guidance, /body/);
+
+ // Only the body overflowed, so only the body is missing from the draft.
+ const copyFailed = await tool.execute(
+ { to: ["[email protected]"], subject: "Recap", body: "word ".repeat(600) },
+ countingContext()
+ );
+ assert.match(copyFailed.data.guidance, /its body didn't fit/);
+ assert.match(copyFailed.data.guidance, /Put the body in your reply/);
+ assert.doesNotMatch(copyFailed.data.guidance, /subject/);
+});
+
+test("a draft whose text couldn't be copied gives the clipboard back to the turn", async (t) => {
+ const results = [{ copyFailed: true }, { bodyCopied: true }];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => ({
+ state: "sent",
+ destinationLabel: "[email protected]",
+ ...results.shift(),
+ }),
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const tool = createEmailDraftTool("mailto");
+ const draft = { to: ["[email protected]"], subject: "Recap", body: "word ".repeat(600) };
+
+ await tool.execute(draft, scope.createContext("1"));
+ const second = await tool.execute(draft, scope.createContext("2"));
+
+ // Nothing of the first draft reached the clipboard, so the second may use it.
+ assert.equal(second.data.status, "draft_opened");
+ assert.equal(second.data.bodyCopied, true);
+});
+
+test("malformed text or a failed call never leaks the turn's slots", async (t) => {
+ const sent = [];
+ let reject = true;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (_connector, _action, args) => {
+ if (reject) {
+ reject = false;
+ throw new Error("No handler registered for 'connector-run-direct'");
+ }
+ sent.push(args);
+ return { state: "sent", destinationLabel: "[email protected]", bodyCopied: true };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const tool = createEmailDraftTool("mailto");
+ // Half an emoji, as a model sometimes emits it, in a body too long for a link.
+ const draft = { to: ["[email protected]"], subject: "\uD83D", body: `${"word ".repeat(600)}\uDC00` };
+
+ const failedCall = await tool.execute(draft, scope.createContext("1"));
+ assert.equal(failedCall.data.status, "unavailable");
+ const results = [];
+ for (const id of ["2", "3", "4"])
+ results.push(await tool.execute(draft, scope.createContext(id)));
+
+ // The rejected call gave back its draft and clipboard slots.
+ assert.equal(results[0].data.status, "draft_opened");
+ assert.equal(sent.length, 1);
+ assert.equal(results[1].data.reason, "clipboard_in_use");
+});
+
+test("a recipient with a non-ASCII domain is shown with its punycode form", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => ({ state: "sent", destinationLabel: "ignored" }),
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ await useEnglish();
+
+ // All-Cyrillic "apple": one script, so allowed, but its punycode gives it away.
+ const result = await createEmailDraftTool("gmail").execute(
+ { to: ["a@аррӏе.com", "[email protected]"], subject: "s", body: "b" },
+ countingContext()
+ );
+
+ // The data keeps bare addresses, so the model can reuse them in a retry.
+ assert.deepEqual(result.data.recipients, ["a@аррӏе.com", "[email protected]"]);
+ assert.equal(
+ result.displayText,
+ "Opened a draft to a@аррӏе.com (xn--80ak6aa92e.com), [email protected]."
+ );
+});
+
+test("email_draft keeps its turn out of the user's document, whatever the outcome", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async (_connector, _action, args) => ({
+ state: "sent",
+ destinationLabel: "[email protected]",
+ bodyCopied: args.clipboardReserved === true && !args.body.startsWith("unwritable"),
+ copyFailed: args.body.startsWith("unwritable"),
+ }),
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const tool = createEmailDraftTool("gmail");
+
+ // The compose window takes focus, so pasting the confirmation at the caret
+ // would land in the draft or overwrite the clipboard.
+ const opened = countingContext();
+ await tool.execute({ to: ["[email protected]"], subject: "s", body: "b" }, opened);
+ // A question back to the user must not be pasted into their document.
+ const clarifying = countingContext();
+ await tool.execute({ to: ["Gabe"], subject: "s", body: "b" }, clarifying);
+ const overflowing = countingContext();
+ await tool.execute(
+ { to: ["[email protected]"], subject: "s", body: "word ".repeat(2000) },
+ overflowing
+ );
+ const uncopied = countingContext();
+ await tool.execute(
+ { to: ["[email protected]"], subject: "s", body: `unwritable ${"word ".repeat(2000)}` },
+ uncopied
+ );
+
+ assert.equal(opened.holds, 1);
+ assert.equal(clarifying.holds, 1);
+ // A draft that fits its link leaves the clipboard alone, so the held answer
+ // can still be copied.
+ assert.equal(opened.preservesClipboard, false);
+ assert.equal(clarifying.preservesClipboard, false);
+ // An overflowing body goes to the clipboard; the answer must not replace it.
+ assert.equal(overflowing.preservesClipboard, true);
+ // Nothing reached the clipboard, so the answer (which carries the text) is copied.
+ assert.equal(uncopied.preservesClipboard, false);
+});
+
+test("email_draft opens nothing once its turn is cancelled", async (t) => {
+ let ran = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => {
+ ran += 1;
+ return { state: "sent", destinationLabel: "[email protected]" };
+ },
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const controller = new AbortController();
+ controller.abort();
+
+ const result = await createEmailDraftTool("gmail").execute(
+ { to: ["[email protected]"], subject: "s", body: "b" },
+ countingContext(controller.signal)
+ );
+
+ assert.equal(ran, 0);
+ assert.equal(result.data.status, "not_sent");
+});
+
+test("email_draft reports a blocked policy without retrying", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorRunDirect: async () => ({ state: "unavailable", reason: "policy_blocked" }),
+ },
+ },
+ });
+ const { createEmailDraftTool } = await loadEmail();
+ const result = await createEmailDraftTool("gmail").execute({
+ subject: "s",
+ body: "b",
+ });
+ assert.equal(result.data.status, "unavailable");
+ assert.equal(result.data.reason, "policy_blocked");
+});
+
+test("find_contact returns matches and guidance for zero or several", async (t) => {
+ const responses = [
+ { contacts: [] },
+ {
+ contacts: [
+ { name: "Gabe Torres", email: "[email protected]", lastMet: null },
+ { name: "Gabriel Stone", email: "[email protected]", lastMet: null },
+ ],
+ },
+ ];
+ installBrowserGlobals(t, {
+ window: { electronAPI: { connectorFindContacts: async () => responses.shift() } },
+ });
+ const { findContactTool } = await loadContact();
+ await useEnglish();
+
+ const none = await findContactTool.execute({ name: "Zed" });
+ const several = await findContactTool.execute({ name: "Gab" });
+
+ assert.match(none.data.guidance, /ask the user/i);
+ assert.equal(several.data.contacts.length, 2);
+ assert.match(several.data.guidance, /which one/i);
+ assert.equal(several.displayText, "Contacts found: 2");
+});
+
+test("find_contact asks for a last name when more people match than it lists", async (t) => {
+ const contacts = Array.from({ length: 5 }, (_, i) => ({
+ name: `Josh ${i}`,
+ email: `josh${i}@example.com`,
+ lastMet: null,
+ }));
+ installBrowserGlobals(t, {
+ window: { electronAPI: { connectorFindContacts: async () => ({ contacts, hasMore: true }) } },
+ });
+ const { findContactTool } = await loadContact();
+ const result = await findContactTool.execute({ name: "Josh" });
+ assert.equal(result.data.contacts.length, 5);
+ assert.match(result.data.guidance, /last name/);
+});
+
+test("find_contact reports an org policy refusal instead of an empty result", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ connectorFindContacts: async () => ({ contacts: [], unavailableReason: "policy_blocked" }),
+ },
+ },
+ });
+ const { findContactTool } = await loadContact();
+ const result = await findContactTool.execute({ name: "Gabe" });
+ assert.equal(result.data.status, "unavailable");
+ assert.equal(result.data.reason, "policy_blocked");
+});
+
+test("find_contact keeps its turn out of the user's document, whatever it finds", async (t) => {
+ const one = [{ name: "Gabe Torres", email: "[email protected]", lastMet: null }];
+ const two = [...one, { name: "Gabriel Stone", email: "[email protected]", lastMet: null }];
+ const responses = [{ contacts: [] }, { contacts: two }, { contacts: one }];
+ installBrowserGlobals(t, {
+ window: { electronAPI: { connectorFindContacts: async () => responses.shift() } },
+ });
+ const { findContactTool } = await loadContact();
+
+ const holdsFor = async (name) => {
+ const context = countingContext();
+ await findContactTool.execute({ name }, context);
+ // A lookup writes nothing to the clipboard, so its answer is still copied.
+ assert.equal(context.preservesClipboard, false);
+ return context.holds;
+ };
+
+ assert.equal(await holdsFor("Zed"), 1);
+ assert.equal(await holdsFor("Gab"), 1);
+ // One match is usually followed by a question ("What should it say?"),
+ // which must not be pasted at the caret either.
+ assert.equal(await holdsFor("Gabe Torres"), 1);
+});
+
+test("connector plan eligibility uses usage data, then the persisted isSubscribed flag", async () => {
+ const { hasConnectorPlan } = await loadEligibility();
+ const success = (isSubscribed, isTrial) => ({
+ status: "success",
+ accountId: "acct",
+ data: { isSubscribed, isTrial },
+ isRefreshing: false,
+ });
+ assert.equal(hasConnectorPlan(success(false, true), false), true);
+ assert.equal(hasConnectorPlan(success(false, false), true), false);
+ // A fresh voice-window session never loads usage, so the isSubscribed flag
+ // the control panel persisted (the API sets it for trials too) decides.
+ assert.equal(hasConnectorPlan({ status: "idle", accountId: null }, true), true);
+ assert.equal(hasConnectorPlan({ status: "idle", accountId: null }, false), false);
+ assert.equal(hasConnectorPlan({ status: "loading", accountId: "acct" }, false), false);
+});
+
+test("connector tools register only when connectors are available", async () => {
+ const { createToolRegistry } = await loadRegistry();
+ const base = {
+ isSignedIn: true,
+ calendarConnected: false,
+ cloudBackupEnabled: false,
+ webSearchEnabled: false,
+ };
+
+ const without = createToolRegistry(base)
+ .getAll()
+ .map((tool) => tool.name);
+ const withConnectors = createToolRegistry({ ...base, connectors: { emailDraftTarget: "gmail" } })
+ .getAll()
+ .map((tool) => tool.name);
+
+ assert.equal(without.includes("email_draft"), false);
+ assert.ok(withConnectors.includes("email_draft"));
+ assert.ok(withConnectors.includes("find_contact"));
+});
+
+test("the system prompt adds connector rules only when a connector tool is present", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-connector-prompts-test-" });
+ const { getAgentSystemPrompt } = await vite.ssrLoadModule("/config/prompts.ts");
+
+ const withEmail = getAgentSystemPrompt(["find_contact", "email_draft"]);
+ const withoutEmail = getAgentSystemPrompt(["search_notes"]);
+
+ assert.match(withEmail, /Use find_contact/);
+ assert.match(withEmail, /Use email_draft/);
+ assert.match(withEmail, /needs_clarification result that lists candidates/);
+ assert.match(withEmail, /guidance and message in each connector result/);
+ // A corrected retry or a find_contact follow-up needs no question first.
+ assert.doesNotMatch(withEmail, /ask the user before calling it again/);
+ assert.doesNotMatch(withoutEmail, /needs_clarification/);
+});
diff --git a/test/services/emailDraftTarget.test.js b/test/services/emailDraftTarget.test.js
new file mode 100644
index 000000000..edf459895
--- /dev/null
+++ b/test/services/emailDraftTarget.test.js
@@ -0,0 +1,76 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/utils/emailDraftTarget.ts");
+
+const PERSONAL_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad";
+const WORK_TENANT = "72f988bf-86f1-41af-91ab-2d7cd011db47";
+
+const resolve = async (emailDraftTarget, gcalConnected, mcalAccounts) => {
+ const { resolveEmailDraftTarget } = await load();
+ return resolveEmailDraftTarget({ emailDraftTarget, gcalConnected, mcalAccounts });
+};
+
+test("an explicit choice always wins", async () => {
+ assert.equal(await resolve("outlookWork", true, []), "outlookWork");
+});
+
+test("automatic follows the connected calendar", async () => {
+ assert.equal(await resolve("auto", true, [{ email: "[email protected]" }]), "gmail");
+ assert.equal(await resolve("auto", false, [{ email: "[email protected]" }]), "outlookWork");
+ assert.equal(await resolve("auto", false, [{ email: "[email protected]" }]), "outlookPersonal");
+ assert.equal(await resolve("auto", false, []), "mailto");
+});
+
+test("an unknown stored value behaves like automatic", async () => {
+ assert.equal(await resolve("yahoo", false, []), "mailto");
+ const { normalizeEmailDraftTarget } = await load();
+ assert.equal(normalizeEmailDraftTarget("yahoo"), "auto");
+ assert.equal(normalizeEmailDraftTarget("gmail"), "gmail");
+});
+
+test("any work account picks outlook work, regardless of order", async () => {
+ assert.equal(
+ await resolve("auto", false, [{ email: "[email protected]" }, { email: "[email protected]" }]),
+ "outlookWork"
+ );
+ assert.equal(
+ await resolve("auto", false, [{ email: "[email protected]" }, { email: "[email protected]" }]),
+ "outlookPersonal"
+ );
+});
+
+test("the tenant decides personal or work, whatever the address", async () => {
+ // A personal account on a custom domain, and a work tenant on a consumer-looking domain.
+ assert.equal(
+ await resolve("auto", false, [{ email: "[email protected]", tenantId: PERSONAL_TENANT }]),
+ "outlookPersonal"
+ );
+ assert.equal(
+ await resolve("auto", false, [{ email: "[email protected]", tenantId: WORK_TENANT }]),
+ "outlookWork"
+ );
+ // An account connected before the tenant was stored falls back to the domain.
+ assert.equal(
+ await resolve("auto", false, [{ email: "[email protected]", tenantId: null }]),
+ "outlookWork"
+ );
+});
+
+test("personal Microsoft domains are recognised in every country", async () => {
+ for (const email of [
+ ]) {
+ assert.equal(await resolve("auto", false, [{ email }]), "outlookPersonal", email);
+ }
+ // A company domain that merely starts with one of those words is still work.
+ for (const email of ["[email protected]", "[email protected]", "[email protected]"]) {
+ assert.equal(await resolve("auto", false, [{ email }]), "outlookWork", email);
+ }
+});
diff --git a/test/services/toolExecutionContext.test.js b/test/services/toolExecutionContext.test.js
new file mode 100644
index 000000000..526850b31
--- /dev/null
+++ b/test/services/toolExecutionContext.test.js
@@ -0,0 +1,284 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const loadRegistry = () => import("../../src/services/tools/ToolRegistry.ts");
+const loadScope = () => import("../../src/components/chat/toolExecutionScope.ts");
+
+function recordingTool(seen) {
+ return {
+ name: "record_context",
+ description: "Records the context it was called with",
+ parameters: { type: "object", properties: {}, additionalProperties: false },
+ readOnly: true,
+ async execute(args, context) {
+ seen.push({ args, context });
+ return { success: true, data: { ok: true }, displayText: "ok" };
+ },
+ };
+}
+
+test("toAISDKFormat gives each call its own tool-call id and the shared scope", async () => {
+ const { ToolRegistry } = await loadRegistry();
+ const seen = [];
+ const registry = new ToolRegistry();
+ registry.register(recordingTool(seen));
+ const controller = new AbortController();
+ const onApprovalRequested = () => {};
+ const tools = registry.toAISDKFormat((toolCallId) => ({
+ toolCallId,
+ signal: controller.signal,
+ onApprovalRequested,
+ onHoldDelivery() {},
+ }));
+
+ await tools.record_context.execute({ a: 1 }, { toolCallId: "call-1", messages: [] });
+ await tools.record_context.execute({ a: 2 }, { toolCallId: "call-2", messages: [] });
+
+ assert.deepEqual(
+ seen.map((entry) => entry.context.toolCallId),
+ ["call-1", "call-2"]
+ );
+ assert.equal(seen[0].context.signal, controller.signal);
+ assert.equal(seen[1].context.onApprovalRequested, onApprovalRequested);
+});
+
+test("toAISDKFormat reports each call's display text next to the model's output", async () => {
+ const { ToolRegistry } = await loadRegistry();
+ const registry = new ToolRegistry();
+ registry.register(recordingTool([]));
+ const shown = [];
+ const tools = registry.toAISDKFormat(undefined, (toolCallId, displayText) =>
+ shown.push({ toolCallId, displayText })
+ );
+
+ const output = await tools.record_context.execute({}, { toolCallId: "call-7", messages: [] });
+
+ assert.deepEqual(output, { ok: true });
+ assert.deepEqual(shown, [{ toolCallId: "call-7", displayText: "ok" }]);
+});
+
+test("toAISDKFormat without a context factory passes no context", async () => {
+ const { ToolRegistry } = await loadRegistry();
+ const seen = [];
+ const registry = new ToolRegistry();
+ registry.register(recordingTool(seen));
+
+ await registry.toAISDKFormat().record_context.execute({}, { toolCallId: "call-3", messages: [] });
+
+ assert.equal(seen[0].context, undefined);
+});
+
+test("a tool execution scope shares one signal and aborts it once", async () => {
+ const { createToolExecutionScope } = await loadScope();
+ let approvals = 0;
+ const holds = [];
+ const scope = createToolExecutionScope({
+ onApprovalRequested: () => {
+ approvals += 1;
+ },
+ onHoldDelivery: (options) => {
+ holds.push(options);
+ },
+ });
+ const first = scope.createContext("call-a");
+ const second = scope.createContext("call-b");
+
+ assert.equal(first.toolCallId, "call-a");
+ assert.equal(first.signal, second.signal);
+ assert.equal(first.signal.aborted, false);
+ first.onApprovalRequested();
+ second.onHoldDelivery({ preserveClipboard: true });
+ assert.equal(approvals, 1);
+ assert.deepEqual(holds, [{ preserveClipboard: true }]);
+
+ scope.abort();
+ scope.abort();
+ assert.equal(second.signal.aborted, true);
+});
+
+test("a scope's notices do nothing once its turn has ended", async () => {
+ const { createToolExecutionScope } = await loadScope();
+ let notices = 0;
+ const scope = createToolExecutionScope({
+ onApprovalRequested: () => {
+ notices += 1;
+ },
+ onHoldDelivery: () => {
+ notices += 1;
+ },
+ });
+ const context = scope.createContext("call-d");
+
+ // A slow tool result arriving after Esc must not reopen a dismissed panel.
+ scope.abort();
+ context.onApprovalRequested();
+ context.onHoldDelivery();
+
+ assert.equal(notices, 0);
+});
+
+test("turn slots are shared by a scope's calls and start over with each turn", async () => {
+ const { createToolExecutionScope } = await loadScope();
+ const scope = createToolExecutionScope();
+ const first = scope.createContext("call-e");
+ const second = scope.createContext("call-f");
+
+ assert.equal(first.claimTurnSlot("draft", 2), true);
+ assert.equal(second.claimTurnSlot("draft", 2), true);
+ assert.equal(first.claimTurnSlot("draft", 2), false);
+ // Keys count separately.
+ assert.equal(second.claimTurnSlot("clipboard", 1), true);
+ assert.equal(createToolExecutionScope().createContext("call-g").claimTurnSlot("draft", 2), true);
+});
+
+test("executeTool settles an aborted call at once and never runs one after the abort", async () => {
+ const { executeTool } = await loadRegistry();
+ const { createToolExecutionScope } = await loadScope();
+ let runs = 0;
+ const hanging = {
+ ...recordingTool([]),
+ execute: () => {
+ runs += 1;
+ // Ignores the signal, like a fetch with no timeout; rejects much later.
+ return new Promise((_resolve, reject) => setTimeout(() => reject(new Error("late")), 50));
+ },
+ };
+ const scope = createToolExecutionScope();
+
+ const pending = executeTool(hanging, {}, scope.createContext("call-h"));
+ scope.abort();
+ assert.deepEqual(await pending, { success: false, data: null, displayText: "" });
+ assert.deepEqual(await executeTool(hanging, {}, scope.createContext("call-i")), {
+ success: false,
+ data: null,
+ displayText: "",
+ });
+ assert.equal(runs, 1);
+ // The late rejection is swallowed rather than surfacing as unhandled.
+ await new Promise((resolve) => setTimeout(resolve, 80));
+});
+
+test("executeTool passes results and errors through while the turn is live", async () => {
+ const { executeTool } = await loadRegistry();
+ const { createToolExecutionScope } = await loadScope();
+ const context = createToolExecutionScope().createContext("call-j");
+ assert.deepEqual(await executeTool(recordingTool([]), { a: 1 }, context), {
+ success: true,
+ data: { ok: true },
+ displayText: "ok",
+ });
+ const failing = { ...recordingTool([]), execute: async () => Promise.reject(new Error("boom")) };
+ await assert.rejects(executeTool(failing, {}, context), /boom/);
+ assert.deepEqual(await executeTool(recordingTool([]), {}), {
+ success: true,
+ data: { ok: true },
+ displayText: "ok",
+ });
+});
+
+test("an aborted AI SDK turn ends even when a tool never settles", async () => {
+ const { streamText, stepCountIs } = require("ai");
+ const { MockLanguageModelV3, simulateReadableStream } = require("ai/test");
+ const { ToolRegistry } = await loadRegistry();
+ const { createToolExecutionScope } = await loadScope();
+ const registry = new ToolRegistry();
+ let started;
+ const toolStarted = new Promise((resolve) => {
+ started = resolve;
+ });
+ registry.register({
+ ...recordingTool([]),
+ name: "slow",
+ execute: () => {
+ started();
+ return new Promise(() => {});
+ },
+ });
+ const model = new MockLanguageModelV3({
+ doStream: async () => ({
+ stream: simulateReadableStream({
+ chunks: [
+ { type: "stream-start", warnings: [] },
+ { type: "tool-call", toolCallId: "call-1", toolName: "slow", input: "{}" },
+ {
+ type: "finish",
+ finishReason: { unified: "tool-calls", raw: "tool_calls" },
+ usage: { inputTokens: { total: 1 }, outputTokens: { total: 1 } },
+ },
+ ],
+ }),
+ }),
+ });
+ const scope = createToolExecutionScope();
+ const streamAbort = new AbortController();
+ const result = streamText({
+ model,
+ messages: [{ role: "user", content: "hi" }],
+ tools: registry.toAISDKFormat(scope.createContext),
+ stopWhen: stepCountIs(5),
+ abortSignal: streamAbort.signal,
+ });
+ const drained = (async () => {
+ for await (const _chunk of result.fullStream);
+ })();
+
+ await toolStarted;
+ // Let the SDK settle into waiting on the tool, as it has by the time a user
+ // presses Esc; an abort in the same tick still ends the stream on its own.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ // What cancelStream does: abort the tool scope and the stream.
+ scope.abort();
+ streamAbort.abort();
+ const outcome = await Promise.race([
+ drained.then(() => "ended"),
+ new Promise((resolve) => setTimeout(() => resolve("still pending"), 2000)),
+ ]);
+ assert.equal(outcome, "ended");
+});
+
+test("a scope without handlers ignores approval and delivery notices", async () => {
+ const { createToolExecutionScope } = await loadScope();
+ const context = createToolExecutionScope().createContext("call-c");
+ assert.doesNotThrow(() => context.onApprovalRequested());
+ assert.doesNotThrow(() => context.onHoldDelivery());
+});
+
+test("the cloud tool loop passes each call's id to executeToolCall", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-tool-context-cloud-test-",
+ });
+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
+ t.after(() => reasoningService.destroy());
+
+ let step = 0;
+ t.mock.method(reasoningService, "streamFromIPC", () => {
+ step += 1;
+ const events =
+ step === 1
+ ? [{ type: "tool_call", id: "call-9", name: "record_context", arguments: "{}" }]
+ : [{ type: "content", text: "done" }];
+ return {
+ stream: (async function* () {
+ for (const event of events) yield event;
+ })(),
+ wasCancelled: () => false,
+ };
+ });
+
+ const received = [];
+ const stream = reasoningService.processTextStreamingCloud([{ role: "user", content: "hi" }], {
+ systemPrompt: "s",
+ tools: [{ name: "record_context", description: "d", parameters: {} }],
+ executeToolCall: async (name, _args, toolCallId) => {
+ received.push({ name, toolCallId });
+ return { data: "ok", displayText: "ok" };
+ },
+ });
+ for await (const _chunk of stream) {
+ // drain
+ }
+
+ assert.deepEqual(received, [{ name: "record_context", toolCallId: "call-9" }]);
+});
diff --git a/test/stores/connectorApprovalStore.test.js b/test/stores/connectorApprovalStore.test.js
new file mode 100644
index 000000000..cdfd53852
--- /dev/null
+++ b/test/stores/connectorApprovalStore.test.js
@@ -0,0 +1,296 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const load = () => import("../../src/stores/connectorApprovalStore.ts");
+
+const PREVIEW = {
+ verbKey: "default",
+ destinationLabel: "#eng",
+ accountLabel: "chad",
+ body: "Hello team",
+};
+
+function fakeElectron(commitImpl) {
+ const calls = { commit: [], cancel: [] };
+ return {
+ calls,
+ api: {
+ connectorCommit: async (actionId, edits) => {
+ calls.commit.push({ actionId, edits });
+ return commitImpl ? commitImpl() : { state: "sent", url: "https://slack.test/p/1" };
+ },
+ connectorCancel: async (actionId, reason) => {
+ calls.cancel.push({ actionId, reason });
+ return { cancelled: true };
+ },
+ },
+ };
+}
+
+function context(toolCallId, controller = new AbortController()) {
+ let requested = 0;
+ return {
+ controller,
+ requestedCount: () => requested,
+ value: {
+ toolCallId,
+ signal: controller.signal,
+ onApprovalRequested: () => {
+ requested += 1;
+ },
+ },
+ };
+}
+
+async function freshStore() {
+ const store = await load();
+ store.useConnectorApprovalStore.setState({ entries: {} });
+ return store;
+}
+
+test("a request shows a pending card and tells the surface", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const ctx = context("call-1");
+
+ void store.requestApproval(ctx.value, { actionId: "a1", connectorId: "slack", preview: PREVIEW });
+
+ assert.equal(store.useConnectorApprovalStore.getState().entries["call-1"].state, "pending");
+ assert.equal(ctx.requestedCount(), 1);
+ // Settle it so the 10-minute expiry timer doesn't keep the test process alive.
+ store.cancelApproval("call-1");
+});
+
+test("Send commits the edited draft once and reports the edited text", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-2").value, {
+ actionId: "a2",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ store.updateApprovalDraft("call-2", { body: "Hello team!" });
+ await Promise.all([store.approveAction("call-2"), store.approveAction("call-2")]);
+
+ assert.deepEqual(await outcome, {
+ state: "sent",
+ url: "https://slack.test/p/1",
+ finalText: "Hello team!",
+ });
+ assert.deepEqual(electron.calls.commit, [{ actionId: "a2", edits: { body: "Hello team!" } }]);
+ assert.equal(store.useConnectorApprovalStore.getState().entries["call-2"].state, "sent");
+});
+
+test("an unedited send commits the preview text and reports no edit", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-8").value, {
+ actionId: "a8",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ await store.approveAction("call-8");
+
+ assert.deepEqual(await outcome, { state: "sent", url: "https://slack.test/p/1" });
+ assert.deepEqual(electron.calls.commit[0].edits, { body: "Hello team" });
+});
+
+test("the draft is frozen once sending starts, and a title needs a titled preview", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-9").value, {
+ actionId: "a9",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ store.updateApprovalDraft("call-9", { title: "Not allowed" });
+ const sending = store.approveAction("call-9");
+ store.updateApprovalDraft("call-9", { body: "Too late" });
+ await sending;
+ await outcome;
+
+ assert.deepEqual(electron.calls.commit[0].edits, { body: "Hello team" });
+});
+
+test("Cancel withdraws a pending card", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-3").value, {
+ actionId: "a3",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ store.cancelApproval("call-3");
+
+ assert.deepEqual(await outcome, { state: "cancelled" });
+ assert.deepEqual(electron.calls.cancel, [{ actionId: "a3", reason: "cancelled_by_user" }]);
+});
+
+test("ending the conversation withdraws a pending card", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const ctx = context("call-4");
+ const outcome = store.requestApproval(ctx.value, {
+ actionId: "a4",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ ctx.controller.abort();
+
+ assert.deepEqual(await outcome, { state: "not_sent", reason: "conversation_ended" });
+ assert.deepEqual(electron.calls.cancel, [{ actionId: "a4", reason: "conversation_ended" }]);
+});
+
+test("ending the conversation during Send keeps the real result", async (t) => {
+ let releaseCommit;
+ const electron = fakeElectron(
+ () =>
+ new Promise((resolve) => {
+ releaseCommit = () => resolve({ state: "sent", url: "https://slack.test/p/5" });
+ })
+ );
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const ctx = context("call-5");
+ const outcome = store.requestApproval(ctx.value, {
+ actionId: "a5",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ const sending = store.approveAction("call-5");
+ ctx.controller.abort();
+ releaseCommit();
+ await sending;
+
+ assert.deepEqual(await outcome, { state: "sent", url: "https://slack.test/p/5" });
+ assert.equal(electron.calls.cancel.length, 0);
+});
+
+test("a commit IPC failure is reported as unknown, never as not sent", async (t) => {
+ const electron = fakeElectron(() => {
+ throw new Error("ipc channel closed");
+ });
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-6").value, {
+ actionId: "a6",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ await store.approveAction("call-6");
+
+ assert.deepEqual(await outcome, { state: "unknown" });
+});
+
+test("an unanswered card expires after ten minutes", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-7").value, {
+ actionId: "a7",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ t.mock.timers.tick(store.APPROVAL_TTL_MS);
+
+ assert.deepEqual(await outcome, { state: "not_sent", reason: "expired" });
+ assert.deepEqual(electron.calls.cancel, [{ actionId: "a7", reason: "expired" }]);
+});
+
+test("a commit result with the wrong key settles as unknown instead of hanging", async (t) => {
+ const electron = fakeElectron(() => ({ status: "sent", url: "https://slack.test/p/10" }));
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-10").value, {
+ actionId: "a10",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ await store.approveAction("call-10");
+
+ assert.deepEqual(await outcome, { state: "unknown" });
+ assert.equal(store.useConnectorApprovalStore.getState().entries["call-10"].state, "unknown");
+});
+
+test("a commit result with an unknown state settles as unknown instead of hanging", async (t) => {
+ const electron = fakeElectron(() => ({ state: "bogus" }));
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-12").value, {
+ actionId: "a12",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ await store.approveAction("call-12");
+
+ assert.deepEqual(await outcome, { state: "unknown" });
+ assert.equal(store.useConnectorApprovalStore.getState().entries["call-12"].state, "unknown");
+});
+
+test("a commit result that resolves undefined settles as unknown", async (t) => {
+ const electron = fakeElectron(() => undefined);
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const outcome = store.requestApproval(context("call-11").value, {
+ actionId: "a11",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ await store.approveAction("call-11");
+
+ assert.deepEqual(await outcome, { state: "unknown" });
+ assert.equal(store.useConnectorApprovalStore.getState().entries["call-11"].state, "unknown");
+});
+
+test("a duplicate request for the same tool call cancels the new action and leaves the first alone", async (t) => {
+ const electron = fakeElectron();
+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });
+ const store = await freshStore();
+ const ctx = context("call-12");
+ const firstOutcome = store.requestApproval(ctx.value, {
+ actionId: "a12-first",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ const secondOutcome = store.requestApproval(ctx.value, {
+ actionId: "a12-second",
+ connectorId: "slack",
+ preview: PREVIEW,
+ });
+
+ assert.deepEqual(await secondOutcome, { state: "not_sent", reason: "duplicate_tool_call" });
+ assert.deepEqual(electron.calls.cancel, [
+ { actionId: "a12-second", reason: "cancelled_by_user" },
+ ]);
+
+ const entry = store.useConnectorApprovalStore.getState().entries["call-12"];
+ assert.equal(entry.state, "pending");
+ assert.equal(entry.actionId, "a12-first");
+
+ await store.approveAction("call-12");
+
+ assert.deepEqual(await firstOutcome, { state: "sent", url: "https://slack.test/p/1" });
+ assert.deepEqual(electron.calls.commit, [
+ { actionId: "a12-first", edits: { body: "Hello team" } },
+ ]);
+});