Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(connectors): post to Slack from the assistant after approval (#2369)
Chad Pihad8d86df1a536
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.ymlindex 384e54879..cfa8c64a2 100644--- a/.github/workflows/build-and-notarize.yml+++ b/.github/workflows/build-and-notarize.yml@@ -132,6 +132,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Verify PipeWire system audio helper buildrun: |@@ -249,6 +250,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Build and Sign Applicationrun: |@@ -387,6 +389,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Build Application (${{ matrix.arch }})run: npm run build:mac -- --${{ matrix.arch }} --publish neverdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 2f9d8d4d4..fab67bcad 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -127,6 +127,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Verify PipeWire system audio helper buildrun: |@@ -243,6 +244,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Build and Sign Applicationrun: npm run build:win -- --publish always@@ -363,6 +365,7 @@ jobs:echo "GOOGLE_CALENDAR_CLIENT_ID=${{ secrets.GOOGLE_CALENDAR_CLIENT_ID }}" >> .envecho "GOOGLE_CALENDAR_CLIENT_SECRET=${{ secrets.GOOGLE_CALENDAR_CLIENT_SECRET }}" >> .envecho "MICROSOFT_CALENDAR_CLIENT_ID=${{ secrets.MICROSOFT_CALENDAR_CLIENT_ID }}" >> .env+ echo "SLACK_CLIENT_ID=${{ secrets.SLACK_CLIENT_ID }}" >> .env- name: Build Application (${{ matrix.arch }})run: npm run build:mac -- --${{ matrix.arch }} --publish alwaysdiff --git a/CLAUDE.md b/CLAUDE.mdindex a4247e9e2..d603ff63a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -173,6 +173,8 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- 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+ - Slack (`slackConnector.js`): PKCE user token through `oauthLoopbackFlow.js`. Slack only distributes apps with HTTPS redirect URLs, so it redirects to the openwhispr.com relay (`openwhispr-website`, `app/auth/slack/callback/route.ts`), which forwards to the loopback server by the port in `state` (`v1.<port>.<nonce>`). The loopback server shows a local result page, and the flow waits 5 minutes. `SLACK_OAUTH_REDIRECT_URI` points a dev build at a website preview. Rotating tokens refresh single-flight, only for the login a pending action is bound to, and are saved before use; transient refresh errors never disconnect (`slackAuth.js`). Channels the user is in and people are cached 10 min; a list cut off at the page cap resolves only an exact #channel or an email (`slackDirectory.js`, `targetResolution.js`). `conversations.open` runs only at Send. Disconnect revokes the refresh and access tokens. Failures follow `SLACK_PRE_SEND_REJECTIONS` (`slackApi.js`); everything else is `unknown`+ - Logins: one encrypted file per OpenWhispr account and connector under `userData/connectors/` (atomic writes, `0o700`, `connectorCredentials.js`). Every write names the account and the generation it started from, so an OAuth round trip, refresh or disconnect that outlives a reconnect or account switch writes nothing. Bindings carry `ownerAccountId`; receipts carry `account_id`. Signed out → every connector action is refused (`signed_out`). Pending actions also expire in main (`sweepExpired`, every minute)- **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/)@@ -703,7 +705,7 @@ A dedicated global hotkey that starts a dictation whose transcript is sent strai4. 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 chat5. 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 clipboard6. 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)+7. Connector tools (`email_draft`, `find_contact`, `slack_send_message`; 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), any `find_contact` (a lookup is almost always followed by a question for the user), and any `slack_send_message` (holds on every outcome — a card, a question back, or a receipt) 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.jsindex 0c6048dee..63b9ec9b2 100644--- a/main.js+++ b/main.js@@ -472,17 +472,79 @@ function initializeCoreManagers() {const { createConnectorManager } = require("./src/helpers/connectors/connectorManager");const { createPendingActions } = require("./src/helpers/connectors/pendingActions");const { createActionLog } = require("./src/helpers/connectors/actionLog");+ const { createCredentialStore } = require("./src/helpers/connectors/credentialStore");+ const { createConnectorCredentials } = require("./src/helpers/connectors/connectorCredentials");+ const { createSlackApi } = require("./src/helpers/connectors/slackApi");+ const { createSlackAuth } = require("./src/helpers/connectors/slackAuth");+ const { createSlackDirectory } = require("./src/helpers/connectors/slackDirectory");+ const { createSlackConnector } = require("./src/helpers/connectors/slackConnector");+ const { renderOAuthResultPage } = require("./src/helpers/connectors/oauthResultPage");+ const { runOAuthLoopbackFlow, OAuthFlowError } = require("./src/helpers/oauthLoopbackFlow");+ const { broadcastToWindows } = require("./src/helpers/windowBroadcast");+ const { connectorAccountIdFrom } = require("./src/helpers/connectors/connectorIpc");+ // The same account receipts are filed under (ipcHandlers' getAccountScope):+ // the one bound to the credential in use. databaseManager's scope doesn't+ // move when one signed-in token replaces another.+ const getConnectorAccountScope = () =>+ accountScopeBinding.resolveActiveAccountScope({+ ...require("./src/helpers/tokenStore").getState(),+ binding: accountScopeBinding.read(),+ });+ const getConnectorAccountId = connectorAccountIdFrom(getConnectorAccountScope);+ const connectorCredentials = createConnectorCredentials({+ store: createCredentialStore({+ dir: path.join(app.getPath("userData"), "connectors"),+ secretCrypto: require("./src/helpers/secretCrypto"),+ logger: debugLogger,+ }),+ getAccountId: getConnectorAccountId,+ });+ const slackApi = createSlackApi({+ fetchImpl: (url, init) => net.fetch(url, { ...init, useSessionCookies: false }),+ });+ const slackAuth = createSlackAuth({+ api: slackApi,+ credentials: connectorCredentials,+ getClientId: () => process.env.SLACK_CLIENT_ID,+ runOAuthLoopbackFlow,+ OAuthFlowError,+ renderResultPage: ({ ok }) =>+ renderOAuthResultPage({+ ok,+ title: i18nMain.t(+ ok ? "connectors.slack.browser.connectedTitle" : "connectors.slack.browser.failedTitle"+ ),+ body: i18nMain.t(+ ok ? "connectors.slack.browser.connectedBody" : "connectors.slack.browser.failedBody"+ ),+ }),+ // Shared by every consumer of Slack auth: its single-flight refresh map is+ // per instance, so a second instance could spend the same single-use+ // refresh token.+ logger: debugLogger,+ });connectorManager = createConnectorManager({connectors: [require("./src/helpers/connectors/emailConnector").createEmailConnector({openExternal: (url) => require("./src/helpers/externalUrlOpener").openExternalUrl(url),writeClipboard: (text, webContents) => clipboardManager.writeClipboard(text, webContents),}),+ createSlackConnector({+ api: slackApi,+ auth: slackAuth,+ directory: createSlackDirectory({ api: slackApi }),+ credentials: connectorCredentials,+ }),],pendingActions: createPendingActions(),actionLog: createActionLog(databaseManager),logger: debugLogger,+ getAccountId: getConnectorAccountId,+ credentials: connectorCredentials,+ onStatusChanged: (statuses) => broadcastToWindows("connector-status-changed", statuses),});+ // Pending cards expire in main even when no renderer ever answers them.+ setInterval(() => connectorManager.sweepExpired(), 60 * 1000).unref();whisperManager = new WhisperManager();if (process.platform !== "darwin") {whisperCudaManager = new WhisperCudaManager();diff --git a/preload.js b/preload.jsindex b4e1c2967..64ef8e4fb 100644--- a/preload.js+++ b/preload.js@@ -1273,6 +1273,13 @@ contextBridge.exposeInMainWorld("electronAPI", {connectorRecentActions: (connectorId, limit) =>ipcRenderer.invoke("connector-recent-actions", connectorId, limit),connectorFindContacts: (query) => ipcRenderer.invoke("connector-find-contacts", query),+ connectorConnect: (connectorId) => ipcRenderer.invoke("connector-connect", connectorId),+ connectorDisconnect: (connectorId) => ipcRenderer.invoke("connector-disconnect", connectorId),+ onConnectorStatusChanged: (callback) => {+ const listener = (_event, statuses) => callback(statuses);+ ipcRenderer.on("connector-status-changed", listener);+ return () => ipcRenderer.removeListener("connector-status-changed", listener);+ },calendarGetAvailability: (request) => ipcRenderer.invoke("calendar-get-availability", request),gcalGetEvent: (eventId) => ipcRenderer.invoke("gcal-get-event", eventId),diff --git a/src/components/ConnectorsSection.tsx b/src/components/ConnectorsSection.tsxindex 1e77513a2..89e688701 100644--- a/src/components/ConnectorsSection.tsx+++ b/src/components/ConnectorsSection.tsx@@ -1,36 +1,29 @@-import { useEffect, useState, useSyncExternalStore, type ReactElement } from "react";+import { 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 { SettingsPanel, SettingsPanelRow } from "./ui/SettingsSection";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";+import { RecentActions } from "./connectors/RecentActions";+import { SlackConnectorRow } from "./connectors/SlackConnectorRow";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 { t } = 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.@@ -45,35 +38,6 @@ export function ConnectorsSection({ onUpgrade }: ConnectorsSectionProps): ReactEconst 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",@@ -133,33 +97,9 @@ export function ConnectorsSection({ onUpgrade }: ConnectorsSectionProps): ReactE)}</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>- )}+ {showActions && <RecentActions connectorId="email" />}</SettingsPanelRow>+ <SlackConnectorRow isPaid={isPaid} blockedByOrg={blockedByOrg} onUpgrade={onUpgrade} /></SettingsPanel>);}diff --git a/src/components/chat/ApprovalCard.tsx b/src/components/chat/ApprovalCard.tsxindex a986de5f1..787ae3a3b 100644--- a/src/components/chat/ApprovalCard.tsx+++ b/src/components/chat/ApprovalCard.tsx@@ -1,4 +1,4 @@-import { useState, type ReactElement } from "react";+import { useRef, useState, type KeyboardEvent, type ReactElement } from "react";import { useTranslation } from "react-i18next";import { Button } from "../ui/button";import {@@ -7,6 +7,7 @@ import {updateApprovalDraft,type ApprovalEntry,} from "../../stores/connectorApprovalStore";+import { connectorErrorCopyKey } from "../../utils/connectorErrorCopy";// The draft lives in the store, so edit mode only changes how it is shown:// Send always commits exactly what the card displays.@@ -14,13 +15,38 @@ export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElementconst { t } = useTranslation();const { preview, draft } = entry;const [editing, setEditing] = useState(false);+ const cardRef = useRef<HTMLDivElement>(null);const destination = preview.destinationLabel;+ // The fields exist only while the card can still change.+ const showEditor = editing && entry.state === "pending";++ // Send and Cancel remove the button that had focus; the card keeps it, so+ // keyboard and screen-reader users land on the result.+ const leaveEditingAndFocusCard = (): void => {+ setEditing(false);+ cardRef.current?.focus();+ };++ // Esc in a field ends editing and keeps the draft. It must not reach the+ // assistant panel, whose Esc cancels the whole turn and withdraws the card.+ const onEditorKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopPropagation();+ setEditing(false);+ };++ const openLink = (url: string): void => {+ void window.electronAPI?.openExternal?.(url);+ };return (<div- data-approval-card={entry.toolCallId}+ ref={cardRef}+ tabIndex={-1}+ data-approval-card={entry.key}data-state={entry.state}- className="my-1.5 rounded-lg border border-border/70 bg-surface-2/60 p-3 text-[13px]"+ className="my-1.5 rounded-lg border border-border/70 bg-surface-2/60 p-3 text-[13px] outline-none focus-visible:ring-1 focus-visible:ring-ring"><p className="font-medium text-foreground">{t(`connectors.approval.headers.${preview.verbKey}`, {@@ -37,17 +63,15 @@ export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElement: t("connectors.approval.identity", { account: preview.accountLabel })}</p>- {editing ? (- <div className="mt-2 space-y-2">+ {showEditor ? (+ <div className="mt-2 space-y-2" onKeyDown={onEditorKeyDown}>{draft.title !== undefined && (<inputaria-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 })- }+ onChange={(event) => updateApprovalDraft(entry.key, { title: event.target.value })}/>)}<textarea@@ -55,9 +79,7 @@ export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElementclassName="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 })- }+ onChange={(event) => updateApprovalDraft(entry.key, { body: event.target.value })}/></div>) : (@@ -75,14 +97,64 @@ export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElement</p>))}+ {/* One live region for every outcome, rendered from the start so a+ screen reader announces each change. */}+ <div role="status" aria-live="polite" className="text-xs">+ {entry.state === "pending" && entry.notice === "policy_retry" && (+ <p className="mt-2 text-muted-foreground">{t("connectors.approval.policyRetry")}</p>+ )}+ {entry.state === "committing" && (+ <p className="mt-2 text-muted-foreground">{t("connectors.approval.sending")}</p>+ )}+ {entry.state === "sent" && (+ <p className="mt-2 text-foreground">+ {t("connectors.approval.sent", { destination })}+ {entry.url && (+ <Button size="sm" variant="link" onClick={() => openLink(entry.url as string)}>+ {t("connectors.approval.open")}+ </Button>+ )}+ </p>+ )}+ {/* Translated copy only: entry.message is the connector's English,+ written for the model. */}+ {entry.state === "failed" && (+ <p className="mt-2 text-destructive">+ {t("connectors.approval.failed", {+ message: t(`connectors.approval.errors.${connectorErrorCopyKey(entry.errorCode)}`, {+ destination,+ defaultValue: t("connectors.approval.errors.generic"),+ }),+ })}+ </p>+ )}+ {entry.state === "unknown" && (+ <p className="mt-2 text-foreground">+ {t("connectors.approval.unknown", { destination })}+ {entry.url && (+ <Button size="sm" variant="link" onClick={() => openLink(entry.url as string)}>+ {t("connectors.approval.open")}+ </Button>+ )}+ </p>+ )}+ {entry.state === "cancelled" && (+ <p className="mt-2 text-muted-foreground">{t("connectors.approval.cancelled")}</p>+ )}+ {entry.state === "not_sent" && (+ <p className="mt-2 text-muted-foreground">{t("connectors.approval.notSent")}</p>+ )}+ </div>+{entry.state === "pending" && (<div className="mt-2 flex gap-2"><Buttonsize="sm"onClick={() => {- // A frozen textarea would look editable while the draft sends.- setEditing(false);- void approveAction(entry.toolCallId);+ // Leaving the editor also means a frozen textarea never looks+ // editable while the draft sends.+ leaveEditingAndFocusCard();+ void approveAction(entry.key);}}>{t("connectors.approval.send")}@@ -90,55 +162,18 @@ export function ApprovalCard({ entry }: { entry: ApprovalEntry }): ReactElement<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)}>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ leaveEditingAndFocusCard();+ cancelApproval(entry.key);+ }}+ >{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.tsxindex 686adf007..c493d1c6a 100644--- a/src/components/chat/ChatMessage.tsx+++ b/src/components/chat/ChatMessage.tsx@@ -7,9 +7,10 @@ import type { ToolCallInfo } from "./types";import { extractNoteCards } from "./noteCards";import { toolIcons } from "./toolIcons";import { ApprovalCard } from "./ApprovalCard";-import { useConnectorApprovalStore } from "../../stores/connectorApprovalStore";+import { approvalKey, useConnectorApprovalStore } from "../../stores/connectorApprovalStore";interface ChatMessageProps {+ messageId: string;role: "user" | "assistant";content: string;isStreaming: boolean;@@ -124,8 +125,10 @@ 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]);+function ToolCallItem({ messageId, toolCall }: { messageId: string; toolCall: ToolCallInfo }) {+ const approval = useConnectorApprovalStore(+ (state) => state.entries[approvalKey(messageId, toolCall.id)]+ );return approval ? <ApprovalCard entry={approval} /> : <ToolCallStep toolCall={toolCall} />;}@@ -172,6 +175,7 @@ function NoteCard({}export function ChatMessage({+ messageId,role,content,isStreaming,@@ -235,7 +239,7 @@ export function ChatMessage({)}>{toolCalls.map((tc) => (- <ToolCallItem key={tc.id} toolCall={tc} />+ <ToolCallItem key={tc.id} messageId={messageId} toolCall={tc} />))}</div>)}diff --git a/src/components/chat/ChatMessages.tsx b/src/components/chat/ChatMessages.tsxindex c3ce2273a..d7e0a9235 100644--- a/src/components/chat/ChatMessages.tsx+++ b/src/components/chat/ChatMessages.tsx@@ -47,6 +47,7 @@ export function ChatMessages({.map((msg) => (<ChatMessagekey={msg.id}+ messageId={msg.id}role={msg.role as "user" | "assistant"}content={msg.content}isStreaming={msg.isStreaming}diff --git a/src/components/chat/toolExecutionScope.ts b/src/components/chat/toolExecutionScope.tsindex 63ff8512d..7778c2a26 100644--- a/src/components/chat/toolExecutionScope.ts+++ b/src/components/chat/toolExecutionScope.ts@@ -1,7 +1,15 @@import type { HoldDeliveryOptions, ToolExecutionContext } from "../../services/tools/ToolRegistry";+export interface ToolContextRequest {+ /** The assistant message the tool call belongs to. */+ messageId: string;+ toolCallId: string;+ /** The model SDK's own per-call abort signal, when it has one. */+ signal?: AbortSignal;+}+export interface ToolExecutionScope {- createContext: (toolCallId: string) => ToolExecutionContext;+ createContext: (request: ToolContextRequest) => ToolExecutionContext;abort: () => void;}@@ -36,9 +44,12 @@ export function createToolExecutionScope(handlers: ToolExecutionHandlers = {}):if (used > 0) turnSlots.set(key, used - 1);};return {- createContext: (toolCallId) => ({+ createContext: ({ messageId, toolCallId, signal }) => ({+ messageId,toolCallId,- signal: controller.signal,+ // Either the turn ending or the SDK abandoning this one call releases+ // whatever the tool is waiting on.+ signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal,onApprovalRequested: notify(handlers.onApprovalRequested),onHoldDelivery: notify(handlers.onHoldDelivery),claimTurnSlot,diff --git a/src/components/chat/toolIcons.ts b/src/components/chat/toolIcons.tsindex e70eb56b3..f9aa2d63e 100644--- a/src/components/chat/toolIcons.ts+++ b/src/components/chat/toolIcons.ts@@ -11,6 +11,7 @@ import {Zap,Mail,Users,+ MessageSquare,} from "../icons";export const toolIcons: Record<string, typeof Search> = {@@ -27,4 +28,5 @@ export const toolIcons: Record<string, typeof Search> = {update_dictionary: BookOpen,email_draft: Mail,find_contact: Users,+ slack_send_message: MessageSquare,};diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.tsindex 7311a4416..32f9e97a6 100644--- a/src/components/chat/useChatStreaming.ts+++ b/src/components/chat/useChatStreaming.ts@@ -17,6 +17,7 @@ import { getUsageState } from "../../lib/usageStore";import { readIsSubscribed } from "../../lib/subscriptionFlag";import { hasConnectorPlan } from "../../utils/connectorEligibility";import { resolveEmailDraftTarget } from "../../utils/emailDraftTarget";+import { ensureConnectorStatus, isConnectorReady } from "../../stores/connectorStatusStore";import {appendDictionarySuffix,appendPlainTextResponseSuffix,@@ -347,16 +348,20 @@ export function useChatStreaming({const calendarConnected =settings.gcalConnected || settings.mcalConnected || settings.appleCalendarConnected;const webSearchEnabled = isWebSearchAllowed(usePolicyStore.getState());- const connectors =+ const connectorsAvailable =allowConnectors &&settings.isSignedIn &&hasConnectorPlan(getUsageState(), readIsSubscribed()) &&- isConnectorsAllowed(usePolicyStore.getState())- ? { emailDraftTarget: resolveEmailDraftTarget(settings) }- : undefined;+ isConnectorsAllowed(usePolicyStore.getState());+ // The first send in a window must not miss a connected Slack.+ if (connectorsAvailable) await ensureConnectorStatus();+ const slackReady = connectorsAvailable && isConnectorReady("slack");+ const connectors = connectorsAvailable+ ? { emailDraftTarget: resolveEmailDraftTarget(settings), slackReady }+ : 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"}`;+ const cacheKey = `${settings.isSignedIn}-${calendarConnected}-${settings.cloudBackupEnabled}-${scopeKey}-${webSearchEnabled}-${snippetKey}-${connectors?.emailDraftTarget ?? "no-connectors"}-${slackReady}`;if (toolRegistryRef.current?.key === cacheKey) {registry = toolRegistryRef.current.registry;} else {@@ -489,7 +494,11 @@ export function useChatStreaming({displayText: t("agentMode.tools.invalidArgs", { name }),};}- const result = await executeTool(tool, args, toolScope.createContext(toolCallId));+ const result = await executeTool(+ tool,+ args,+ toolScope.createContext({ messageId: assistantId, toolCallId })+ );const data = result.success? typeof result.data === "string"? result.data@@ -514,8 +523,14 @@ export function useChatStreaming({...(cloudScreenContext ? { screenContext: cloudScreenContext } : {}),});} else {- const aiTools = registry?.toAISDKFormat(toolScope.createContext, (id, text) =>- toolDisplayTexts.set(id, text)+ const aiTools = registry?.toAISDKFormat(+ (toolCallId, abortSignal) =>+ toolScope.createContext({+ messageId: assistantId,+ toolCallId,+ signal: abortSignal,+ }),+ (id, text) => toolDisplayTexts.set(id, text));stream = ReasoningService.processTextStreamingAI(llmMessages,diff --git a/src/components/connectors/RecentActions.tsx b/src/components/connectors/RecentActions.tsxnew file mode 100644index 000000000..8c60c60bd--- /dev/null+++ b/src/components/connectors/RecentActions.tsx@@ -0,0 +1,94 @@+import { useEffect, useState, type ReactElement } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "../ui/button";+import { SectionLabel } from "../ui/SettingsSection";+import { normalizeDbDate } from "../../utils/dateFormatting";+import type { ConnectorActionRecord } from "../../types/connectors";++function formatWhen(createdAt: string, locale: string): string {+ const date = normalizeDbDate(createdAt);+ return Number.isNaN(date.getTime())+ ? createdAt+ : date.toLocaleString(locale, { dateStyle: "short", timeStyle: "short" });+}++function isWebUrl(value: string | null): value is string {+ return typeof value === "string" && value.startsWith("https://");+}++/** The last ten receipts for one connector: labels, times and states, never content. */+export function RecentActions({+ connectorId,+ refreshKey = "",+}: {+ connectorId: string;+ refreshKey?: string;+}): ReactElement | null {+ const { t, i18n } = useTranslation();+ 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([]);+ let active = true;+ void window.electronAPI+ ?.connectorRecentActions?.(connectorId, 10)+ .then((rows) => {+ if (active) setRecent(rows ?? []);+ })+ .catch(() => {+ if (active) setRecent([]);+ });+ return () => {+ active = false;+ };+ }, [connectorId, refreshKey, accountScopeChanges]);++ if (recent.length === 0) return null;+ return (+ <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}`)}+ {isWebUrl(row.resultUrl) && (+ <Button+ size="sm"+ variant="link"+ className="h-auto p-0 ms-1"+ onClick={() => void window.electronAPI?.openExternal?.(row.resultUrl as string)}+ >+ {t("connectors.approval.open")}+ </Button>+ )}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/src/components/connectors/SlackConnectorRow.tsx b/src/components/connectors/SlackConnectorRow.tsxnew file mode 100644index 000000000..238d85d85--- /dev/null+++ b/src/components/connectors/SlackConnectorRow.tsx@@ -0,0 +1,160 @@+import { useEffect, useRef, useState, type ReactElement } from "react";+import { useTranslation } from "react-i18next";+import { MessageSquare } from "../icons";+import { Button } from "../ui/button";+import { SettingsPanelRow } from "../ui/SettingsSection";+import { RecentActions } from "./RecentActions";+import { ensureConnectorStatus, useConnectorStatusStore } from "../../stores/connectorStatusStore";++type RowPhase = "idle" | "connecting" | "disconnecting";++// Connect and disconnect failures with their own copy; anything else reads+// as a generic failure.+const ROW_ERRORS = new Set([+ "oauth_denied",+ "oauth_timeout",+ "oauth_state_mismatch",+ "ports_busy",+ "token_exchange_failed",+ "not_configured",+ "connection_changed",+ "signed_out",+ "policy_blocked",+ "policy_unavailable",+ "disconnect_failed",+]);++interface SlackConnectorRowProps {+ isPaid: boolean;+ blockedByOrg: boolean;+ onUpgrade: () => void;+}++export function SlackConnectorRow({+ isPaid,+ blockedByOrg,+ onUpgrade,+}: SlackConnectorRowProps): ReactElement | null {+ const { t } = useTranslation();+ const status = useConnectorStatusStore((state) => state.statuses.slack);+ const [phase, setPhase] = useState<RowPhase>("idle");+ const [errorCode, setErrorCode] = useState<string | null>(null);+ const latestAttempt = useRef(0);++ // Loaded for every plan: a lapsed plan must still see, and remove, its login.+ useEffect(() => {+ void ensureConnectorStatus();+ }, []);++ const connected = Boolean(status?.connected);+ const needsReconnect = connected && Boolean(status?.needsReconnect);+ const canConnect = isPaid && !blockedByOrg;++ // The status broadcast from main updates the row; results only carry a+ // failure to show. Connect stays clickable while the browser is open: a+ // new attempt replaces an abandoned one, which main cancels+ // ("oauth_cancelled", not an error), so only the latest attempt's result+ // reaches the row.+ const connect = async (): Promise<void> => {+ const attempt = ++latestAttempt.current;+ const isLatest = (): boolean => attempt === latestAttempt.current;+ setPhase("connecting");+ setErrorCode(null);+ try {+ const result = await window.electronAPI?.connectorConnect?.("slack");+ if (!isLatest()) return;+ if (!result) setErrorCode("connect_failed");+ else if (result.status === "failed" && result.errorCode !== "oauth_cancelled") {+ setErrorCode(result.errorCode);+ } else if (result.status === "unavailable") setErrorCode(result.reason);+ } catch {+ if (isLatest()) setErrorCode("connect_failed");+ } finally {+ if (isLatest()) setPhase("idle");+ }+ };++ const disconnect = async (): Promise<void> => {+ setPhase("disconnecting");+ setErrorCode(null);+ try {+ const result = await window.electronAPI?.connectorDisconnect?.("slack");+ if (!result) setErrorCode("disconnect_failed");+ else if (result.status === "failed") setErrorCode(result.errorCode);+ else if (result.status === "unavailable") setErrorCode(result.reason);+ } catch {+ setErrorCode("disconnect_failed");+ } finally {+ setPhase("idle");+ }+ };++ // With connectors turned off, the row exists only to remove a login.+ if (blockedByOrg && !connected) return null;++ let summary = t("connectors.slack.description");+ if (needsReconnect) summary = t("connectors.slack.needsReconnect");+ else if (connected) {+ summary = t("connectors.slack.connectedAs", {+ account: status?.accountLabel ?? "",+ workspace: status?.workspaceLabel ?? "",+ });+ } else if (phase === "connecting") summary = t("connectors.slack.connecting");+ else if (!isPaid) summary = t("connectors.slack.proRequired");++ return (+ <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">+ <MessageSquare className="w-4 h-4 text-primary" aria-hidden="true" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-semibold text-foreground">{t("connectors.slack.title")}</p>+ <p className="text-xs text-muted-foreground/70 mt-0.5 leading-relaxed" dir="auto">+ {summary}+ </p>+ {errorCode && (+ <p role="alert" className="text-xs text-destructive mt-1">+ {t(+ `connectors.slack.errors.${ROW_ERRORS.has(errorCode) ? errorCode : "connect_failed"}`+ )}+ </p>+ )}+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {needsReconnect && canConnect && (+ <Button size="sm" disabled={phase === "disconnecting"} onClick={() => void connect()}>+ {t("connectors.slack.reconnect")}+ </Button>+ )}+ {connected && (+ <Button+ size="sm"+ variant="outline"+ disabled={phase !== "idle"}+ onClick={() => void disconnect()}+ >+ {t("connectors.slack.disconnect")}+ </Button>+ )}+ {!connected && canConnect && (+ <Button size="sm" disabled={phase === "disconnecting"} onClick={() => void connect()}>+ {t("connectors.slack.connect")}+ </Button>+ )}+ {!connected && !isPaid && (+ <Button size="sm" className="shrink-0" onClick={onUpgrade}>+ {t("integrations.api.viewPlans")}+ </Button>+ )}+ </div>+ </div>+ {connected && (+ <RecentActions+ connectorId="slack"+ refreshKey={`${status?.accountLabel ?? ""}:${status?.workspaceLabel ?? ""}`}+ />+ )}+ </SettingsPanelRow>+ );+}diff --git a/src/components/dictation/AssistantPanel.tsx b/src/components/dictation/AssistantPanel.tsxindex 9a3f1ee52..3979cc8e8 100644--- a/src/components/dictation/AssistantPanel.tsx+++ b/src/components/dictation/AssistantPanel.tsx@@ -44,7 +44,7 @@ import {} from "../../helpers/assistantResponseDelivery";import { buildAssistantCommandSendOptions } from "./assistantCommandOptions";import { ApprovalCard } from "../chat/ApprovalCard";-import { useConnectorApprovalStore } from "../../stores/connectorApprovalStore";+import { approvalKey, useConnectorApprovalStore } from "../../stores/connectorApprovalStore";export interface AssistantCommand {id: number;@@ -256,9 +256,11 @@ export function AssistantPanel({]);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 panelApprovals = latestAssistantMessage+ ? (latestAssistantMessage.toolCalls ?? [])+ .map((toolCall) => approvalEntries[approvalKey(latestAssistantMessage.id, toolCall.id)])+ .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry))+ : [];const approvalAwaitingUser = panelApprovals.some((entry) => entry.state === "pending" || entry.state === "committing");@@ -523,7 +525,7 @@ export function AssistantPanel({</div>) : null}{panelApprovals.map((entry) => (- <ApprovalCard key={entry.toolCallId} entry={entry} />+ <ApprovalCard key={entry.key} entry={entry} />))}{thinking && (<div role="status">diff --git a/src/config/prompts.ts b/src/config/prompts.tsindex f09db31fe..31e542d10 100644--- a/src/config/prompts.ts+++ b/src/config/prompts.ts@@ -54,6 +54,8 @@ const TOOL_INSTRUCTIONS: Record<string, string> = {"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.",+ slack_send_message:+ "Use slack_send_message to post to a Slack channel or person as the user; the user approves each message on a card before it is sent. For a person, pass their name, @handle or email address.",};const twoDigits = (value: number): string => String(value).padStart(2, "0");@@ -75,7 +77,7 @@ function getLocalCalendarContext(): string {return `Current local date and time: ${formatLocalRfc3339(now)}. IANA time zone: ${timeZone}.`;}-const CONNECTOR_TOOL_NAMES = ["find_contact", "email_draft"];+const CONNECTOR_TOOL_NAMES = ["find_contact", "email_draft", "slack_send_message"];// 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).diff --git a/src/helpers/connectors/actionLog.js b/src/helpers/connectors/actionLog.jsindex 4329bd415..a7b19d6f2 100644--- a/src/helpers/connectors/actionLog.js+++ b/src/helpers/connectors/actionLog.js@@ -4,7 +4,7 @@ function createActionLog(databaseManager) {update: (id, patch, fromState) =>databaseManager.updateConnectorActionState(id, patch, fromState ?? null),listRecent: (connector, limit, accountId) =>- databaseManager.listRecentConnectorActions(connector, limit, accountId),+ databaseManager.listRecentConnectorActions(connector, limit, accountId ?? null),reconcileInterrupted: () => databaseManager.reconcileInterruptedConnectorActions(),};}diff --git a/src/helpers/connectors/connectorCredentials.js b/src/helpers/connectors/connectorCredentials.jsnew file mode 100644index 000000000..49afaf091--- /dev/null+++ b/src/helpers/connectors/connectorCredentials.js@@ -0,0 +1,63 @@+const crypto = require("crypto");++// One login per OpenWhispr account and connector. The file name hashes the+// account id, so any id is a safe file name, and one account's login is+// never overwritten by, or read as, another's.+function slotFor(accountId, connectorId) {+ const accountKey = crypto+ .createHash("sha256")+ .update(String(accountId))+ .digest("hex")+ .slice(0, 24);+ return `${connectorId}-${accountKey}`;+}++function codedError(code) {+ return Object.assign(new Error(code), { code });+}++function createConnectorCredentials({ store, getAccountId }) {+ const generation = (accountId, connectorId) =>+ accountId ? store.getGeneration(slotFor(accountId, connectorId)) : 0;++ // The login stored for this account, with the generation it was read at.+ function read(accountId, connectorId) {+ if (!accountId) return null;+ const credential = store.read(slotFor(accountId, connectorId));+ return credential ? { credential, generation: generation(accountId, connectorId) } : null;+ }++ // Every write names the account and the generation its caller started+ // from. A reconnect, disconnect or account switch that landed in between+ // wins, and the late write is refused instead of overwriting it.+ function expect(accountId, connectorId, expectedGeneration) {+ if (!accountId) throw codedError("signed_out");+ if (generation(accountId, connectorId) !== expectedGeneration) {+ throw codedError("connection_changed");+ }+ }++ return {+ activeAccountId: () => getAccountId() || null,+ read,+ generation,+ // A new login: approvals bound to the old one must not send.+ replace(accountId, connectorId, credential, expectedGeneration) {+ expect(accountId, connectorId, expectedGeneration);+ store.replace(slotFor(accountId, connectorId), credential);+ return generation(accountId, connectorId);+ },+ // A token refresh for the same login keeps its generation, so approvals+ // bound to it stay valid.+ save(accountId, connectorId, credential, expectedGeneration) {+ expect(accountId, connectorId, expectedGeneration);+ store.save(slotFor(accountId, connectorId), credential);+ },+ clear(accountId, connectorId, expectedGeneration) {+ expect(accountId, connectorId, expectedGeneration);+ store.clear(slotFor(accountId, connectorId));+ },+ };+}++module.exports = { createConnectorCredentials, slotFor };diff --git a/src/helpers/connectors/connectorIpc.js b/src/helpers/connectors/connectorIpc.jsindex 1dcb2e9b9..dea57702d 100644--- a/src/helpers/connectors/connectorIpc.js+++ b/src/helpers/connectors/connectorIpc.js@@ -12,6 +12,18 @@ function isPlainObject(value) {return value !== null && typeof value === "object" && !Array.isArray(value);}+// Connectors must tell "signed out" ({}) from "can't tell" (null). Without a+// bearer token only the sender's window can read the cookie session, so a+// window that is already gone must not read as signed out.+function createConnectorAuthLookup({ hasBearerToken, windowFor, authHeaderFor }) {+ return async (event) => {+ if (hasBearerToken()) return authHeaderFor(null);+ const win = windowFor(event);+ if (!win || win.isDestroyed()) return null;+ return authHeaderFor(win);+ };+}+function createConnectorPolicyResolver({getAuthHeader,getPolicy,@@ -24,13 +36,15 @@ function createConnectorPolicyResolver({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.+ // Read before the lookup: a sign-in or sign-out during it then fails+ // the policy fetch's generation check instead of passing it.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";+ const authHeaders = await getAuthHeader(event);+ if (!authHeaders || typeof authHeaders !== "object") return "unavailable";+ // Connector logins outlive an OpenWhispr sign-out, so no account means+ // no action (unlike screen context, where signed out is allowed).+ if (!authHeaders.Authorization && !authHeaders.Cookie) return "signed_out";+ // Assigned before the fetch: the deadline's fallback peeks this request.request = { expectedAuthGeneration, authHeaders };const snapshot = await getPolicy(request);return connectorPolicyState(snapshot);@@ -56,6 +70,13 @@ function createConnectorPolicyResolver({};}+// Connect, disconnect and the connectors' bindings file logins under the+// account receipts are filed under: the one getAccountScope() binds to the+// credential in use, or none.+function connectorAccountIdFrom(getAccountScope) {+ return () => getAccountScope()?.accountId ?? null;+}+function sameAccountScope(left, right) {return Boolean(left &&@@ -141,6 +162,17 @@ function registerConnectorIpc({ ipcMain, manager, getPolicyState, getAccountScopreturn manager.recentActions(connectorId, limit, getAccountScope()?.accountId ?? null);});+ ipcMain.handle("connector-connect", async (event, connectorId) => {+ if (!isNonEmptyString(connectorId)) return { status: "unavailable", reason: "invalid_request" };+ return manager.connect(connectorId, await getPolicyState(event));+ });++ // Removing access is always allowed, so disconnect skips the policy check.+ ipcMain.handle("connector-disconnect", (_event, connectorId) => {+ if (!isNonEmptyString(connectorId)) return { status: "unavailable", reason: "invalid_request" };+ return manager.disconnect(connectorId);+ });+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.@@ -155,4 +187,9 @@ function registerConnectorIpc({ ipcMain, manager, getPolicyState, getAccountScop}}-module.exports = { registerConnectorIpc, createConnectorPolicyResolver };+module.exports = {+ registerConnectorIpc,+ createConnectorPolicyResolver,+ createConnectorAuthLookup,+ connectorAccountIdFrom,+};diff --git a/src/helpers/connectors/connectorManager.js b/src/helpers/connectors/connectorManager.jsindex 25f58fc0c..0a61fc246 100644--- a/src/helpers/connectors/connectorManager.js+++ b/src/helpers/connectors/connectorManager.js@@ -1,4 +1,5 @@const crypto = require("crypto");+const { describeError } = require("./errorSummary");const { policyRefusal } = require("./connectorPolicy");const CANCEL_REASONS = new Set(["cancelled_by_user", "conversation_ended", "expired"]);@@ -42,7 +43,10 @@ function normalizeCommitResult(result) {case "failed":return failedResult(result);case "unknown":- return { state: "unknown", ...stringFields({ checkUrl: result.checkUrl }) };+ return {+ state: "unknown",+ ...stringFields({ checkUrl: result.checkUrl, errorCode: result.errorCode }),+ };default:return { state: "unknown" };}@@ -96,6 +100,15 @@ const RECEIPT_UNAVAILABLE_PREPARE_RESULT = {message: "Couldn't record this action, so nothing was prepared.",};+// Connecting writes a login for the account, so it needs one.+function actionRefusal(policyState, accountId) {+ return policyRefusal(policyState) ?? (accountId ? null : "signed_out");+}++function isString(value) {+ return typeof value === "string";+}+function normalizePreviewNote(note) {if (!note || typeof note.key !== "string") return null;return note.values && typeof note.values === "object"@@ -108,11 +121,7 @@ function normalizePreviewNote(note) {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;- }+ if (![verbKey, destinationLabel, accountLabel, body].every(isString)) return null;return {verbKey,destinationLabel,@@ -125,24 +134,27 @@ function normalizePreview(preview) {};}-// The payload stays in main; only the fields each status defines reach the-// renderer.+// A connector's prepare result decides whether a card appears and what it+// shows, so anything malformed fails closed, with no card and no receipt. The+// payload stays in main; only the fields each status defines reach the+// renderer, so a connector can't leak anything else (such as message text)+// through an odd result.function normalizePrepareResult(result) {switch (result?.status) {case "ready": {const preview = normalizePreview(result.preview);- return preview+ return preview && result.payload !== undefined? { 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")- : [],- };+ return isString(result.message)+ ? {+ status: "needs_clarification",+ message: result.message,+ candidates: Array.isArray(result.candidates) ? result.candidates.filter(isString) : [],+ }+ : INVALID_PREPARE_RESULT;case "failed":return {status: "failed",@@ -154,6 +166,23 @@ function normalizePrepareResult(result) {}}+function normalizeStatus(status) {+ const value = status && typeof status === "object" ? status : {};+ return {+ connected: value.connected === true,+ accountLabel: isString(value.accountLabel) ? value.accountLabel : null,+ workspaceLabel: isString(value.workspaceLabel) ? value.workspaceLabel : null,+ needsReconnect: value.needsReconnect === true,+ };+}++// A binding that can't be compared counts as no connection.+function normalizeBinding(binding) {+ if (!binding || typeof binding !== "object") return null;+ if (!isString(binding.accountId) || !Number.isInteger(binding.generation)) return null;+ return binding;+}+function sanitizeEdits(edits) {const clean = {};if (edits && typeof edits.title === "string") clean.title = edits.title;@@ -161,15 +190,39 @@ function sanitizeEdits(edits) {return clean;}+const REVOKE_TIMEOUT_MS = 5000;+const CONNECT_ERROR_CODES = new Set([+ "not_configured",+ "oauth_denied",+ "oauth_timeout",+ "oauth_state_mismatch",+ "ports_busy",+ "token_exchange_failed",+]);++// A revoke is best effort: nothing may hang on an unreachable provider.+async function withinDeadline(promise, ms) {+ let timer;+ try {+ await Promise.race([promise, new Promise((resolve) => (timer = setTimeout(resolve, ms)))]);+ } finally {+ clearTimeout(timer);+ }+}+// 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.+// anything is written or done. Connecting and disconnecting a login use+// getAccountId(), the account whose login slot they write.function createConnectorManager({connectors,pendingActions,actionLog,logger,+ getAccountId,+ credentials = null,+ onStatusChanged = () => {},randomId = () => crypto.randomBytes(16).toString("hex"),}) {const byId = new Map(connectors.map((connector) => [connector.id, connector]));@@ -180,7 +233,11 @@ function createConnectorManager({try {return write() !== false;} catch (error) {- logger.error("connector receipt write failed", { step, error: error.message }, "connectors");+ logger.error(+ "connector receipt write failed",+ { step, ...describeError(error) },+ "connectors"+ );return false;}}@@ -191,7 +248,7 @@ function createConnectorManager({try {write();} catch (error) {- logger.warn("connector receipt update failed", { error: error.message }, "connectors");+ logger.warn("connector receipt update failed", { ...describeError(error) }, "connectors");}}@@ -202,9 +259,17 @@ function createConnectorManager({}});- // 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() {+ 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 };+ }++ // Cards the renderer never answered are expired here too, so their payload+ // (message text) doesn't linger and Recent never shows them as waiting.+ // Their receipts say so rather than a later "app_quit".+ function sweepExpired() {for (const actionId of pendingActions.sweepExpired()) {record(() =>actionLog.update(actionId, { state: "expired", errorCode: "expired" }, "pending")@@ -212,47 +277,178 @@ function createConnectorManager({}}- // A lookup that throws counts as no connection, so the connector's- // exception text never reaches the renderer.- async function readBinding(connector) {+ async function statusOf(connector) {try {- return await connector.getBinding();+ return { id: connector.id, ...normalizeStatus(await connector.getStatus()) };} catch (error) {logger.warn(- "connector binding lookup failed",- { connectorId: connector.id, error: error.message },+ "connector status failed",+ { connectorId: connector.id, ...describeError(error) },+ "connectors"+ );+ return { id: connector.id, ...normalizeStatus(null) };+ }+ }++ async function currentBinding(connector) {+ try {+ return normalizeBinding(await connector.getBinding());+ } catch (error) {+ logger.warn(+ "connector binding failed",+ { connectorId: connector.id, ...describeError(error) },"connectors");return null;}}- function resolveAction(connectorId, action, kind) {+ async function status() {+ sweepExpired();+ return Promise.all([...byId.values()].map(statusOf));+ }++ // The sign-in in flight per account and connector. A new Connect replaces+ // it: a user who closed the browser tab would otherwise wait out the flow.+ const connecting = new Map();+ let statusSequence = 0;++ async function notifyStatusChanged() {+ const sequence = ++statusSequence;+ try {+ const statuses = await status();+ // A later change is already being announced; this snapshot is older.+ if (sequence === statusSequence) onStatusChanged(statuses);+ } catch (error) {+ logger.warn("connector status broadcast failed", describeError(error), "connectors");+ }+ }++ async function revokeQuietly(connector, credential) {+ try {+ await withinDeadline(connector.revoke(credential), REVOKE_TIMEOUT_MS);+ } catch (error) {+ logger.warn(+ "connector revoke failed",+ { connectorId: connector.id, ...describeError(error) },+ "connectors"+ );+ }+ }++ async function connect(connectorId, policyState) {+ const accountId = getAccountId();+ const refusal = actionRefusal(policyState, accountId);+ if (refusal) return { status: "unavailable", reason: refusal };const connector = byId.get(connectorId);- if (!connector) return { error: "unknown_connector" };- if (connector.actions[action]?.kind !== kind) return { error: "unknown_action" };- return { connector };+ if (!connector?.authorize || !credentials) {+ return { status: "unavailable", reason: "unknown_connector" };+ }+ const flowKey = `${accountId}:${connectorId}`;+ connecting.get(flowKey)?.abort();+ const controller = new AbortController();+ connecting.set(flowKey, controller);+ // The OAuth round trip can take minutes. What it returns belongs to the+ // account and slot generation that started it, or to no one.+ const startGeneration = credentials.generation(accountId, connectorId);+ try {+ let credential;+ try {+ credential = await connector.authorize({ signal: controller.signal });+ } catch (error) {+ // Replaced by a newer Connect before the provider answered: nothing+ // was issued, so nothing is saved or revoked.+ if (controller.signal.aborted) return { status: "failed", errorCode: "oauth_cancelled" };+ const summary = describeError(error);+ logger.warn("connector connect failed", { connectorId, ...summary }, "connectors");+ return {+ status: "failed",+ errorCode: CONNECT_ERROR_CODES.has(summary.errorCode)+ ? summary.errorCode+ : "connect_failed",+ };+ }+ // Replaced after the provider answered: the newer attempt is the one+ // the user wants, and nobody will use this login.+ if (controller.signal.aborted) {+ await revokeQuietly(connector, credential);+ return { status: "failed", errorCode: "oauth_cancelled" };+ }+ try {+ if (getAccountId() !== accountId) {+ throw Object.assign(new Error("account changed"), { code: "connection_changed" });+ }+ // A new login: approvals prepared under the old one must not send.+ credentials.replace(accountId, connectorId, credential, startGeneration);+ } catch (error) {+ // Nobody will use this login, so it is revoked rather than left live.+ await revokeQuietly(connector, credential);+ if (error.code === "connection_changed" || error.code === "signed_out") {+ return { status: "failed", errorCode: "connection_changed" };+ }+ // A real write failure (disk, permission, encryption), not a race.+ logger.warn(+ "connector login save failed",+ { connectorId, ...describeError(error) },+ "connectors"+ );+ return { status: "failed", errorCode: "credential_save_failed" };+ }+ invalidate(connectorId);+ await notifyStatusChanged();+ const current = await statusOf(connector);+ return {+ status: "connected",+ accountLabel: current.accountLabel,+ workspaceLabel: current.workspaceLabel,+ };+ } finally {+ if (connecting.get(flowKey) === controller) connecting.delete(flowKey);+ }}- 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 };+ // Removing access is always allowed: no policy or plan check.+ async function disconnect(connectorId) {+ const connector = byId.get(connectorId);+ if (!connector?.revoke || !credentials) {+ return { status: "unavailable", reason: "unknown_connector" };+ }+ const accountId = getAccountId();+ if (!accountId) return { status: "unavailable", reason: "signed_out" };+ const entry = credentials.read(accountId, connectorId);+ if (entry) {+ await revokeQuietly(connector, entry.credential);+ try {+ credentials.clear(accountId, connectorId, entry.generation);+ } catch (error) {+ if (error.code === "connection_changed" || error.code === "signed_out") {+ // A reconnect landed while revoking: that newer login stays.+ return { status: "failed", errorCode: "connection_changed" };}- })- );+ // A real write failure (disk, permission): the revoke above already+ // happened, so the login is dead even though the local slot wasn't+ // cleared. Never claim "disconnected" for a slot that's still there.+ logger.warn(+ "connector login clear failed",+ { connectorId, ...describeError(error) },+ "connectors"+ );+ return { status: "failed", errorCode: "disconnect_failed" };+ }+ }+ invalidate(connectorId);+ await notifyStatusChanged();+ return { status: "disconnected" };+ }++ async function disconnectAll() {+ for (const connector of byId.values()) {+ if (connector.revoke) await disconnect(connector.id);+ }}async function prepare(connectorId, action, args, { policyState, accountId }) {- expireStale();+ sweepExpired();const refusal = policyRefusal(policyState);if (refusal) return { status: "unavailable", reason: refusal };const resolved = resolveAction(connectorId, action, "approval");@@ -260,20 +456,21 @@ function createConnectorManager({if (!accountId) return RECEIPT_UNAVAILABLE_PREPARE_RESULT;const { connector } = resolved;- const binding = await readBinding(connector);+ const binding = await currentBinding(connector);if (!binding) return { status: "unavailable", reason: "not_connected" };let prepared;try {- prepared = normalizePrepareResult(await connector.prepare(action, args || {}));+ prepared = normalizePrepareResult(await connector.prepare(action, args || {}, { binding }));} catch (error) {logger.warn("connector prepare threw",- { connectorId, action, error: error.message },+ { connectorId, action, ...describeError(error) },"connectors");return { ...INVALID_PREPARE_RESULT, errorCode: "prepare_failed" };}+ if (prepared.errorCode === "reconnect_needed") void notifyStatusChanged();if (prepared.status !== "ready") return prepared;const actionId = pendingActions.create({@@ -311,7 +508,7 @@ function createConnectorManager({}async function commit(actionId, edits, { policyState, accountId }) {- expireStale();+ sweepExpired();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@@ -319,12 +516,17 @@ function createConnectorManager({if (entry.state !== "pending") return { state: "not_sent", reason: "not_pending" };const refusal = policyRefusal(policyState);+ // A policy lookup that timed out or went offline says nothing about this+ // action: leave it pending so the user can press Send again.+ if (refusal === "policy_unavailable") {+ return { state: "not_sent", reason: refusal, retryable: true };+ }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));+ const begun = pendingActions.beginCommit(actionId, await currentBinding(connector));if (!begun.ok) {if (begun.reason === "expired" || begun.reason === "connection_changed") {const state = begun.reason === "expired" ? "expired" : "cancelled";@@ -352,16 +554,19 @@ function createConnectorManager({let result;try {result = normalizeCommitResult(- await connector.commit(entry.action, entry.payload, sanitizeEdits(edits))+ await connector.commit(entry.action, entry.payload, sanitizeEdits(edits), {+ binding: entry.binding,+ }));} catch (error) {logger.warn("connector commit threw",- { connectorId: entry.connectorId, action: entry.action, error: error.message },+ { connectorId: entry.connectorId, action: entry.action, ...describeError(error) },"connectors");result = { state: "unknown" };}+ if (result.errorCode === "reconnect_needed") void notifyStatusChanged();pendingActions.finish(actionId);record(() =>@@ -373,14 +578,19 @@ function createConnectorManager({);logger.info("connector action finished",- { connectorId: entry.connectorId, action: entry.action, state: result.state },+ {+ connectorId: entry.connectorId,+ action: entry.action,+ state: result.state,+ errorCode: result.errorCode || null,+ },"connectors");return result;}function cancel(actionId, reason) {- expireStale();+ sweepExpired();const safeReason = CANCEL_REASONS.has(reason) ? reason : "cancelled_by_user";const cancelled = pendingActions.cancel(actionId);if (cancelled) {@@ -420,7 +630,7 @@ function createConnectorManager({} catch (error) {logger.warn("connector direct action threw",- { connectorId, action, error: error.message },+ { connectorId, action, ...describeError(error) },"connectors");result = uncertainDirectResult("direct_failed");@@ -448,12 +658,26 @@ function createConnectorManager({// Receipts name the people a user wrote to: only the account that took the// action sees them.function recentActions(connectorId, limit, accountId) {- expireStale();+ sweepExpired();+ if (!accountId) return [];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 };+ return {+ status,+ prepare,+ commit,+ cancel,+ runDirect,+ invalidate,+ recentActions,+ sweepExpired,+ connect,+ disconnect,+ disconnectAll,+ notifyStatusChanged,+ };}module.exports = { createConnectorManager };diff --git a/src/helpers/connectors/connectorPolicy.js b/src/helpers/connectors/connectorPolicy.jsindex 3226b59af..465506537 100644--- a/src/helpers/connectors/connectorPolicy.js+++ b/src/helpers/connectors/connectorPolicy.js@@ -16,9 +16,13 @@ function connectorPolicyState(snapshot) {}// The reason a connector call reports for a verdict other than "allowed".+// Signing out is its own refusal (connector logins outlive it); anything+// unrecognized fails closed as unavailable.function policyRefusal(policyState) {if (policyState === "allowed") return null;- return policyState === "blocked" ? "policy_blocked" : "policy_unavailable";+ if (policyState === "blocked") return "policy_blocked";+ if (policyState === "signed_out") return "signed_out";+ return "policy_unavailable";}module.exports = { connectorPolicyState, policyRefusal };diff --git a/src/helpers/connectors/credentialStore.js b/src/helpers/connectors/credentialStore.jsnew file mode 100644index 000000000..289ffe8b1--- /dev/null+++ b/src/helpers/connectors/credentialStore.js@@ -0,0 +1,93 @@+const fs = require("fs");+const path = require("path");+const crypto = require("crypto");+const { describeError } = require("./errorSummary");++const CONNECTOR_ID_PATTERN = /^[a-z][a-z0-9-]*$/;++function createCredentialStore({ dir, secretCrypto, logger, fsImpl = fs }) {+ // Generations live in memory: pending actions die with the process, so the+ // counter only has to be monotonic within one run.+ const generations = new Map();++ function fileFor(connectorId) {+ if (!CONNECTOR_ID_PATTERN.test(connectorId)) {+ throw new Error(`Invalid connector id: ${connectorId}`);+ }+ return path.join(dir, `${connectorId}.bin`);+ }++ function bump(connectorId) {+ generations.set(connectorId, (generations.get(connectorId) || 0) + 1);+ }++ function persist(connectorId, credential) {+ const file = fileFor(connectorId);+ fsImpl.mkdirSync(dir, { recursive: true, mode: 0o700 });+ // mkdir's mode only applies when it creates the directory.+ if (process.platform !== "win32") fsImpl.chmodSync(dir, 0o700);+ const text = JSON.stringify(credential);+ const data = secretCrypto.isAvailable()+ ? secretCrypto.encrypt(text)+ : Buffer.from(text, "utf8");+ // Write then rename: a crash mid-write must never leave a truncated file,+ // which would read as "not connected" and lose the login.+ const temp = `${file}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;+ try {+ fsImpl.writeFileSync(temp, data, { mode: 0o600 });+ fsImpl.renameSync(temp, file);+ } catch (error) {+ try {+ fsImpl.unlinkSync(temp);+ } catch {+ // The temp file was never created.+ }+ throw error;+ }+ }++ function read(connectorId) {+ const file = fileFor(connectorId);+ if (!fsImpl.existsSync(file)) return null;+ try {+ const buf = fsImpl.readFileSync(file);+ if (!secretCrypto.isAvailable()) return JSON.parse(buf.toString("utf8"));+ const { value, needsReencrypt } = secretCrypto.decrypt(buf);+ const credential = JSON.parse(value);+ if (needsReencrypt) persist(connectorId, credential);+ return credential;+ } catch (error) {+ logger.warn(+ "connector credential unreadable",+ { connectorId, ...describeError(error) },+ "connectors"+ );+ return null;+ }+ }++ // A new login: pending approvals prepared under the old one must not send.+ function replace(connectorId, credential) {+ persist(connectorId, credential);+ bump(connectorId);+ }++ // A token refresh for the same login keeps pending approvals valid.+ function save(connectorId, credential) {+ persist(connectorId, credential);+ }++ function clear(connectorId) {+ const file = fileFor(connectorId);+ if (fsImpl.existsSync(file)) fsImpl.unlinkSync(file);+ bump(connectorId);+ }++ function getGeneration(connectorId) {+ return generations.get(connectorId) || 0;+ }++ return { read, replace, save, clear, getGeneration };+}++module.exports = { createCredentialStore };diff --git a/src/helpers/connectors/deliveryClassifier.js b/src/helpers/connectors/deliveryClassifier.jsnew file mode 100644index 000000000..7669dcd1b--- /dev/null+++ b/src/helpers/connectors/deliveryClassifier.js@@ -0,0 +1,43 @@+// Codes that mean the request never left this machine. Everything else+// (reset, timeout, abort, unknown) may have reached the provider, so it is+// reported as "unknown" rather than risking a duplicate on retry.+const PRE_CONNECT_CODES = new Set([+ "ENOTFOUND",+ "EAI_AGAIN",+ "ECONNREFUSED",+ "ENETUNREACH",+ "EHOSTUNREACH",+ "ERR_NAME_NOT_RESOLVED",+ "ERR_NAME_RESOLUTION_FAILED",+ "ERR_INTERNET_DISCONNECTED",+ "ERR_CONNECTION_REFUSED",+ "ERR_ADDRESS_UNREACHABLE",+]);++function errorCode(error) {+ if (!error) return null;+ if (typeof error.code === "string") return error.code;+ if (typeof error.cause?.code === "string") return error.cause.code;+ const match = /net::(ERR_[A-Z_]+)/.exec(String(error.message || ""));+ return match ? match[1] : null;+}++function classifyTransportError(error) {+ return PRE_CONNECT_CODES.has(errorCode(error)) ? "failed" : "unknown";+}++// A 4xx is the provider refusing the request. A 5xx (or anything unexpected)+// may come after the provider acted, so it must not be reported as not sent.+function classifyHttpStatus(status) {+ if (status >= 200 && status < 300) return "ok";+ if (status >= 400 && status < 500) return "failed";+ return "unknown";+}++// Provider error bodies (e.g. Slack's ok:false) prove nothing unless the+// provider documents the code as a rejection that happens before acting.+function classifyProviderError(code, definiteRejections) {+ return typeof code === "string" && definiteRejections.has(code) ? "failed" : "unknown";+}++module.exports = { classifyTransportError, classifyHttpStatus, classifyProviderError };diff --git a/src/helpers/connectors/errorSummary.js b/src/helpers/connectors/errorSummary.jsnew file mode 100644index 000000000..24ab74300--- /dev/null+++ b/src/helpers/connectors/errorSummary.js@@ -0,0 +1,11 @@+// Raw error messages can carry URLs, tokens or response text (network errors+// quote the request URL), so connector logs record only these two fields.+function describeError(error) {+ let errorCode = null;+ if (typeof error?.code === "string") errorCode = error.code;+ else if (typeof error?.cause?.code === "string") errorCode = error.cause.code;+ else if (typeof error?.redirectCode === "string") errorCode = error.redirectCode;+ return { errorName: typeof error?.name === "string" ? error.name : "Error", errorCode };+}++module.exports = { describeError };diff --git a/src/helpers/connectors/oauthResultPage.js b/src/helpers/connectors/oauthResultPage.jsnew file mode 100644index 000000000..aebddda64--- /dev/null+++ b/src/helpers/connectors/oauthResultPage.js@@ -0,0 +1,17 @@+const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };+const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ESCAPES[char]);++// Shown in the browser tab after a connector's OAuth redirect. The loopback+// server serves it, so it works without openwhispr.com.+function renderOAuthResultPage({ ok, title, body }) {+ return `<!doctype html>+<html><head><meta charset="utf-8"><title>${escapeHtml(title)}</title>+<style>+body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#f7f7f8;color:#1a1a1a}+main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;color:#555}+@media (prefers-color-scheme:dark){body{background:#161618;color:#f2f2f2}p{color:#aaa}}+</style></head>+<body><main dir="auto" data-ok="${ok ? "true" : "false"}"><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p></main></body></html>`;+}++module.exports = { renderOAuthResultPage };diff --git a/src/helpers/connectors/pendingActions.js b/src/helpers/connectors/pendingActions.jsindex dc3505737..6e17e45e8 100644--- a/src/helpers/connectors/pendingActions.js+++ b/src/helpers/connectors/pendingActions.js@@ -3,11 +3,13 @@ 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.+// another OpenWhispr account, another provider login, or a reconnect+// (generation bump) must not inherit it.function bindingsMatch(a, b) {return Boolean(a &&b &&+ (a.ownerAccountId ?? null) === (b.ownerAccountId ?? null) &&a.accountId === b.accountId &&(a.workspaceId ?? null) === (b.workspaceId ?? null) &&a.generation === b.generation@@ -89,7 +91,9 @@ function createPendingActions({return removed;}- // Committing actions are left alone: their real outcome is still coming.+ // Pending actions whose card outlived the TTL without the renderer ever+ // answering (window closed, renderer crashed). Committing ones are never+ // touched: their real outcome must still be recorded.function sweepExpired() {const expired = [];for (const [actionId, entry] of actions) {diff --git a/src/helpers/connectors/slackApi.js b/src/helpers/connectors/slackApi.jsnew file mode 100644index 000000000..c27489f80--- /dev/null+++ b/src/helpers/connectors/slackApi.js@@ -0,0 +1,137 @@+const {+ classifyTransportError,+ classifyHttpStatus,+ classifyProviderError,+} = require("./deliveryClassifier");+const { describeError } = require("./errorSummary");++const SLACK_API_BASE = "https://slack.com/api/";+const REQUEST_TIMEOUT_MS = 15000;+const MAX_RETRY_AFTER_MS = 5000;++// chat.postMessage error codes Slack documents as refusals made before+// anything is posted. The first eight are the spec's list; the rest are auth,+// channel-state and argument refusals from the same table. Every other+// ok:false code (internal_error, fatal_error, codes added later) may follow a+// partial success, so it stays "unknown".+const SLACK_PRE_SEND_REJECTIONS = new Set([+ "channel_not_found",+ "not_in_channel",+ "invalid_auth",+ "not_authed",+ "missing_scope",+ "no_text",+ "msg_too_long",+ "ratelimited",+ "token_expired",+ "token_revoked",+ "account_inactive",+ "is_archived",+ "restricted_action",+ "restricted_action_read_only_channel",+ "ekm_access_denied",+ "markdown_text_conflict",+ "invalid_arguments",+ "rate_limited",+]);++function retryAfterMs(header) {+ if (header === null || header === undefined || header === "") return null;+ const seconds = Number(header);+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;+}++function transportCode(error) {+ const { errorName, errorCode } = describeError(error);+ if (errorCode) return errorCode;+ return errorName === "TimeoutError" ? "timeout" : "network_error";+}++function createSlackApi({+ fetchImpl,+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+ timeoutMs = REQUEST_TIMEOUT_MS,+}) {+ async function once(method, params, token) {+ // Slack warns "superfluous_charset" when a form body names a charset.+ const headers = { "Content-Type": "application/x-www-form-urlencoded" };+ if (token) headers.Authorization = `Bearer ${token}`;+ let response;+ try {+ response = await fetchImpl(`${SLACK_API_BASE}${method}`, {+ method: "POST",+ headers,+ body: new URLSearchParams(params).toString(),+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (error) {+ return {+ ok: false,+ source: "network",+ outcome: classifyTransportError(error),+ errorCode: transportCode(error),+ };+ }+ // A 429 means Slack did not act.+ if (response.status === 429) {+ return {+ ok: false,+ source: "http",+ status: 429,+ outcome: "failed",+ errorCode: "rate_limited",+ retryAfterMs: retryAfterMs(response.headers.get("retry-after")),+ };+ }+ const httpOutcome = classifyHttpStatus(response.status);+ if (httpOutcome !== "ok") {+ return {+ ok: false,+ source: "http",+ status: response.status,+ outcome: httpOutcome,+ errorCode: `http_${response.status}`,+ };+ }+ let data = null;+ try {+ data = await response.json();+ } catch {+ data = null;+ }+ if (!data || typeof data !== "object") {+ return {+ ok: false,+ source: "http",+ status: response.status,+ outcome: "unknown",+ errorCode: "bad_response",+ };+ }+ if (data.ok === true) return { ok: true, data };+ const code = typeof data.error === "string" ? data.error : "unknown_error";+ return {+ ok: false,+ source: "slack",+ status: response.status,+ outcome: classifyProviderError(code, SLACK_PRE_SEND_REJECTIONS),+ errorCode: code,+ };+ }++ // One retry, only for a 429 that asks for 5 s or less: Slack refused the+ // first request, so repeating it cannot post twice.+ async function call(method, params = {}, { token } = {}) {+ const first = await once(method, params, token);+ const retryAfter = first.ok ? null : first.retryAfterMs;+ if (typeof retryAfter === "number" && retryAfter <= MAX_RETRY_AFTER_MS) {+ await sleep(retryAfter);+ return once(method, params, token);+ }+ return first;+ }++ return { call };+}++module.exports = { createSlackApi, SLACK_PRE_SEND_REJECTIONS, MAX_RETRY_AFTER_MS };diff --git a/src/helpers/connectors/slackAuth.js b/src/helpers/connectors/slackAuth.jsnew file mode 100644index 000000000..70b07692c--- /dev/null+++ b/src/helpers/connectors/slackAuth.js@@ -0,0 +1,272 @@+const { describeError } = require("./errorSummary");++const SLACK_AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize";+const SLACK_USER_SCOPES = [+ "chat:write",+ "channels:read",+ "groups:read",+ "im:write",+ "users:read",+ "users:read.email",+];+const EXPIRY_SKEW_MS = 60 * 1000;+// PKCE apps get refresh tokens that expire 30 days after they are issued.+const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;+// Slack only distributes apps whose redirect URLs are HTTPS, so it redirects+// to the openwhispr.com relay, which forwards to this loopback server by the+// port in state (spec §7.2). A first Slack sign-in (workspace choice, 2FA)+// can outlast the calendars' 120 s, so the flow waits 5 minutes.+const SLACK_RELAY_REDIRECT_URI = "https://openwhispr.com/auth/slack/callback";+const SLACK_LOOPBACK = { ports: [0], callbackPath: "/slack/callback", timeoutMs: 5 * 60 * 1000 };++// SLACK_OAUTH_REDIRECT_URI points a dev build at a website preview of the+// relay. Only an https: URL is accepted; anything else uses the real relay.+function slackRedirectUri(env) {+ const override = env?.SLACK_OAUTH_REDIRECT_URI;+ if (typeof override !== "string" || !override) return SLACK_RELAY_REDIRECT_URI;+ try {+ return new URL(override).protocol === "https:" ? override : SLACK_RELAY_REDIRECT_URI;+ } catch {+ return SLACK_RELAY_REDIRECT_URI;+ }+}+// oauth.v2.access errors that mean the login itself is gone. Rate limits,+// service_unavailable, internal_error and every other error keep the login:+// the next attempt may work, and a false "reconnect" disconnects the user.+const OAUTH_LOGIN_GONE = new Set([+ "invalid_refresh_token",+ "token_revoked",+ "token_expired",+ "invalid_auth",+ "account_inactive",+ "invalid_client_id",+ "access_denied",+ "team_access_not_granted",+ "not_allowed_token_type",+ "pkce_not_allowed",+]);++function codedError(code) {+ return Object.assign(new Error(code), { code });+}++// The code exchange nests the user token under authed_user; a refresh+// returns it at the top level (both recorded in plan Task 3).+function parseUserTokens(data, now) {+ const source = typeof data?.authed_user?.access_token === "string" ? data.authed_user : data;+ if (typeof source?.access_token !== "string") return null;+ if (source.token_type !== undefined && source.token_type !== "user") return null;+ return {+ accessToken: source.access_token,+ refreshToken: typeof source.refresh_token === "string" ? source.refresh_token : null,+ expiresAt: Number.isFinite(source.expires_in) ? now + source.expires_in * 1000 : null,+ };+}++// Only the login a pending action was approved under may act for it.+function sameLogin(entry, binding) {+ return Boolean(+ entry &&+ binding &&+ entry.generation === binding.generation &&+ entry.credential.userId === binding.accountId &&+ entry.credential.teamId === binding.workspaceId+ );+}++function createSlackAuth({+ api,+ credentials,+ getClientId,+ runOAuthLoopbackFlow,+ OAuthFlowError,+ loopback = SLACK_LOOPBACK,+ redirectUri = slackRedirectUri(process.env),+ renderResultPage = null,+ // Optional: told about a credential write that failed for a reason other+ // than a reconnect/disconnect race (disk, permission, encryption errors+ // from credentialStore) via logger.warn(message, describeError(error),+ // area). Never a token or a raw error.message.+ logger = null,+ now = Date.now,+}) {+ const refreshes = new Map();++ // `signal` gives the sign-in up when a newer Connect replaces it.+ function authorize({ signal } = {}) {+ const clientId = getClientId();+ // Fail before opening a browser on a client_id-less URL.+ if (!clientId) return Promise.reject(codedError("not_configured"));+ return runOAuthLoopbackFlow({+ errorParam: "slack_error",+ ...loopback,+ publicRedirectUri: redirectUri,+ renderResultPage,+ signal,+ buildAuthUrl: (redirectUri, state, codeChallenge) => {+ const params = new URLSearchParams({+ client_id: clientId,+ user_scope: SLACK_USER_SCOPES.join(","),+ redirect_uri: redirectUri,+ state,+ code_challenge: codeChallenge,+ code_challenge_method: "S256",+ });+ return `${SLACK_AUTHORIZE_URL}?${params.toString()}`;+ },+ handleCallback: async (code, redirectUri, codeVerifier) => {+ const exchanged = await api.call("oauth.v2.access", {+ client_id: clientId,+ code,+ code_verifier: codeVerifier,+ redirect_uri: redirectUri,+ });+ const tokens = exchanged.ok ? parseUserTokens(exchanged.data, now()) : null;+ if (!tokens)+ throw new OAuthFlowError("token_exchange_failed", "slack_token_exchange_failed");+ const identity = await api.call("auth.test", {}, { token: tokens.accessToken });+ if (!identity.ok)+ throw new OAuthFlowError("token_exchange_failed", "slack_identity_failed");+ return {+ ...tokens,+ refreshIssuedAt: tokens.refreshToken ? now() : null,+ userId: identity.data.user_id,+ userName: identity.data.user,+ teamId: identity.data.team_id,+ teamName: identity.data.team,+ teamUrl: identity.data.url,+ needsReconnect: false,+ };+ },+ });+ }++ // Flags the login the binding names, and only it, as needing a reconnect:+ // Slack said that login is gone. A reconnect or disconnect that landed+ // first wins, and nothing is written to it.+ function markReconnect(binding) {+ const entry = credentials.read(binding?.ownerAccountId ?? null, "slack");+ if (!sameLogin(entry, binding)) return { ok: false, errorCode: "connection_changed" };+ try {+ credentials.save(+ binding.ownerAccountId,+ "slack",+ { ...entry.credential, needsReconnect: true },+ binding.generation+ );+ } catch (error) {+ if (error.code === "connection_changed" || error.code === "signed_out") {+ return { ok: false, errorCode: "connection_changed" };+ }+ // A real write failure (disk, permission, encryption). Slack's answer+ // still stands: the login is gone, though the flag wasn't recorded.+ logger?.warn("slack reconnect flag save failed", describeError(error), "connectors");+ }+ return { ok: false, errorCode: "reconnect_needed" };+ }++ function callRefresh(refreshToken) {+ return api.call("oauth.v2.access", {+ client_id: getClientId() ?? "",+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ });+ }++ async function refresh(binding, credential) {+ if (!credential.refreshToken) return markReconnect(binding);+ let result = await callRefresh(credential.refreshToken);+ // No clear answer: Slack may have rotated the token anyway. The used+ // refresh token still works for a short grace period, so ask once more.+ if (!result.ok && result.outcome === "unknown" && !OAUTH_LOGIN_GONE.has(result.errorCode)) {+ result = await callRefresh(credential.refreshToken);+ }+ if (!result.ok) {+ // A reconnect or disconnect may have landed while the network call was+ // in flight. That always wins over the login this refresh started+ // with: report connection_changed and write nothing for either the+ // login-gone or the transient case.+ if (!sameLogin(credentials.read(binding.ownerAccountId, "slack"), binding)) {+ return { ok: false, errorCode: "connection_changed" };+ }+ return OAUTH_LOGIN_GONE.has(result.errorCode)+ ? markReconnect(binding)+ : { ok: false, errorCode: result.errorCode };+ }+ const tokens = parseUserTokens(result.data, now());+ if (!tokens) return { ok: false, errorCode: "bad_response" };+ const next = {+ ...credential,+ ...tokens,+ refreshToken: tokens.refreshToken ?? credential.refreshToken,+ refreshIssuedAt: tokens.refreshToken ? now() : credential.refreshIssuedAt,+ needsReconnect: false,+ };+ // Saved before use, and only into the slot and generation this refresh+ // started from: a reconnect or disconnect that landed meanwhile wins.+ try {+ credentials.save(binding.ownerAccountId, "slack", next, binding.generation);+ } catch (error) {+ if (error.code === "connection_changed" || error.code === "signed_out") {+ return { ok: false, errorCode: "connection_changed" };+ }+ // A real write failure (disk, permission, encryption): the rotated+ // token is lost, so this is worth a log line, never the token itself.+ logger?.warn("slack token save failed", describeError(error), "connectors");+ return { ok: false, errorCode: "credential_save_failed" };+ }+ return { ok: true, token: next.accessToken, credential: next };+ }++ async function getAccessToken(binding, { forceRefresh = false } = {}) {+ const entry = credentials.read(binding?.ownerAccountId ?? null, "slack");+ if (!sameLogin(entry, binding)) return { ok: false, errorCode: "connection_changed" };+ const { credential } = entry;+ if (credential.needsReconnect) return { ok: false, errorCode: "reconnect_needed" };+ const fresh = !credential.expiresAt || credential.expiresAt - EXPIRY_SKEW_MS > now();+ if (fresh && !forceRefresh) return { ok: true, token: credential.accessToken, credential };+ // Refresh tokens are single-use, so concurrent callers for one login+ // share one refresh.+ const key = `${binding.ownerAccountId}:${binding.generation}`;+ let pending = refreshes.get(key);+ if (!pending) {+ pending = refresh(binding, credential).finally(() => refreshes.delete(key));+ refreshes.set(key, pending);+ }+ return pending;+ }++ // With token rotation, auth.revoke revokes only the token it is given, so+ // the refresh token and the access token are revoked separately. Best+ // effort: the local login is deleted whatever Slack answers.+ async function revoke(credential) {+ for (const token of [credential?.refreshToken, credential?.accessToken]) {+ if (typeof token === "string" && token) await api.call("auth.revoke", {}, { token });+ }+ }++ function statusOf(credential) {+ const refreshExpired = Boolean(+ credential.refreshToken &&+ credential.refreshIssuedAt &&+ now() - credential.refreshIssuedAt > REFRESH_TOKEN_TTL_MS+ );+ return {+ connected: true,+ accountLabel: credential.userName ?? null,+ workspaceLabel: credential.teamName ?? null,+ needsReconnect: Boolean(credential.needsReconnect) || refreshExpired,+ };+ }++ return { authorize, getAccessToken, markReconnect, revoke, statusOf };+}++module.exports = {+ createSlackAuth,+ SLACK_USER_SCOPES,+ SLACK_LOOPBACK,+ SLACK_RELAY_REDIRECT_URI,+ slackRedirectUri,+ OAUTH_LOGIN_GONE,+};diff --git a/src/helpers/connectors/slackConnector.js b/src/helpers/connectors/slackConnector.jsnew file mode 100644index 000000000..85a05cef2--- /dev/null+++ b/src/helpers/connectors/slackConnector.js@@ -0,0 +1,351 @@+const { resolveTarget } = require("./targetResolution");+const { isValidEmailAddress } = require("./emailCompose");++// markdown_text's documented limit, applied to what Slack receives.+const SLACK_MESSAGE_LIMIT = 12000;+// Slack refused the token, so it did nothing: refresh and repeat once. A+// revoked login fails that refresh, which flags it for a reconnect.+const RETRY_AFTER_REFRESH = new Set([+ "token_expired",+ "invalid_auth",+ "http_401",+ "token_revoked",+ "account_inactive",+ "not_authed",+]);+// Plan Task 3: whether markdown_text turns <!here>, <@U…> and <url> into+// mentions and links.+const SLACK_ESCAPE_SPECIALS = true;+const TOO_LARGE_FOR_NAMES =+ "This Slack workspace is too large to look people up by name. Ask the user for the person's email address, or the exact #channel name.";++// Escaping &, < and > makes a message post exactly as the card showed it:+// no channel-wide mention or link the user didn't see.+function escapeSpecials(text) {+ return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+}++// What Slack receives in the message field. Escaping lengthens the text, so+// the limit is checked on this, not on what the user typed.+function formatMessage(text) {+ return SLACK_ESCAPE_SPECIALS ? escapeSpecials(text) : text;+}++function messageParams(channel, text) {+ return { channel, markdown_text: formatMessage(text) };+}++// chat.postMessage returns no permalink; this is Slack's permalink format.+function messageUrl(teamUrl, channel, ts) {+ if (typeof teamUrl !== "string" || typeof ts !== "string") return undefined;+ return `${teamUrl.replace(/\/?$/, "/")}archives/${channel}/p${ts.replace(".", "")}`;+}++function failureMessage(errorCode, label = "", fallback = "Slack didn't accept the message.") {+ switch (errorCode) {+ case "not_in_channel":+ return `You're not a member of ${label}.`;+ case "channel_not_found":+ return `${label} couldn't be found in Slack anymore.`;+ case "is_archived":+ return `${label} is archived.`;+ case "reconnect_needed":+ case "token_revoked":+ case "invalid_auth":+ case "account_inactive":+ case "not_authed":+ return "Slack needs to be reconnected in Settings.";+ case "connection_changed":+ return "The Slack connection changed before sending, so nothing was sent.";+ case "rate_limited":+ case "ratelimited":+ return "Slack is busy. Try again shortly.";+ case "missing_scope":+ return "OpenWhispr doesn't have permission to post there. Reconnect Slack in Settings.";+ case "msg_too_long":+ return "The message is too long for Slack (12,000 characters at most, once formatted).";+ case "no_text":+ return "The message is empty.";+ default:+ return fallback;+ }+}++function textProblem(text) {+ if (typeof text !== "string" || !text.trim()) return "no_text";+ if (formatMessage(text).length > SLACK_MESSAGE_LIMIT) return "msg_too_long";+ return null;+}++function parseDestination(raw) {+ const value = raw.trim();+ if (value.startsWith("#")) return { kind: "channel", query: value.slice(1) };+ if (isValidEmailAddress(value)) return { kind: "email", query: value };+ if (value.startsWith("@")) return { kind: "person", query: value.slice(1) };+ return { kind: "any", query: value };+}++function clarify(message, candidates = []) {+ return {+ status: "needs_clarification",+ message,+ candidates: candidates.map((candidate) => candidate.hint ?? candidate.label),+ };+}++function prepareFailed(errorCode, message) {+ return { status: "failed", errorCode, message };+}++function createSlackConnector({ api, auth, directory, credentials }) {+ async function findTarget(parsed, token, cacheKey) {+ if (parsed.kind === "email") {+ const found = await directory.personByEmail(token, parsed.query);+ if (!found.ok) return { error: found.errorCode };+ if (found.candidate) return { candidate: found.candidate };+ return {+ clarify: clarify(+ `No one in this Slack workspace uses ${parsed.query}. Ask the user who they meant.`+ ),+ };+ }+ const lists = (+ await Promise.all([+ parsed.kind === "person" ? null : directory.channels(token, cacheKey),+ parsed.kind === "channel" ? null : directory.people(token, cacheKey),+ ])+ ).filter(Boolean);+ const failure = lists.find((list) => !list.ok);+ if (failure) return { error: failure.errorCode };+ const candidates = lists.flatMap((list) => list.items);++ // A name is only unique if every candidate was seen. When a list stopped+ // at the page cap, only an exact channel name (unique in a workspace)+ // still identifies something; a person needs an email address.+ if (lists.some((list) => list.truncated)) {+ if (parsed.kind !== "channel") return { clarify: clarify(TOO_LARGE_FOR_NAMES) };+ const exact = resolveTarget(parsed.query, candidates, { exactOnly: true });+ if (exact.status === "match") return { candidate: exact.candidate };+ return {+ clarify: clarify(+ `Couldn't find a channel named exactly #${parsed.query} that the user is in. Ask for the exact #channel name.`+ ),+ };+ }++ const resolved = resolveTarget(parsed.query, candidates);+ if (resolved.status === "match") return { candidate: resolved.candidate };+ if (resolved.status === "ambiguous") {+ return {+ clarify: clarify(+ `More than one match for "${parsed.query}". Ask the user which one they meant.`,+ resolved.candidates+ ),+ };+ }+ const where =+ parsed.kind === "channel"+ ? `a channel called #${parsed.query} that the user is in`+ : `"${parsed.query}"`;+ return { clarify: clarify(`Couldn't find ${where} in Slack. Ask the user where to send it.`) };+ }++ // Slack refusing a token it just issued means the login itself is gone.+ function refusedAgain(binding) {+ return { ok: false, outcome: "failed", errorCode: auth.markReconnect(binding).errorCode };+ }++ // A write Slack refused for its token did nothing, so it is the one write+ // that may be repeated: once, after refreshing the login the action is+ // bound to. Never whichever login is current.+ async function writeWithRefresh(method, params, binding, access) {+ const first = await api.call(method, params, { token: access.token });+ if (first.ok || !RETRY_AFTER_REFRESH.has(first.errorCode)) return { result: first, access };+ const refreshed = await auth.getAccessToken(binding, { forceRefresh: true });+ if (!refreshed.ok) {+ return { result: { ok: false, outcome: "failed", errorCode: refreshed.errorCode }, access };+ }+ const second = await api.call(method, params, { token: refreshed.token });+ if (!second.ok && RETRY_AFTER_REFRESH.has(second.errorCode)) {+ return { result: refusedAgain(binding), access: refreshed };+ }+ return { result: second, access: refreshed };+ }++ // Lookups only read, but a refused token gets the same treatment: one+ // more try after refreshing the bound login, then a reconnect.+ async function findTargetWithRefresh(parsed, binding, access, cacheKey) {+ const first = await findTarget(parsed, access.token, cacheKey);+ if (!RETRY_AFTER_REFRESH.has(first.error)) return first;+ const refreshed = await auth.getAccessToken(binding, { forceRefresh: true });+ if (!refreshed.ok) return { error: refreshed.errorCode };+ const second = await findTarget(parsed, refreshed.token, cacheKey);+ if (!RETRY_AFTER_REFRESH.has(second.error)) return second;+ return { error: refusedAgain(binding).errorCode };+ }++ return {+ id: "slack",+ actions: { send_message: { kind: "approval" } },++ async getStatus() {+ const entry = credentials.read(credentials.activeAccountId(), "slack");+ return entry+ ? auth.statusOf(entry.credential)+ : { connected: false, accountLabel: null, workspaceLabel: null, needsReconnect: false };+ },++ async getBinding() {+ const ownerAccountId = credentials.activeAccountId();+ const entry = credentials.read(ownerAccountId, "slack");+ if (!entry) return null;+ return {+ ownerAccountId,+ accountId: entry.credential.userId,+ workspaceId: entry.credential.teamId,+ generation: entry.generation,+ };+ },++ async prepare(action, args, { binding } = {}) {+ if (action !== "send_message")+ return prepareFailed("unknown_action", "Unknown Slack action.");+ const text = typeof args.text === "string" ? args.text : "";+ const problem = textProblem(text);+ if (problem) return prepareFailed(problem, failureMessage(problem));+ const destination = typeof args.destination === "string" ? args.destination.trim() : "";+ if (!destination)+ return clarify("Ask the user which Slack channel or person to send this to.");++ const access = await auth.getAccessToken(binding);+ if (!access.ok) {+ return prepareFailed(+ access.errorCode,+ failureMessage(access.errorCode, "", "Couldn't reach Slack. Try again.")+ );+ }+ const { credential } = access;+ const cacheKey = `${binding.ownerAccountId}:${credential.teamId}:${credential.userId}:${binding.generation}`;+ const found = await findTargetWithRefresh(+ parseDestination(destination),+ binding,+ access,+ cacheKey+ );+ if (found.clarify) return found.clarify;+ if (found.error) {+ return prepareFailed(+ found.error,+ failureMessage(found.error, "", "Couldn't reach Slack to look that up. Try again.")+ );+ }++ const target = {+ kind: found.candidate.kind,+ id: found.candidate.id,+ label: found.candidate.label,+ };+ return {+ status: "ready",+ payload: { target, text },+ preview: {+ verbKey: "slackPost",+ destinationLabel: target.label,+ accountLabel: credential.userName,+ workspaceLabel: credential.teamName,+ body: text,+ },+ };+ },++ async commit(action, payload, edits, { binding } = {}) {+ if (action !== "send_message") {+ return { state: "failed", errorCode: "unknown_action", message: "Unknown Slack action." };+ }+ const { target } = payload;+ const text = typeof edits.body === "string" ? edits.body : payload.text;+ // Checked before anything reaches Slack, a DM open included.+ const problem = textProblem(text);+ if (problem) return { state: "failed", errorCode: problem, message: failureMessage(problem) };++ const access = await auth.getAccessToken(binding);+ if (!access.ok) {+ return {+ state: "failed",+ errorCode: access.errorCode,+ message: failureMessage(+ access.errorCode,+ target.label,+ "Couldn't reach Slack. Nothing was sent."+ ),+ };+ }++ let channel = target.id;+ let current = access;+ if (target.kind === "user") {+ // Opening a DM creates it in Slack, so it happens only after the user+ // pressed Send (spec §5 invariant 2).+ const opened = await writeWithRefresh(+ "conversations.open",+ { users: target.id },+ binding,+ current+ );+ current = opened.access;+ const channelId = opened.result.ok ? opened.result.data?.channel?.id : null;+ // Whatever happened to the DM, the message itself was never posted.+ if (!channelId) {+ const errorCode = opened.result.ok ? "bad_response" : opened.result.errorCode;+ return {+ state: "failed",+ errorCode,+ message: failureMessage(+ errorCode,+ target.label,+ `Couldn't open a conversation with ${target.label}. Nothing was sent.`+ ),+ };+ }+ channel = channelId;+ }++ const posted = await writeWithRefresh(+ "chat.postMessage",+ messageParams(channel, text),+ binding,+ current+ );+ const { result } = posted;+ if (result.ok) {+ return {+ state: "sent",+ url: messageUrl(posted.access.credential.teamUrl, channel, result.data.ts),+ };+ }+ if (result.outcome === "failed") {+ return {+ state: "failed",+ errorCode: result.errorCode,+ message: failureMessage(result.errorCode, target.label),+ };+ }+ return {+ state: "unknown",+ errorCode: result.errorCode,+ checkUrl: `https://app.slack.com/client/${posted.access.credential.teamId}/${channel}`,+ };+ },++ authorize: (options) => auth.authorize(options),+ revoke: (credential) => auth.revoke(credential),+ };+}++module.exports = {+ createSlackConnector,+ escapeSpecials,+ formatMessage,+ SLACK_MESSAGE_LIMIT,+ SLACK_ESCAPE_SPECIALS,+};diff --git a/src/helpers/connectors/slackDirectory.js b/src/helpers/connectors/slackDirectory.jsnew file mode 100644index 000000000..44645a1b4--- /dev/null+++ b/src/helpers/connectors/slackDirectory.js@@ -0,0 +1,96 @@+const CACHE_TTL_MS = 10 * 60 * 1000;+const PAGE_LIMIT = 200;+const MAX_PAGES = 10;++function channelCandidate(channel) {+ return { id: channel.id, kind: "channel", label: `#${channel.name}`, names: [channel.name] };+}++function isPerson(user) {+ return (+ Boolean(user) && !user.deleted && !user.is_bot && !user.is_app_user && user.id !== "USLACKBOT"+ );+}++function personCandidate(user) {+ const profile = user.profile ?? {};+ const realName = profile.real_name || user.real_name || "";+ const displayName = profile.display_name || "";+ const label = realName || displayName || user.name;+ return {+ id: user.id,+ kind: "user",+ label,+ hint: `${label} (@${displayName || user.name})`,+ names: [...new Set([displayName, realName, user.name].filter(Boolean))],+ };+}++function createSlackDirectory({ api, now = Date.now }) {+ const cache = new Map();++ // Stops at MAX_PAGES and says so: callers must not treat a cut-off list+ // as every channel or person there is.+ async function listAll(method, params, token, itemsOf) {+ const items = [];+ let cursor = "";+ for (let page = 0; page < MAX_PAGES; page += 1) {+ const result = await api.call(+ method,+ { ...params, limit: String(PAGE_LIMIT), ...(cursor ? { cursor } : {}) },+ { token }+ );+ if (!result.ok) return { ok: false, errorCode: result.errorCode };+ items.push(...itemsOf(result.data));+ cursor = result.data.response_metadata?.next_cursor || "";+ if (!cursor) return { ok: true, items, truncated: false };+ }+ return { ok: true, items, truncated: true };+ }++ async function cached(kind, cacheKey, load) {+ const key = `${kind}:${cacheKey}`;+ const hit = cache.get(key);+ if (hit && now() - hit.at < CACHE_TTL_MS) return hit.value;+ const value = await load();+ if (value.ok) cache.set(key, { at: now(), value });+ return value;+ }++ // Only channels the user is in: a user token can't post anywhere else.+ function channels(token, cacheKey) {+ return cached("channels", cacheKey, () =>+ listAll(+ "users.conversations",+ { types: "public_channel,private_channel", exclude_archived: "true" },+ token,+ (data) =>+ (data.channels ?? []).filter((channel) => !channel.is_archived).map(channelCandidate)+ )+ );+ }++ function people(token, cacheKey) {+ return cached("people", cacheKey, () =>+ listAll("users.list", {}, token, (data) =>+ (data.members ?? []).filter(isPerson).map(personCandidate)+ )+ );+ }++ async function personByEmail(token, email) {+ const result = await api.call("users.lookupByEmail", { email }, { token });+ if (result.ok) {+ return {+ ok: true,+ candidate: isPerson(result.data.user) ? personCandidate(result.data.user) : null,+ };+ }+ if (result.errorCode === "users_not_found") return { ok: true, candidate: null };+ return { ok: false, errorCode: result.errorCode };+ }++ return { channels, people, personByEmail };+}++module.exports = { createSlackDirectory };diff --git a/src/helpers/connectors/targetResolution.js b/src/helpers/connectors/targetResolution.jsnew file mode 100644index 000000000..a001f6888--- /dev/null+++ b/src/helpers/connectors/targetResolution.js@@ -0,0 +1,49 @@+const MAX_CANDIDATES = 5;++// Case, accents, spaces and punctuation don't tell apart the names people+// say aloud: "Eng Backend", "eng-backend" and "eng_backend" are one name.+function normalizeName(value) {+ return String(value ?? "")+ .normalize("NFKD")+ .replace(/\p{M}/gu, "")+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]/gu, "");+}++function distinctById(candidates) {+ const byId = new Map();+ for (const candidate of candidates) {+ if (!byId.has(candidate.id)) byId.set(candidate.id, candidate);+ }+ return [...byId.values()];+}++// Stages run in order and the first stage with any match decides: an exact+// name never loses to a longer one that merely starts the same way, and two+// matches at the same stage are always ambiguous, never guessed. exactOnly+// is for incomplete candidate lists, where a looser match elsewhere could+// have been missed.+function resolveTarget(query, candidates, { exactOnly = false } = {}) {+ const raw = String(query ?? "").trim();+ const normalized = normalizeName(raw);+ if (!normalized) return { status: "none" };++ const stages = [+ (name) => name === raw,+ (name) => normalizeName(name) === normalized,+ (name) => normalizeName(name).startsWith(normalized),+ ];+ for (const matches of exactOnly ? stages.slice(0, 1) : stages) {+ const found = distinctById(+ candidates.filter((candidate) =>+ candidate.names.some((name) => Boolean(name) && matches(name))+ )+ );+ if (found.length === 1) return { status: "match", candidate: found[0] };+ if (found.length > 1)+ return { status: "ambiguous", candidates: found.slice(0, MAX_CANDIDATES) };+ }+ return { status: "none" };+}++module.exports = { resolveTarget, normalizeName, MAX_CANDIDATES };diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 2cd130092..e3db314f0 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -519,13 +519,19 @@ class DatabaseManager {updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`);+ this.db.exec(+ "CREATE INDEX IF NOT EXISTS idx_connector_actions_connector ON connector_actions(connector, created_at)"+ );+ // Destination labels name channels and people in someone's workspace,+ // so a receipt belongs to the OpenWhispr account that made it. Tables+ // created before the column existed gain it here.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)"+ "CREATE INDEX IF NOT EXISTS idx_connector_actions_account ON connector_actions(account_id, connector, created_at)");try {this.db.exec("ALTER TABLE agent_conversations ADD COLUMN cloud_id TEXT");@@ -4805,7 +4811,7 @@ class DatabaseManager {// sign-in or account switch.insertConnectorAction({id,- accountId,+ accountId = null,connector,action,kind,@@ -4856,7 +4862,7 @@ class DatabaseManager {// Receipts name the people a user wrote to, so only the account that took// the action sees them.- listRecentConnectorActions(connector, limit, accountId) {+ listRecentConnectorActions(connector, limit = 10, accountId = null) {if (!this.db) throw new Error("Database not initialized");if (!accountId) return [];return this.dbdiff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 20dc6df10..1c4d902b7 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -36,6 +36,7 @@ const { resolveSystemDefaultMicrophone } = require("./systemDefaultMicrophone");const {registerConnectorIpc,createConnectorPolicyResolver,+ createConnectorAuthLookup,} = require("./connectors/connectorIpc");const { searchContacts } = require("./connectors/contactSearch");// The renderer's ModelRegistry is not main-loadable; the raw registry data is@@ -691,6 +692,8 @@ class IPCHandlers {generation,hasToken: Boolean(token),});+ // A sign-out or another account changes whose login shows.+ void this.connectorManager?.notifyStatusChanged();});if (this.whisperManager?.serverManager) {@@ -2213,6 +2216,7 @@ class IPCHandlers {"active-account-scope-changed",accountId !== null ? { accountId, authGeneration: state.generation } : null);+ void this.connectorManager?.notifyStatusChanged();return { success: true };});@@ -2238,6 +2242,8 @@ class IPCHandlers {};}try {+ // Best effort; each revoke has a 5s deadline (connectorManager.js).+ await this.connectorManager?.disconnectAll();const result = this.databaseManager.deleteAccountData(accountId);this.notifyVectorChanges();for (const noteId of result.deletedNoteIds) {@@ -4021,7 +4027,8 @@ class IPCHandlers {} catch (e) {errors.push(`Device setting files: ${e.message}`);}- for (const directoryName of ["bin", "llama-cpp"]) {+ // "connectors" holds encrypted connector logins (Slack, …).+ for (const directoryName of ["bin", "llama-cpp", "connectors"]) {try {fs.rmSync(path.join(app.getPath("userData"), directoryName), {recursive: true,@@ -6057,7 +6064,11 @@ class IPCHandlers {ipcMain,manager: this.connectorManager,getPolicyState: createConnectorPolicyResolver({- getAuthHeader,+ getAuthHeader: createConnectorAuthLookup({+ hasBearerToken: () => Boolean(tokenStore.get()),+ windowFor: (event) => BrowserWindow.fromWebContents(event.sender),+ authHeaderFor: getAuthHeaderFromWindow,+ }),getPolicy: (options) => workspacePolicyManager.getPolicy(options),peekPolicy: (options) => workspacePolicyManager.peekPolicy(options),getAuthGeneration: () => tokenStore.getState().generation,diff --git a/src/helpers/oauthLoopbackFlow.js b/src/helpers/oauthLoopbackFlow.jsindex c4308cdac..74f49b8c6 100644--- a/src/helpers/oauthLoopbackFlow.js+++ b/src/helpers/oauthLoopbackFlow.js@@ -43,6 +43,10 @@ function redirect(res, params) {res.end();}+function codedError(code, message, extra = {}) {+ return Object.assign(new Error(message), { code, ...extra });+}+// Runs a PKCE auth-code flow through an ephemeral 127.0.0.1 server:// - buildAuthUrl(redirectUri, state, codeChallenge) → provider authorize URL// - handleCallback(code, redirectUri, codeVerifier) → resolves the flow result;@@ -50,21 +54,68 @@ function redirect(res, params) {// specific callback-page code) to reject.// - errorParam — query-param name for the hosted desktop-callback page// (e.g. "gcal_error"); the success param is derived from the same prefix.-function runOAuthLoopbackFlow({ buildAuthUrl, handleCallback, errorParam }) {+// - redirectHost / ports / callbackPath — shape redirect_uri for providers+// that match it exactly (fixed ports are tried in order); the server+// always listens on 127.0.0.1. With a callbackPath, only that path is a+// callback.+// - renderResultPage({ ok }) — answer the browser from this server instead+// of the hosted page, for providers that page doesn't know.+// - publicRedirectUri — for providers that require an HTTPS redirect: the+// provider redirects to that URL (a relay), which forwards the browser to+// this server by the port carried in state as v1.<port>.<nonce>. An error+// callback then counts only with that state.+// - timeoutMs — how long the flow waits for the provider's redirect.+// - signal — an AbortSignal that gives the flow up (a newer attempt replaced+// it): the server closes and the flow rejects with code "oauth_cancelled".+// Once the provider has answered, the exchange finishes regardless, so a+// login it already issued still reaches the caller.+function runOAuthLoopbackFlow({+ buildAuthUrl,+ handleCallback,+ errorParam,+ redirectHost = "127.0.0.1",+ ports = [0],+ callbackPath = "",+ renderResultPage = null,+ publicRedirectUri = null,+ timeoutMs = OAUTH_TIMEOUT_MS,+ signal = null,+}) {const connectedParam = errorParam.replace(/_error$/, "_connected");+ if (signal?.aborted) {+ return Promise.reject(codedError("oauth_cancelled", "OAuth flow cancelled"));+ }return new Promise((resolve, reject) => {const codeVerifier = crypto.randomBytes(32).toString("base64url").slice(0, 43);const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");- const state = crypto.randomBytes(32).toString("hex");+ const nonce = crypto.randomBytes(32).toString("hex");+ // Behind a relay the provider never sees this server, so the relay finds it+ // by the port in state. It is set once listening, before the browser opens.+ let state = nonce;+ const redirectUriFor = (port) =>+ publicRedirectUri ?? `http://${redirectHost}:${port}${callbackPath}`;let callbackClaimed = false;+ const respond = (res, ok, params) => {+ if (renderResultPage) {+ res.writeHead(ok ? 200 : 400, { "Content-Type": "text/html; charset=utf-8" });+ res.end(renderResultPage({ ok }));+ return;+ }+ redirect(res, params);+ };++ const invalidRequest = (res) => {+ res.writeHead(400, { "Content-Type": "text/html" });+ res.end("<html><body><h3>Invalid request.</h3></body></html>");+ };+const server = http.createServer(async (req, res) => {// Accepted requests can outlive server.close(), so only the first// terminal callback may settle the flow or exchange a code.if (callbackClaimed) {- res.writeHead(400, { "Content-Type": "text/html" });- res.end("<html><body><h3>Invalid request.</h3></body></html>");+ invalidRequest(res);return;}@@ -74,68 +125,120 @@ function runOAuthLoopbackFlow({ buildAuthUrl, handleCallback, errorParam }) {const code = url.searchParams.get("code");const error = url.searchParams.get("error");+ // With a callback path, nothing else on this port is the provider's+ // answer: a stray request is refused and the flow keeps waiting.+ if (callbackPath && url.pathname !== callbackPath) {+ invalidRequest(res);+ return;+ }++ // Behind a relay, an error counts only with this flow's state:+ // without it, it is a stray request, not the user's answer.+ if (error && publicRedirectUri && returnedState !== state) {+ invalidRequest(res);+ return;+ }+if (error) {callbackClaimed = true;- redirect(res, { [errorParam]: error });+ respond(res, false, { [errorParam]: error });cleanup();- reject(new Error(`OAuth error: ${error}`));+ reject(codedError("oauth_denied", `OAuth error: ${error}`, { providerError: error }));return;}if (!code || returnedState !== state) {- res.writeHead(400, { "Content-Type": "text/html" });- res.end("<html><body><h3>Invalid request.</h3></body></html>");+ invalidRequest(res);// A real callback with a code but the wrong state is a failed// attempt (stale tab, CSRF). Fail the flow now. A request with no// code (favicon / bare GET) must keep waiting for the redirect.if (code) {callbackClaimed = true;cleanup();- reject(new Error("OAuth state mismatch"));+ reject(codedError("oauth_state_mismatch", "OAuth state mismatch"));}return;}callbackClaimed = true;- const redirectUri = `http://127.0.0.1:${server.address().port}`;- const result = await handleCallback(code, redirectUri, codeVerifier);+ const result = await handleCallback(+ code,+ redirectUriFor(server.address().port),+ codeVerifier+ );- redirect(res, { [connectedParam]: "true" });+ respond(res, true, { [connectedParam]: "true" });cleanup();resolve(result);} catch (err) {callbackClaimed = true;- redirect(res, { [errorParam]: err.redirectCode || "server_error" });+ respond(res, false, { [errorParam]: err.redirectCode || "server_error" });cleanup();reject(err);}});let timeoutId;+ let listenErrorHandler = null;const cleanup = () => {clearTimeout(timeoutId);- server.close();+ signal?.removeEventListener("abort", onAbort);+ if (server.listening) server.close();+ };++ const onAbort = () => {+ if (callbackClaimed) return;+ callbackClaimed = true;+ cleanup();+ reject(codedError("oauth_cancelled", "OAuth flow cancelled"));};+ signal?.addEventListener("abort", onAbort, { once: true });- server.listen(0, "127.0.0.1", () => {+ // One "listening" handler for the whole flow: a failed attempt on a busy+ // port must not leave behind a second one that opens another tab.+ server.once("listening", () => {+ // Given up while binding: close without opening the browser.+ if (callbackClaimed) {+ server.close();+ return;+ }+ if (listenErrorHandler) server.off("error", listenErrorHandler);+ server.on("error", (err) => {+ cleanup();+ reject(err);+ });+ // Fire-and-forget like the shell.openExternal call it replaced: a+ // failed browser launch surfaces as the flow timeout.const port = server.address().port;- const redirectUri = `http://127.0.0.1:${port}`;- // Fire-and-forget like the shell.openExternal call it replaced: a failed- // browser launch surfaces as the flow timeout.- openExternalUrl(buildAuthUrl(redirectUri, state, codeChallenge)).catch(() => {});+ if (publicRedirectUri) state = `v1.${port}.${nonce}`;+ openExternalUrl(buildAuthUrl(redirectUriFor(port), state, codeChallenge)).catch(() => {});});+ // A port in use falls through to the next one in the list.+ const listenOn = (index) => {+ listenErrorHandler = (err) => {+ listenErrorHandler = null;+ if (err.code === "EADDRINUSE" && index + 1 < ports.length) {+ listenOn(index + 1);+ return;+ }+ callbackClaimed = true;+ cleanup();+ reject(+ err.code === "EADDRINUSE" ? codedError("ports_busy", "No loopback port was free") : err+ );+ };+ server.once("error", listenErrorHandler);+ server.listen(ports[index], "127.0.0.1");+ };+ listenOn(0);+timeoutId = setTimeout(() => {callbackClaimed = true;- server.close();- reject(new Error("OAuth flow timed out"));- }, OAUTH_TIMEOUT_MS);-- server.on("error", (err) => {cleanup();- reject(err);- });+ reject(codedError("oauth_timeout", "OAuth flow timed out"));+ }, timeoutMs);});}diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 4736eeebe..61324b93d 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -714,7 +714,8 @@"connectors": {"approval": {"headers": {- "default": "إرسال إلى {{destination}}"+ "default": "إرسال إلى {{destination}}",+ "slackPost": "نشر في {{destination}}"},"identity": "بصفتك {{account}}","identityWithWorkspace": "بصفتك {{account}} في {{workspace}}",@@ -730,7 +731,24 @@"failed": "تعذّر الإرسال: {{message}}","unknown": "تعذّر تأكيد الإرسال. تحقق من {{destination}}.","cancelled": "تم الإلغاء. لم يتم إرسال شيء.",- "notSent": "لم يُرسل."+ "notSent": "لم يُرسل.",+ "policyRetry": "تعذّر التحقق من إعدادات مؤسستك، لذا لم يتم إرسال شيء. اضغط على إرسال للمحاولة مرة أخرى.",+ "errors": {+ "not_in_channel": "أنت لست عضوًا في {{destination}}.",+ "channel_not_found": "تعذّر العثور على {{destination}} في Slack بعد الآن.",+ "is_archived": "{{destination}} مؤرشفة.",+ "reconnect_needed": "يلزم إعادة ربط Slack من الإعدادات.",+ "connection_changed": "تغيّر اتصال Slack قبل الإرسال، لذا لم يُرسل شيء.",+ "rate_limited": "Slack مشغول حاليًا. حاول مرة أخرى بعد قليل.",+ "missing_scope": "لا يملك OpenWhispr إذنًا للنشر هناك. أعد ربط Slack من الإعدادات.",+ "msg_too_long": "الرسالة طويلة جدًا بالنسبة لـ Slack (12,000 حرف كحد أقصى بعد التنسيق).",+ "no_text": "الرسالة فارغة.",+ "network": "تعذّر الوصول إلى Slack. لم يُرسل شيء.",+ "credential_save_failed": "تعذّر حفظ تسجيل الدخول إلى Slack على هذا الكمبيوتر. لم يُرسل شيء. حاول مرة أخرى.",+ "dm_failed": "تعذّر فتح الرسالة المباشرة إلى {{destination}}. لم يُرسل شيء.",+ "restricted": "{{destination}} للقراءة فقط أو مقيّدة بالنسبة لك.",+ "generic": "حدث خطأ ما. لم يُرسل شيء."+ }},"policyOff": "أوقفت مؤسستك تشغيل الموصلات.","email": {@@ -747,13 +765,46 @@"mailto": "تطبيق البريد الافتراضي"}},+ "slack": {+ "title": "Slack",+ "description": "يمكن للمساعد نشر الرسائل في القنوات وللأشخاص نيابةً عنك. توافق على كل رسالة قبل إرسالها.",+ "connect": "ربط",+ "reconnect": "إعادة الربط",+ "disconnect": "قطع الربط",+ "connecting": "أكمل الربط في متصفحك…",+ "connectedAs": "متصل بصفتك {{account}} في {{workspace}}",+ "needsReconnect": "يلزم إعادة ربط Slack.",+ "proRequired": "قم بالترقية إلى خطة مدفوعة ليتمكن المساعد من إرسال رسائل Slack نيابةً عنك.",+ "errors": {+ "connect_failed": "تعذّر ربط Slack. حاول مرة أخرى.",+ "disconnect_failed": "تعذّر قطع ربط Slack. حاول مرة أخرى.",+ "oauth_denied": "لم يتم ربط Slack لأن الإذن لم يُمنح.",+ "oauth_timeout": "استغرق الربط وقتًا طويلاً. حاول مرة أخرى.",+ "oauth_state_mismatch": "رابط تسجيل الدخول هذا كان قديمًا. حاول مرة أخرى.",+ "ports_busy": "يستخدم تطبيق آخر المنافذ التي يحتاجها OpenWhispr للربط. أغلقه وحاول مرة أخرى.",+ "token_exchange_failed": "لم يكمل Slack عملية الربط. حاول مرة أخرى.",+ "not_configured": "Slack غير متاح في هذا الإصدار.",+ "connection_changed": "تغيّر حسابك أو اتصال Slack أثناء الربط. حاول مرة أخرى.",+ "signed_out": "سجّل الدخول إلى OpenWhispr لربط Slack.",+ "policy_blocked": "أوقفت مؤسستك تشغيل الموصلات.",+ "policy_unavailable": "تعذّر التحقق من إعدادات مؤسستك. حاول مرة أخرى."+ },+ "browser": {+ "connectedTitle": "تم توصيل Slack",+ "connectedBody": "يمكنك إغلاق هذا التبويب والعودة إلى OpenWhispr.",+ "failedTitle": "لم يتم توصيل Slack",+ "failedBody": "عد إلى OpenWhispr للمحاولة مرة أخرى."+ }+ },"recent": {"title": "الإجراءات الأخيرة","actions": {- "email_draft": "مسودة إلى {{destination}}"+ "email_draft": "مسودة إلى {{destination}}",+ "slack_send_message": "رسالة إلى {{destination}}"},"unlabeledActions": {- "email_draft": "مسودة بريد إلكتروني"+ "email_draft": "مسودة بريد إلكتروني",+ "slack_send_message": "رسالة Slack"},"states": {"pending": "قيد الانتظار",@@ -772,7 +823,6 @@"draftOpenedOnlySubjectCopied": "تم فتح مسودة إلى {{destination}}. الموضوع موجود في الحافظة.","needsDetails": "يلزم مزيد من التفاصيل.","unavailable": "الموصلات غير متاحة حاليًا.",- "failed": "لم ينجح ذلك.","unknown": "لم يتم التأكيد. تحقق مما إذا كان الإجراء قد تم قبل المحاولة مرة أخرى.","draftUnknown": "لم يتم التأكيد: ربما لم تُفتح المسودة إلى {{destination}}. تحقق قبل المحاولة مرة أخرى.","contactsFound": "جهات الاتصال التي عُثر عليها: {{total}}",@@ -781,7 +831,21 @@"errors": {"open_failed": "تعذّر فتح تطبيق البريد الإلكتروني.","draft_too_long": "عدد المستلمين كبير جدًا لرابط المسودة.",- "invalid_address": "يلزم إدخال عناوين بريد إلكتروني كاملة."+ "invalid_address": "يلزم إدخال عناوين بريد إلكتروني كاملة.",+ "not_in_channel": "لست عضوًا في تلك القناة.",+ "channel_not_found": "تعذّر العثور على تلك المحادثة.",+ "is_archived": "تلك القناة مؤرشفة.",+ "reconnect_needed": "يلزم إعادة ربط Slack.",+ "connection_changed": "تغيّر اتصال Slack. لم يُرسل شيء.",+ "rate_limited": "Slack مشغول حاليًا.",+ "missing_scope": "إذن Slack مفقود.",+ "msg_too_long": "الرسالة طويلة جدًا بالنسبة لـ Slack.",+ "no_text": "الرسالة فارغة.",+ "network": "تعذّر الوصول إلى Slack. لم يُرسل شيء.",+ "credential_save_failed": "تعذّر حفظ تسجيل الدخول إلى Slack على هذا الكمبيوتر. لم يُرسل شيء.",+ "dm_failed": "تعذّر فتح الرسالة المباشرة. لم يُرسل شيء.",+ "restricted": "تلك القناة للقراءة فقط أو مقيّدة.",+ "generic": "لم ينجح ذلك."}}},@@ -1325,6 +1389,7 @@"search_notesName": "البحث في الملاحظات","email_draftName": "مسودة بريد إلكتروني","find_contactName": "البحث عن جهة اتصال",+ "slack_send_messageName": "رسالة Slack","get_noteName": "الحصول على الملاحظة","create_noteName": "إنشاء ملاحظة","update_noteName": "تحديث الملاحظة",@@ -1339,6 +1404,7 @@"search_notesStatus": "جاري البحث في الملاحظات...","email_draftStatus": "جارٍ فتح مسودة بريد إلكتروني...","find_contactStatus": "جارٍ البحث عن جهات الاتصال...",+ "slack_send_messageStatus": "جارٍ تحضير رسالة Slack...","web_searchStatus": "جاري البحث في الويب...","copy_to_clipboardStatus": "جاري النسخ إلى الحافظة...","get_calendar_eventsStatus": "جاري التحقق من التقويم...",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 2133c0bbc..36e434dc1 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3850,6 +3850,7 @@"search_notesName": "Notizen durchsuchen","email_draftName": "E-Mail-Entwurf","find_contactName": "Kontakt suchen",+ "slack_send_messageName": "Slack-Nachricht","get_noteName": "Notiz abrufen","create_noteName": "Notiz erstellen","update_noteName": "Notiz aktualisieren",@@ -3864,6 +3865,7 @@"search_notesStatus": "Notizen werden durchsucht...","email_draftStatus": "E-Mail-Entwurf wird geöffnet...","find_contactStatus": "Kontakte werden gesucht...",+ "slack_send_messageStatus": "Slack-Nachricht wird vorbereitet...","web_searchStatus": "Websuche...","copy_to_clipboardStatus": "In Zwischenablage kopieren...","get_calendar_eventsStatus": "Kalender wird geprüft...",@@ -4019,7 +4021,8 @@"connectors": {"approval": {"headers": {- "default": "An {{destination}} senden"+ "default": "An {{destination}} senden",+ "slackPost": "In {{destination}} posten"},"identity": "Als {{account}}","identityWithWorkspace": "Als {{account}} in {{workspace}}",@@ -4035,7 +4038,24 @@"failed": "Senden fehlgeschlagen: {{message}}","unknown": "Konnte nicht bestätigt werden. Bitte {{destination}} prüfen.","cancelled": "Abgebrochen. Es wurde nichts gesendet.",- "notSent": "Nicht gesendet."+ "notSent": "Nicht gesendet.",+ "policyRetry": "Die Einstellungen deiner Organisation konnten nicht geprüft werden, daher wurde nichts gesendet. Auf Senden drücken, um es erneut zu versuchen.",+ "errors": {+ "not_in_channel": "Du bist kein Mitglied von {{destination}}.",+ "channel_not_found": "{{destination}} konnte in Slack nicht mehr gefunden werden.",+ "is_archived": "{{destination}} ist archiviert.",+ "reconnect_needed": "Slack muss in den Einstellungen erneut verbunden werden.",+ "connection_changed": "Die Slack-Verbindung hat sich vor dem Senden geändert, daher wurde nichts gesendet.",+ "rate_limited": "Slack ist gerade ausgelastet. Versuche es in Kürze erneut.",+ "missing_scope": "OpenWhispr hat keine Berechtigung, dort zu posten. Slack in den Einstellungen erneut verbinden.",+ "msg_too_long": "Die Nachricht ist zu lang für Slack (maximal 12.000 Zeichen nach der Formatierung).",+ "no_text": "Die Nachricht ist leer.",+ "network": "Slack war nicht erreichbar. Es wurde nichts gesendet.",+ "credential_save_failed": "Die Slack-Anmeldung konnte auf diesem Computer nicht gespeichert werden. Es wurde nichts gesendet. Versuche es erneut.",+ "dm_failed": "Die Direktnachricht an {{destination}} konnte nicht geöffnet werden. Es wurde nichts gesendet.",+ "restricted": "{{destination}} ist für dich schreibgeschützt oder eingeschränkt.",+ "generic": "Etwas ist schiefgelaufen. Es wurde nichts gesendet."+ }},"policyOff": "Konnektoren wurden von deiner Organisation deaktiviert.","email": {@@ -4052,13 +4072,46 @@"mailto": "Standard-E-Mail-App"}},+ "slack": {+ "title": "Slack",+ "description": "Der Assistent kann Nachrichten in Kanälen und an Personen in deinem Namen posten. Du bestätigst jede Nachricht, bevor sie gesendet wird.",+ "connect": "Verbinden",+ "reconnect": "Erneut verbinden",+ "disconnect": "Trennen",+ "connecting": "Schließe die Verbindung in deinem Browser ab…",+ "connectedAs": "Verbunden als {{account}} in {{workspace}}",+ "needsReconnect": "Slack muss erneut verbunden werden.",+ "proRequired": "Upgrade auf einen kostenpflichtigen Plan, damit der Assistent Slack-Nachrichten für dich sendet.",+ "errors": {+ "connect_failed": "Slack konnte nicht verbunden werden. Versuche es erneut.",+ "disconnect_failed": "Slack konnte nicht getrennt werden. Versuche es erneut.",+ "oauth_denied": "Slack wurde nicht verbunden, da der Zugriff nicht erlaubt wurde.",+ "oauth_timeout": "Die Verbindung hat zu lange gedauert. Versuche es erneut.",+ "oauth_state_mismatch": "Dieser Anmeldelink war veraltet. Versuche es erneut.",+ "ports_busy": "Eine andere App verwendet die Ports, die OpenWhispr zum Verbinden benötigt. Schließe sie und versuche es erneut.",+ "token_exchange_failed": "Slack hat die Verbindung nicht abgeschlossen. Versuche es erneut.",+ "not_configured": "Slack ist in dieser Version nicht verfügbar.",+ "connection_changed": "Dein Konto oder die Slack-Verbindung hat sich während der Verbindung geändert. Versuche es erneut.",+ "signed_out": "Melde dich bei OpenWhispr an, um Slack zu verbinden.",+ "policy_blocked": "Konnektoren wurden von deiner Organisation deaktiviert.",+ "policy_unavailable": "Die Einstellungen deiner Organisation konnten nicht geprüft werden. Versuche es erneut."+ },+ "browser": {+ "connectedTitle": "Slack ist verbunden",+ "connectedBody": "Du kannst diesen Tab schließen und zu OpenWhispr zurückkehren.",+ "failedTitle": "Slack wurde nicht verbunden",+ "failedBody": "Kehre zu OpenWhispr zurück, um es erneut zu versuchen."+ }+ },"recent": {"title": "Letzte Aktionen","actions": {- "email_draft": "Entwurf an {{destination}}"+ "email_draft": "Entwurf an {{destination}}",+ "slack_send_message": "Nachricht an {{destination}}"},"unlabeledActions": {- "email_draft": "E-Mail-Entwurf"+ "email_draft": "E-Mail-Entwurf",+ "slack_send_message": "Slack-Nachricht"},"states": {"pending": "Wartet",@@ -4077,7 +4130,6 @@"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}}",@@ -4086,7 +4138,21 @@"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."+ "invalid_address": "Vollständige E-Mail-Adressen erforderlich.",+ "not_in_channel": "Kein Mitglied dieses Kanals.",+ "channel_not_found": "Diese Unterhaltung wurde nicht gefunden.",+ "is_archived": "Dieser Kanal ist archiviert.",+ "reconnect_needed": "Slack muss erneut verbunden werden.",+ "connection_changed": "Die Slack-Verbindung hat sich geändert. Nichts wurde gesendet.",+ "rate_limited": "Slack ist gerade ausgelastet.",+ "missing_scope": "Slack-Berechtigung fehlt.",+ "msg_too_long": "Nachricht zu lang für Slack.",+ "no_text": "Die Nachricht ist leer.",+ "network": "Slack nicht erreichbar. Nichts wurde gesendet.",+ "credential_save_failed": "Slack-Anmeldung konnte auf diesem Computer nicht gespeichert werden. Nichts wurde gesendet.",+ "dm_failed": "Direktnachricht konnte nicht geöffnet werden. Nichts wurde gesendet.",+ "restricted": "Dieser Kanal ist schreibgeschützt oder eingeschränkt.",+ "generic": "Das hat nicht funktioniert."}}},diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 666f2f677..9bada0925 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3850,6 +3850,7 @@"search_notesName": "Search notes","email_draftName": "Email draft","find_contactName": "Find contact",+ "slack_send_messageName": "Slack message","get_noteName": "Get note","create_noteName": "Create note","update_noteName": "Update note",@@ -3864,6 +3865,7 @@"search_notesStatus": "Searching notes...","email_draftStatus": "Opening an email draft...","find_contactStatus": "Looking up contacts...",+ "slack_send_messageStatus": "Preparing a Slack message...","web_searchStatus": "Searching the web...","copy_to_clipboardStatus": "Copying to clipboard...","get_calendar_eventsStatus": "Checking calendar...",@@ -4019,7 +4021,8 @@"connectors": {"approval": {"headers": {- "default": "Send to {{destination}}"+ "default": "Send to {{destination}}",+ "slackPost": "Post to {{destination}}"},"identity": "As {{account}}","identityWithWorkspace": "As {{account}} in {{workspace}}",@@ -4035,7 +4038,24 @@"failed": "Couldn't send: {{message}}","unknown": "Couldn't confirm it was sent. Check {{destination}}.","cancelled": "Cancelled. Nothing was sent.",- "notSent": "Not sent."+ "notSent": "Not sent.",+ "policyRetry": "Couldn't check your organization's settings, so nothing was sent. Press Send to try again.",+ "errors": {+ "not_in_channel": "You're not a member of {{destination}}.",+ "channel_not_found": "{{destination}} couldn't be found in Slack anymore.",+ "is_archived": "{{destination}} is archived.",+ "reconnect_needed": "Slack needs to be reconnected in Settings.",+ "connection_changed": "The Slack connection changed before sending, so nothing was sent.",+ "rate_limited": "Slack is busy. Try again shortly.",+ "missing_scope": "OpenWhispr doesn't have permission to post there. Reconnect Slack in Settings.",+ "msg_too_long": "The message is too long for Slack (12,000 characters at most, once formatted).",+ "no_text": "The message is empty.",+ "network": "Slack couldn't be reached. Nothing was sent.",+ "credential_save_failed": "The Slack login couldn't be saved on this computer. Nothing was sent. Try again.",+ "dm_failed": "The direct message to {{destination}} couldn't be opened. Nothing was sent.",+ "restricted": "{{destination}} is read-only or restricted for you.",+ "generic": "Something went wrong. Nothing was sent."+ }},"policyOff": "Connectors are turned off by your organization.","email": {@@ -4052,13 +4072,46 @@"mailto": "Default mail app"}},+ "slack": {+ "title": "Slack",+ "description": "The assistant can post messages to channels and people as you. You approve every message before it's sent.",+ "connect": "Connect",+ "reconnect": "Reconnect",+ "disconnect": "Disconnect",+ "connecting": "Finish connecting in your browser…",+ "connectedAs": "Connected as {{account}} in {{workspace}}",+ "needsReconnect": "Slack needs to be reconnected.",+ "proRequired": "Upgrade to a paid plan to let the assistant send Slack messages for you.",+ "errors": {+ "connect_failed": "Couldn't connect Slack. Try again.",+ "disconnect_failed": "Couldn't disconnect Slack. Try again.",+ "oauth_denied": "Slack wasn't connected because access wasn't allowed.",+ "oauth_timeout": "Connecting took too long. Try again.",+ "oauth_state_mismatch": "That sign-in link was out of date. Try again.",+ "ports_busy": "Another app is using the ports OpenWhispr needs to connect. Close it and try again.",+ "token_exchange_failed": "Slack didn't finish connecting. Try again.",+ "not_configured": "Slack isn't available in this build.",+ "connection_changed": "Your account or Slack connection changed while connecting. Try again.",+ "signed_out": "Sign in to OpenWhispr to connect Slack.",+ "policy_blocked": "Connectors are turned off by your organization.",+ "policy_unavailable": "Couldn't check your organization's settings. Try again."+ },+ "browser": {+ "connectedTitle": "Slack is connected",+ "connectedBody": "You can close this tab and return to OpenWhispr.",+ "failedTitle": "Slack wasn't connected",+ "failedBody": "Return to OpenWhispr to try again."+ }+ },"recent": {"title": "Recent actions","actions": {- "email_draft": "Draft to {{destination}}"+ "email_draft": "Draft to {{destination}}",+ "slack_send_message": "Message to {{destination}}"},"unlabeledActions": {- "email_draft": "Email draft"+ "email_draft": "Email draft",+ "slack_send_message": "Slack message"},"states": {"pending": "Waiting",@@ -4077,7 +4130,6 @@"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}}",@@ -4086,7 +4138,21 @@"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."+ "invalid_address": "Needs full email addresses.",+ "not_in_channel": "Not a member of that channel.",+ "channel_not_found": "Couldn't find that conversation.",+ "is_archived": "That channel is archived.",+ "reconnect_needed": "Slack needs to be reconnected.",+ "connection_changed": "The Slack connection changed. Nothing was sent.",+ "rate_limited": "Slack is busy.",+ "missing_scope": "Missing Slack permission.",+ "msg_too_long": "Message too long for Slack.",+ "no_text": "The message is empty.",+ "network": "Couldn't reach Slack. Nothing was sent.",+ "credential_save_failed": "Couldn't save the Slack login on this computer. Nothing was sent.",+ "dm_failed": "Couldn't open the direct message. Nothing was sent.",+ "restricted": "That channel is read-only or restricted.",+ "generic": "That didn't work."}}},diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex ad5bf16e2..f727d02de 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3734,6 +3734,7 @@"search_notesName": "Buscar notas","email_draftName": "Borrador de correo","find_contactName": "Buscar contacto",+ "slack_send_messageName": "Mensaje de Slack","get_noteName": "Obtener nota","create_noteName": "Crear nota","update_noteName": "Actualizar nota",@@ -3748,6 +3749,7 @@"search_notesStatus": "Buscando notas...","email_draftStatus": "Abriendo un borrador de correo...","find_contactStatus": "Buscando contactos...",+ "slack_send_messageStatus": "Preparando un mensaje de Slack...","web_searchStatus": "Buscando en la web...","copy_to_clipboardStatus": "Copiando al portapapeles...","get_calendar_eventsStatus": "Consultando calendario...",@@ -3903,7 +3905,8 @@"connectors": {"approval": {"headers": {- "default": "Enviar a {{destination}}"+ "default": "Enviar a {{destination}}",+ "slackPost": "Publicar en {{destination}}"},"identity": "Como {{account}}","identityWithWorkspace": "Como {{account}} en {{workspace}}",@@ -3919,7 +3922,24 @@"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."+ "notSent": "No enviado.",+ "policyRetry": "No se pudieron comprobar los ajustes de tu organización, así que no se envió nada. Pulsa Enviar para intentarlo de nuevo.",+ "errors": {+ "not_in_channel": "No eres miembro de {{destination}}.",+ "channel_not_found": "{{destination}} ya no se pudo encontrar en Slack.",+ "is_archived": "{{destination}} está archivado.",+ "reconnect_needed": "Slack debe reconectarse en Configuración.",+ "connection_changed": "La conexión de Slack cambió antes de enviar, así que no se envió nada.",+ "rate_limited": "Slack está ocupado. Vuelve a intentarlo en breve.",+ "missing_scope": "OpenWhispr no tiene permiso para publicar ahí. Reconecta Slack en Configuración.",+ "msg_too_long": "El mensaje es demasiado largo para Slack (12.000 caracteres como máximo, una vez formateado).",+ "no_text": "El mensaje está vacío.",+ "network": "No se pudo conectar con Slack. No se envió nada.",+ "credential_save_failed": "No se pudo guardar el inicio de sesión de Slack en este equipo. No se envió nada. Inténtalo de nuevo.",+ "dm_failed": "No se pudo abrir el mensaje directo a {{destination}}. No se envió nada.",+ "restricted": "{{destination}} es de solo lectura o está restringido para ti.",+ "generic": "Algo salió mal. No se envió nada."+ }},"policyOff": "Tu organización ha desactivado los conectores.","email": {@@ -3936,13 +3956,46 @@"mailto": "Aplicación de correo predeterminada"}},+ "slack": {+ "title": "Slack",+ "description": "El asistente puede publicar mensajes en canales y a personas en tu nombre. Apruebas cada mensaje antes de que se envíe.",+ "connect": "Conectar",+ "reconnect": "Reconectar",+ "disconnect": "Desconectar",+ "connecting": "Termina de conectar en tu navegador…",+ "connectedAs": "Conectado como {{account}} en {{workspace}}",+ "needsReconnect": "Slack debe reconectarse.",+ "proRequired": "Actualiza a un plan de pago para que el asistente envíe mensajes de Slack por ti.",+ "errors": {+ "connect_failed": "No se pudo conectar Slack. Inténtalo de nuevo.",+ "disconnect_failed": "No se pudo desconectar Slack. Inténtalo de nuevo.",+ "oauth_denied": "Slack no se conectó porque no se concedió el acceso.",+ "oauth_timeout": "La conexión tardó demasiado. Inténtalo de nuevo.",+ "oauth_state_mismatch": "Ese enlace de inicio de sesión estaba caducado. Inténtalo de nuevo.",+ "ports_busy": "Otra aplicación está usando los puertos que OpenWhispr necesita para conectarse. Ciérrala e inténtalo de nuevo.",+ "token_exchange_failed": "Slack no terminó de conectarse. Inténtalo de nuevo.",+ "not_configured": "Slack no está disponible en esta versión.",+ "connection_changed": "Tu cuenta o la conexión de Slack cambiaron durante la conexión. Inténtalo de nuevo.",+ "signed_out": "Inicia sesión en OpenWhispr para conectar Slack.",+ "policy_blocked": "Tu organización ha desactivado los conectores.",+ "policy_unavailable": "No se pudieron comprobar los ajustes de tu organización. Inténtalo de nuevo."+ },+ "browser": {+ "connectedTitle": "Slack está conectado",+ "connectedBody": "Puedes cerrar esta pestaña y volver a OpenWhispr.",+ "failedTitle": "Slack no se conectó",+ "failedBody": "Vuelve a OpenWhispr para intentarlo de nuevo."+ }+ },"recent": {"title": "Acciones recientes","actions": {- "email_draft": "Borrador a {{destination}}"+ "email_draft": "Borrador a {{destination}}",+ "slack_send_message": "Mensaje a {{destination}}"},"unlabeledActions": {- "email_draft": "Borrador de correo"+ "email_draft": "Borrador de correo",+ "slack_send_message": "Mensaje de Slack"},"states": {"pending": "Esperando",@@ -3961,7 +4014,6 @@"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}}",@@ -3970,7 +4022,21 @@"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."+ "invalid_address": "Se necesitan direcciones de correo completas.",+ "not_in_channel": "No eres miembro de ese canal.",+ "channel_not_found": "No se pudo encontrar esa conversación.",+ "is_archived": "Ese canal está archivado.",+ "reconnect_needed": "Slack debe reconectarse.",+ "connection_changed": "La conexión de Slack cambió. No se envió nada.",+ "rate_limited": "Slack está ocupado.",+ "missing_scope": "Falta el permiso de Slack.",+ "msg_too_long": "Mensaje demasiado largo para Slack.",+ "no_text": "El mensaje está vacío.",+ "network": "No se pudo conectar con Slack. No se envió nada.",+ "credential_save_failed": "No se pudo guardar el inicio de sesión de Slack en este equipo. No se envió nada.",+ "dm_failed": "No se pudo abrir el mensaje directo. No se envió nada.",+ "restricted": "Ese canal es de solo lectura o está restringido.",+ "generic": "No funcionó."}}},diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex b98f5bd37..6199a3b7b 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3850,6 +3850,7 @@"search_notesName": "Rechercher des notes","email_draftName": "Brouillon d'e-mail","find_contactName": "Rechercher un contact",+ "slack_send_messageName": "Message Slack","get_noteName": "Obtenir une note","create_noteName": "Créer une note","update_noteName": "Mettre à jour une note",@@ -3864,6 +3865,7 @@"search_notesStatus": "Recherche de notes...","email_draftStatus": "Ouverture d'un brouillon d'e-mail...","find_contactStatus": "Recherche de contacts...",+ "slack_send_messageStatus": "Préparation d'un message Slack...","web_searchStatus": "Recherche sur le web...","copy_to_clipboardStatus": "Copie dans le presse-papiers...","get_calendar_eventsStatus": "Vérification du calendrier...",@@ -4019,7 +4021,8 @@"connectors": {"approval": {"headers": {- "default": "Envoyer à {{destination}}"+ "default": "Envoyer à {{destination}}",+ "slackPost": "Publier dans {{destination}}"},"identity": "En tant que {{account}}","identityWithWorkspace": "En tant que {{account}} dans {{workspace}}",@@ -4035,7 +4038,24 @@"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é."+ "notSent": "Non envoyé.",+ "policyRetry": "Impossible de vérifier les paramètres de votre organisation, rien n'a donc été envoyé. Cliquez sur Envoyer pour réessayer.",+ "errors": {+ "not_in_channel": "Vous n'êtes pas membre de {{destination}}.",+ "channel_not_found": "{{destination}} n'a pas pu être retrouvé dans Slack.",+ "is_archived": "{{destination}} est archivé.",+ "reconnect_needed": "Slack doit être reconnecté dans les Paramètres.",+ "connection_changed": "La connexion Slack a changé avant l'envoi, donc rien n'a été envoyé.",+ "rate_limited": "Slack est occupé. Réessayez sous peu.",+ "missing_scope": "OpenWhispr n'a pas la permission de publier là-bas. Reconnectez Slack dans les Paramètres.",+ "msg_too_long": "Le message est trop long pour Slack (12 000 caractères maximum, une fois formaté).",+ "no_text": "Le message est vide.",+ "network": "Slack est injoignable. Rien n'a été envoyé.",+ "credential_save_failed": "La connexion Slack n'a pas pu être enregistrée sur cet ordinateur. Rien n'a été envoyé. Réessayez.",+ "dm_failed": "Le message direct à {{destination}} n'a pas pu être ouvert. Rien n'a été envoyé.",+ "restricted": "{{destination}} est en lecture seule ou restreint pour vous.",+ "generic": "Un problème est survenu. Rien n'a été envoyé."+ }},"policyOff": "Votre organisation a désactivé les connecteurs.","email": {@@ -4052,13 +4072,46 @@"mailto": "Application de messagerie par défaut"}},+ "slack": {+ "title": "Slack",+ "description": "L'assistant peut publier des messages dans des canaux et à des personnes en votre nom. Vous approuvez chaque message avant son envoi.",+ "connect": "Connecter",+ "reconnect": "Reconnecter",+ "disconnect": "Déconnecter",+ "connecting": "Terminez la connexion dans votre navigateur…",+ "connectedAs": "Connecté en tant que {{account}} dans {{workspace}}",+ "needsReconnect": "Slack doit être reconnecté.",+ "proRequired": "Passez à un plan payant pour que l'assistant envoie des messages Slack pour vous.",+ "errors": {+ "connect_failed": "Impossible de connecter Slack. Réessayez.",+ "disconnect_failed": "Impossible de déconnecter Slack. Réessayez.",+ "oauth_denied": "Slack n'a pas été connecté car l'accès n'a pas été autorisé.",+ "oauth_timeout": "La connexion a pris trop de temps. Réessayez.",+ "oauth_state_mismatch": "Ce lien de connexion était périmé. Réessayez.",+ "ports_busy": "Une autre application utilise les ports dont OpenWhispr a besoin pour se connecter. Fermez-la et réessayez.",+ "token_exchange_failed": "Slack n'a pas terminé la connexion. Réessayez.",+ "not_configured": "Slack n'est pas disponible dans cette version.",+ "connection_changed": "Votre compte ou la connexion Slack a changé pendant la connexion. Réessayez.",+ "signed_out": "Connectez-vous à OpenWhispr pour connecter Slack.",+ "policy_blocked": "Votre organisation a désactivé les connecteurs.",+ "policy_unavailable": "Impossible de vérifier les paramètres de votre organisation. Réessayez."+ },+ "browser": {+ "connectedTitle": "Slack est connecté",+ "connectedBody": "Vous pouvez fermer cet onglet et retourner à OpenWhispr.",+ "failedTitle": "Slack n'a pas été connecté",+ "failedBody": "Retournez à OpenWhispr pour réessayer."+ }+ },"recent": {"title": "Actions récentes","actions": {- "email_draft": "Brouillon à {{destination}}"+ "email_draft": "Brouillon à {{destination}}",+ "slack_send_message": "Message à {{destination}}"},"unlabeledActions": {- "email_draft": "Brouillon d'e-mail"+ "email_draft": "Brouillon d'e-mail",+ "slack_send_message": "Message Slack"},"states": {"pending": "En attente",@@ -4077,7 +4130,6 @@"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}}",@@ -4086,7 +4138,21 @@"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."+ "invalid_address": "Des adresses e-mail complètes sont nécessaires.",+ "not_in_channel": "Pas membre de ce canal.",+ "channel_not_found": "Cette conversation est introuvable.",+ "is_archived": "Ce canal est archivé.",+ "reconnect_needed": "Slack doit être reconnecté.",+ "connection_changed": "La connexion Slack a changé. Rien n'a été envoyé.",+ "rate_limited": "Slack est occupé.",+ "missing_scope": "Permission Slack manquante.",+ "msg_too_long": "Message trop long pour Slack.",+ "no_text": "Le message est vide.",+ "network": "Impossible de joindre Slack. Rien n'a été envoyé.",+ "credential_save_failed": "Impossible d'enregistrer la connexion Slack sur cet ordinateur. Rien n'a été envoyé.",+ "dm_failed": "Impossible d'ouvrir le message direct. Rien n'a été envoyé.",+ "restricted": "Ce canal est en lecture seule ou restreint.",+ "generic": "Cela n'a pas fonctionné."}}},diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex f83e6f1aa..63d2eddbf 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -3681,6 +3681,7 @@"search_notesName": "Cerca nelle note","email_draftName": "Bozza email","find_contactName": "Trova contatto",+ "slack_send_messageName": "Messaggio Slack","get_noteName": "Ottieni nota","create_noteName": "Crea nota","update_noteName": "Aggiorna nota",@@ -3695,6 +3696,7 @@"search_notesStatus": "Ricerca nelle note...","email_draftStatus": "Apertura di una bozza email...","find_contactStatus": "Ricerca contatti...",+ "slack_send_messageStatus": "Preparazione di un messaggio Slack...","web_searchStatus": "Ricerca sul web...","copy_to_clipboardStatus": "Copia negli appunti...","get_calendar_eventsStatus": "Controllo del calendario...",@@ -3850,7 +3852,8 @@"connectors": {"approval": {"headers": {- "default": "Invia a {{destination}}"+ "default": "Invia a {{destination}}",+ "slackPost": "Pubblica su {{destination}}"},"identity": "Come {{account}}","identityWithWorkspace": "Come {{account}} in {{workspace}}",@@ -3866,7 +3869,24 @@"failed": "Invio non riuscito: {{message}}","unknown": "Impossibile confermare l'invio. Controlla {{destination}}.","cancelled": "Annullato. Non è stato inviato nulla.",- "notSent": "Non inviato."+ "notSent": "Non inviato.",+ "policyRetry": "Non è stato possibile verificare le impostazioni della tua organizzazione, quindi non è stato inviato nulla. Premi Invia per riprovare.",+ "errors": {+ "not_in_channel": "Non sei membro di {{destination}}.",+ "channel_not_found": "{{destination}} non è più stato trovato su Slack.",+ "is_archived": "{{destination}} è archiviato.",+ "reconnect_needed": "Slack deve essere ricollegato nelle Impostazioni.",+ "connection_changed": "La connessione Slack è cambiata prima dell'invio, quindi non è stato inviato nulla.",+ "rate_limited": "Slack è occupato. Riprova a breve.",+ "missing_scope": "OpenWhispr non ha il permesso di pubblicare lì. Ricollega Slack nelle Impostazioni.",+ "msg_too_long": "Il messaggio è troppo lungo per Slack (massimo 12.000 caratteri, una volta formattato).",+ "no_text": "Il messaggio è vuoto.",+ "network": "Impossibile raggiungere Slack. Non è stato inviato nulla.",+ "credential_save_failed": "Impossibile salvare l'accesso a Slack su questo computer. Non è stato inviato nulla. Riprova.",+ "dm_failed": "Impossibile aprire il messaggio diretto a {{destination}}. Non è stato inviato nulla.",+ "restricted": "{{destination}} è di sola lettura o limitato per te.",+ "generic": "Qualcosa è andato storto. Non è stato inviato nulla."+ }},"policyOff": "La tua organizzazione ha disattivato i connettori.","email": {@@ -3883,13 +3903,46 @@"mailto": "App di posta predefinita"}},+ "slack": {+ "title": "Slack",+ "description": "L'assistente può pubblicare messaggi nei canali e alle persone per tuo conto. Approvi ogni messaggio prima che venga inviato.",+ "connect": "Connetti",+ "reconnect": "Riconnetti",+ "disconnect": "Disconnetti",+ "connecting": "Completa la connessione nel tuo browser…",+ "connectedAs": "Connesso come {{account}} in {{workspace}}",+ "needsReconnect": "Slack deve essere ricollegato.",+ "proRequired": "Passa a un piano a pagamento per far inviare all'assistente i messaggi Slack per te.",+ "errors": {+ "connect_failed": "Impossibile connettere Slack. Riprova.",+ "disconnect_failed": "Impossibile disconnettere Slack. Riprova.",+ "oauth_denied": "Slack non è stato connesso perché l'accesso non è stato consentito.",+ "oauth_timeout": "La connessione ha impiegato troppo tempo. Riprova.",+ "oauth_state_mismatch": "Quel link di accesso non era più valido. Riprova.",+ "ports_busy": "Un'altra app sta usando le porte di cui OpenWhispr ha bisogno per connettersi. Chiudila e riprova.",+ "token_exchange_failed": "Slack non ha completato la connessione. Riprova.",+ "not_configured": "Slack non è disponibile in questa versione.",+ "connection_changed": "Il tuo account o la connessione Slack sono cambiati durante la connessione. Riprova.",+ "signed_out": "Accedi a OpenWhispr per connettere Slack.",+ "policy_blocked": "La tua organizzazione ha disattivato i connettori.",+ "policy_unavailable": "Non è stato possibile verificare le impostazioni della tua organizzazione. Riprova."+ },+ "browser": {+ "connectedTitle": "Slack è connesso",+ "connectedBody": "Puoi chiudere questa scheda e tornare a OpenWhispr.",+ "failedTitle": "Slack non è stato connesso",+ "failedBody": "Torna a OpenWhispr per riprovare."+ }+ },"recent": {"title": "Azioni recenti","actions": {- "email_draft": "Bozza a {{destination}}"+ "email_draft": "Bozza a {{destination}}",+ "slack_send_message": "Messaggio a {{destination}}"},"unlabeledActions": {- "email_draft": "Bozza email"+ "email_draft": "Bozza email",+ "slack_send_message": "Messaggio Slack"},"states": {"pending": "In attesa",@@ -3908,7 +3961,6 @@"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}}",@@ -3917,7 +3969,21 @@"errors": {"open_failed": "Impossibile aprire l'app email.","draft_too_long": "Troppi destinatari per un link di bozza.",- "invalid_address": "Servono indirizzi email completi."+ "invalid_address": "Servono indirizzi email completi.",+ "not_in_channel": "Non sei membro di quel canale.",+ "channel_not_found": "Impossibile trovare quella conversazione.",+ "is_archived": "Quel canale è archiviato.",+ "reconnect_needed": "Slack deve essere ricollegato.",+ "connection_changed": "La connessione Slack è cambiata. Non è stato inviato nulla.",+ "rate_limited": "Slack è occupato.",+ "missing_scope": "Permesso Slack mancante.",+ "msg_too_long": "Messaggio troppo lungo per Slack.",+ "no_text": "Il messaggio è vuoto.",+ "network": "Impossibile raggiungere Slack. Non è stato inviato nulla.",+ "credential_save_failed": "Impossibile salvare l'accesso a Slack su questo computer. Non è stato inviato nulla.",+ "dm_failed": "Impossibile aprire il messaggio diretto. Non è stato inviato nulla.",+ "restricted": "Quel canale è di sola lettura o limitato.",+ "generic": "Non ha funzionato."}}},diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex a89a905f3..c4aebdb57 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -3681,6 +3681,7 @@"search_notesName": "ノートを検索","email_draftName": "メールの下書き","find_contactName": "連絡先を検索",+ "slack_send_messageName": "Slackメッセージ","get_noteName": "ノートを取得","create_noteName": "ノートを作成","update_noteName": "ノートを更新",@@ -3695,6 +3696,7 @@"search_notesStatus": "ノートを検索中...","email_draftStatus": "メールの下書きを開いています...","find_contactStatus": "連絡先を検索中...",+ "slack_send_messageStatus": "Slackメッセージを準備しています...","web_searchStatus": "ウェブを検索中...","copy_to_clipboardStatus": "クリップボードにコピー中...","get_calendar_eventsStatus": "カレンダーを確認中...",@@ -3850,7 +3852,8 @@"connectors": {"approval": {"headers": {- "default": "{{destination}} に送信"+ "default": "{{destination}} に送信",+ "slackPost": "{{destination}}に投稿"},"identity": "{{account}} として","identityWithWorkspace": "{{workspace}} の {{account}} として",@@ -3866,7 +3869,24 @@"failed": "送信できませんでした: {{message}}","unknown": "送信されたか確認できませんでした。{{destination}} を確認してください。","cancelled": "キャンセルしました。何も送信されていません。",- "notSent": "送信されていません。"+ "notSent": "送信されていません。",+ "policyRetry": "組織の設定を確認できなかったため、何も送信されていません。もう一度「送信」を押してください。",+ "errors": {+ "not_in_channel": "{{destination}}のメンバーではありません。",+ "channel_not_found": "{{destination}}がSlackで見つからなくなりました。",+ "is_archived": "{{destination}}はアーカイブされています。",+ "reconnect_needed": "設定でSlackを再接続する必要があります。",+ "connection_changed": "送信前にSlackの接続が変わったため、何も送信されませんでした。",+ "rate_limited": "Slackが混み合っています。しばらくしてからもう一度お試しください。",+ "missing_scope": "OpenWhisprにはそこに投稿する権限がありません。設定でSlackを再接続してください。",+ "msg_too_long": "メッセージがSlackには長すぎます(整形後で最大12,000文字)。",+ "no_text": "メッセージが空です。",+ "network": "Slackに接続できませんでした。何も送信されていません。",+ "credential_save_failed": "このコンピューターにSlackのログイン情報を保存できませんでした。何も送信されていません。もう一度お試しください。",+ "dm_failed": "{{destination}}とのダイレクトメッセージを開けませんでした。何も送信されていません。",+ "restricted": "{{destination}}は読み取り専用か、あなたには制限されています。",+ "generic": "問題が発生しました。何も送信されていません。"+ }},"policyOff": "組織によってコネクタが無効にされています。","email": {@@ -3883,13 +3903,46 @@"mailto": "既定のメールアプリ"}},+ "slack": {+ "title": "Slack",+ "description": "アシスタントはチャンネルや個人にあなたとしてメッセージを投稿できます。送信前に必ず内容を承認します。",+ "connect": "接続",+ "reconnect": "再接続",+ "disconnect": "接続を解除",+ "connecting": "ブラウザで接続を完了してください…",+ "connectedAs": "{{workspace}} の {{account}} として接続済み",+ "needsReconnect": "Slackを再接続する必要があります。",+ "proRequired": "アシスタントにSlackメッセージを送信させるには、有料プランへのアップグレードが必要です。",+ "errors": {+ "connect_failed": "Slackを接続できませんでした。もう一度お試しください。",+ "disconnect_failed": "Slackの接続を解除できませんでした。もう一度お試しください。",+ "oauth_denied": "アクセスが許可されなかったため、Slackは接続されませんでした。",+ "oauth_timeout": "接続に時間がかかりすぎました。もう一度お試しください。",+ "oauth_state_mismatch": "そのサインインリンクは期限切れでした。もう一度お試しください。",+ "ports_busy": "OpenWhisprが接続に必要なポートを別のアプリが使用しています。そのアプリを閉じてから、もう一度お試しください。",+ "token_exchange_failed": "Slackの接続が完了しませんでした。もう一度お試しください。",+ "not_configured": "このビルドではSlackを利用できません。",+ "connection_changed": "接続中にアカウントまたはSlackの接続が変わりました。もう一度お試しください。",+ "signed_out": "Slackを接続するにはOpenWhisprにサインインしてください。",+ "policy_blocked": "組織によってコネクタが無効にされています。",+ "policy_unavailable": "組織の設定を確認できませんでした。もう一度お試しください。"+ },+ "browser": {+ "connectedTitle": "Slackが接続されました",+ "connectedBody": "このタブを閉じてOpenWhisprに戻ることができます。",+ "failedTitle": "Slackは接続されませんでした",+ "failedBody": "OpenWhisprに戻ってもう一度お試しください。"+ }+ },"recent": {"title": "最近のアクション","actions": {- "email_draft": "{{destination}} 宛ての下書き"+ "email_draft": "{{destination}} 宛ての下書き",+ "slack_send_message": "{{destination}} 宛てのメッセージ"},"unlabeledActions": {- "email_draft": "メール下書き"+ "email_draft": "メール下書き",+ "slack_send_message": "Slackメッセージ"},"states": {"pending": "待機中",@@ -3908,7 +3961,6 @@"draftOpenedOnlySubjectCopied": "{{destination}} 宛ての下書きを開きました。件名はクリップボードにあります。","needsDetails": "詳細が必要です。","unavailable": "現在コネクタを利用できません。",- "failed": "うまくいきませんでした。","unknown": "未確認です。再試行する前に完了したかどうかを確認してください。","draftUnknown": "未確認:{{destination}} 宛ての下書きが開かなかった可能性があります。再試行する前に確認してください。","contactsFound": "見つかった連絡先: {{total}}",@@ -3917,7 +3969,21 @@"errors": {"open_failed": "メールアプリを開けませんでした。","draft_too_long": "下書きリンクには宛先が多すぎます。",- "invalid_address": "完全なメールアドレスが必要です。"+ "invalid_address": "完全なメールアドレスが必要です。",+ "not_in_channel": "そのチャンネルのメンバーではありません。",+ "channel_not_found": "その会話が見つかりませんでした。",+ "is_archived": "そのチャンネルはアーカイブされています。",+ "reconnect_needed": "Slackを再接続する必要があります。",+ "connection_changed": "Slackの接続が変わりました。何も送信されていません。",+ "rate_limited": "Slackが混み合っています。",+ "missing_scope": "Slackの権限がありません。",+ "msg_too_long": "メッセージがSlackには長すぎます。",+ "no_text": "メッセージが空です。",+ "network": "Slackに接続できませんでした。何も送信されていません。",+ "credential_save_failed": "このコンピューターにSlackのログイン情報を保存できませんでした。何も送信されていません。",+ "dm_failed": "ダイレクトメッセージを開けませんでした。何も送信されていません。",+ "restricted": "そのチャンネルは読み取り専用か、制限されています。",+ "generic": "うまくいきませんでした。"}}},diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex c1ca7dbd1..20ccb80ab 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -3681,6 +3681,7 @@"search_notesName": "Pesquisar notas","email_draftName": "Rascunho de e-mail","find_contactName": "Encontrar contato",+ "slack_send_messageName": "Mensagem do Slack","get_noteName": "Obter nota","create_noteName": "Criar nota","update_noteName": "Atualizar nota",@@ -3695,6 +3696,7 @@"search_notesStatus": "Pesquisando notas...","email_draftStatus": "Abrindo um rascunho de e-mail...","find_contactStatus": "Procurando contatos...",+ "slack_send_messageStatus": "Preparando uma mensagem do Slack...","web_searchStatus": "Pesquisando na web...","copy_to_clipboardStatus": "Copiando para a área de transferência...","get_calendar_eventsStatus": "Verificando calendário...",@@ -3850,7 +3852,8 @@"connectors": {"approval": {"headers": {- "default": "Enviar para {{destination}}"+ "default": "Enviar para {{destination}}",+ "slackPost": "Publicar em {{destination}}"},"identity": "Como {{account}}","identityWithWorkspace": "Como {{account}} em {{workspace}}",@@ -3866,7 +3869,24 @@"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."+ "notSent": "Não enviado.",+ "policyRetry": "Não foi possível verificar as configurações da sua organização, então nada foi enviado. Pressione Enviar para tentar novamente.",+ "errors": {+ "not_in_channel": "Você não é membro de {{destination}}.",+ "channel_not_found": "{{destination}} não foi mais encontrado no Slack.",+ "is_archived": "{{destination}} está arquivado.",+ "reconnect_needed": "O Slack precisa ser reconectado nas Configurações.",+ "connection_changed": "A conexão do Slack mudou antes do envio, então nada foi enviado.",+ "rate_limited": "O Slack está ocupado. Tente novamente em breve.",+ "missing_scope": "O OpenWhispr não tem permissão para publicar ali. Reconecte o Slack nas Configurações.",+ "msg_too_long": "A mensagem é longa demais para o Slack (no máximo 12.000 caracteres, já formatada).",+ "no_text": "A mensagem está vazia.",+ "network": "Não foi possível acessar o Slack. Nada foi enviado.",+ "credential_save_failed": "Não foi possível salvar o login do Slack neste computador. Nada foi enviado. Tente novamente.",+ "dm_failed": "Não foi possível abrir a mensagem direta para {{destination}}. Nada foi enviado.",+ "restricted": "{{destination}} é somente leitura ou restrito para você.",+ "generic": "Algo deu errado. Nada foi enviado."+ }},"policyOff": "Sua organização desativou os conectores.","email": {@@ -3883,13 +3903,46 @@"mailto": "Aplicativo de e-mail padrão"}},+ "slack": {+ "title": "Slack",+ "description": "O assistente pode publicar mensagens em canais e para pessoas em seu nome. Você aprova cada mensagem antes de ela ser enviada.",+ "connect": "Conectar",+ "reconnect": "Reconectar",+ "disconnect": "Desconectar",+ "connecting": "Termine de conectar no seu navegador…",+ "connectedAs": "Conectado como {{account}} em {{workspace}}",+ "needsReconnect": "O Slack precisa ser reconectado.",+ "proRequired": "Atualize para um plano pago para que o assistente envie mensagens do Slack por você.",+ "errors": {+ "connect_failed": "Não foi possível conectar o Slack. Tente novamente.",+ "disconnect_failed": "Não foi possível desconectar o Slack. Tente novamente.",+ "oauth_denied": "O Slack não foi conectado porque o acesso não foi permitido.",+ "oauth_timeout": "A conexão demorou demais. Tente novamente.",+ "oauth_state_mismatch": "Esse link de login estava desatualizado. Tente novamente.",+ "ports_busy": "Outro aplicativo está usando as portas que o OpenWhispr precisa para conectar. Feche-o e tente novamente.",+ "token_exchange_failed": "O Slack não concluiu a conexão. Tente novamente.",+ "not_configured": "O Slack não está disponível nesta versão.",+ "connection_changed": "Sua conta ou a conexão do Slack mudou durante a conexão. Tente novamente.",+ "signed_out": "Entre no OpenWhispr para conectar o Slack.",+ "policy_blocked": "Sua organização desativou os conectores.",+ "policy_unavailable": "Não foi possível verificar as configurações da sua organização. Tente novamente."+ },+ "browser": {+ "connectedTitle": "O Slack está conectado",+ "connectedBody": "Você pode fechar esta aba e voltar para o OpenWhispr.",+ "failedTitle": "O Slack não foi conectado",+ "failedBody": "Volte para o OpenWhispr para tentar novamente."+ }+ },"recent": {"title": "Ações recentes","actions": {- "email_draft": "Rascunho para {{destination}}"+ "email_draft": "Rascunho para {{destination}}",+ "slack_send_message": "Mensagem para {{destination}}"},"unlabeledActions": {- "email_draft": "Rascunho de e-mail"+ "email_draft": "Rascunho de e-mail",+ "slack_send_message": "Mensagem do Slack"},"states": {"pending": "Aguardando",@@ -3908,7 +3961,6 @@"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}}",@@ -3917,7 +3969,21 @@"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."+ "invalid_address": "São necessários endereços de e-mail completos.",+ "not_in_channel": "Não é membro desse canal.",+ "channel_not_found": "Não foi possível encontrar essa conversa.",+ "is_archived": "Esse canal está arquivado.",+ "reconnect_needed": "O Slack precisa ser reconectado.",+ "connection_changed": "A conexão do Slack mudou. Nada foi enviado.",+ "rate_limited": "O Slack está ocupado.",+ "missing_scope": "Falta permissão do Slack.",+ "msg_too_long": "Mensagem longa demais para o Slack.",+ "no_text": "A mensagem está vazia.",+ "network": "Não foi possível acessar o Slack. Nada foi enviado.",+ "credential_save_failed": "Não foi possível salvar o login do Slack neste computador. Nada foi enviado.",+ "dm_failed": "Não foi possível abrir a mensagem direta. Nada foi enviado.",+ "restricted": "Esse canal é somente leitura ou restrito.",+ "generic": "Não funcionou."}}},diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 2983eb617..b8ee9c2ec 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -3725,6 +3725,7 @@"search_notesName": "Поиск заметок","email_draftName": "Черновик письма","find_contactName": "Найти контакт",+ "slack_send_messageName": "Сообщение Slack","get_noteName": "Получить заметку","create_noteName": "Создать заметку","update_noteName": "Обновить заметку",@@ -3739,6 +3740,7 @@"search_notesStatus": "Поиск в заметках...","email_draftStatus": "Открытие черновика письма...","find_contactStatus": "Поиск контактов...",+ "slack_send_messageStatus": "Подготовка сообщения Slack...","web_searchStatus": "Поиск в интернете...","copy_to_clipboardStatus": "Копирование в буфер обмена...","get_calendar_eventsStatus": "Проверка календаря...",@@ -3894,7 +3896,8 @@"connectors": {"approval": {"headers": {- "default": "Отправить в {{destination}}"+ "default": "Отправить в {{destination}}",+ "slackPost": "Опубликовать в {{destination}}"},"identity": "От имени {{account}}","identityWithWorkspace": "От имени {{account}} в {{workspace}}",@@ -3910,7 +3913,24 @@"failed": "Не удалось отправить: {{message}}","unknown": "Не удалось подтвердить отправку. Проверьте {{destination}}.","cancelled": "Отменено. Ничего не отправлено.",- "notSent": "Не отправлено."+ "notSent": "Не отправлено.",+ "policyRetry": "Не удалось проверить настройки Вашей организации, поэтому ничего не было отправлено. Нажмите «Отправить», чтобы попробовать снова.",+ "errors": {+ "not_in_channel": "Вы не являетесь участником {{destination}}.",+ "channel_not_found": "{{destination}} больше не найден в Slack.",+ "is_archived": "{{destination}} архивирован.",+ "reconnect_needed": "Slack нужно переподключить в настройках.",+ "connection_changed": "Подключение к Slack изменилось перед отправкой, поэтому ничего не было отправлено.",+ "rate_limited": "Slack сейчас перегружен. Повторите попытку чуть позже.",+ "missing_scope": "У OpenWhispr нет разрешения публиковать там. Переподключите Slack в настройках.",+ "msg_too_long": "Сообщение слишком длинное для Slack (не более 12 000 символов после форматирования).",+ "no_text": "Сообщение пустое.",+ "network": "Не удалось связаться со Slack. Ничего не отправлено.",+ "credential_save_failed": "Не удалось сохранить вход в Slack на этом компьютере. Ничего не отправлено. Попробуйте снова.",+ "dm_failed": "Не удалось открыть личные сообщения с {{destination}}. Ничего не отправлено.",+ "restricted": "{{destination}} доступен вам только для чтения или ограничен.",+ "generic": "Что-то пошло не так. Ничего не отправлено."+ }},"policyOff": "Ваша организация отключила коннекторы.","email": {@@ -3927,13 +3947,46 @@"mailto": "Почтовое приложение по умолчанию"}},+ "slack": {+ "title": "Slack",+ "description": "Ассистент может публиковать сообщения в каналах и людям от вашего имени. Вы одобряете каждое сообщение перед отправкой.",+ "connect": "Подключить",+ "reconnect": "Переподключить",+ "disconnect": "Отключить",+ "connecting": "Завершите подключение в браузере…",+ "connectedAs": "Подключено как {{account}} в {{workspace}}",+ "needsReconnect": "Slack нужно переподключить.",+ "proRequired": "Перейдите на платный план, чтобы ассистент отправлял сообщения в Slack за вас.",+ "errors": {+ "connect_failed": "Не удалось подключить Slack. Попробуйте снова.",+ "disconnect_failed": "Не удалось отключить Slack. Попробуйте снова.",+ "oauth_denied": "Slack не был подключён, так как доступ не был разрешён.",+ "oauth_timeout": "Подключение заняло слишком много времени. Попробуйте снова.",+ "oauth_state_mismatch": "Эта ссылка для входа устарела. Попробуйте снова.",+ "ports_busy": "Другое приложение использует порты, которые нужны OpenWhispr для подключения. Закройте его и попробуйте снова.",+ "token_exchange_failed": "Slack не завершил подключение. Попробуйте снова.",+ "not_configured": "Slack недоступен в этой сборке.",+ "connection_changed": "Ваш аккаунт или подключение к Slack изменились во время подключения. Попробуйте снова.",+ "signed_out": "Войдите в OpenWhispr, чтобы подключить Slack.",+ "policy_blocked": "Ваша организация отключила коннекторы.",+ "policy_unavailable": "Не удалось проверить настройки вашей организации. Попробуйте снова."+ },+ "browser": {+ "connectedTitle": "Slack подключён",+ "connectedBody": "Вы можете закрыть эту вкладку и вернуться в OpenWhispr.",+ "failedTitle": "Slack не был подключён",+ "failedBody": "Вернитесь в OpenWhispr, чтобы попробовать снова."+ }+ },"recent": {"title": "Последние действия","actions": {- "email_draft": "Черновик для {{destination}}"+ "email_draft": "Черновик для {{destination}}",+ "slack_send_message": "Сообщение для {{destination}}"},"unlabeledActions": {- "email_draft": "Черновик письма"+ "email_draft": "Черновик письма",+ "slack_send_message": "Сообщение в Slack"},"states": {"pending": "Ожидание",@@ -3952,7 +4005,6 @@"draftOpenedOnlySubjectCopied": "Открыт черновик для {{destination}}. Тема скопирована в буфер обмена.","needsDetails": "Нужны уточнения.","unavailable": "Коннекторы сейчас недоступны.",- "failed": "Не получилось.","unknown": "Не подтверждено. Проверьте, выполнено ли действие, прежде чем повторять.","draftUnknown": "Не подтверждено: черновик для {{destination}} мог не открыться. Проверьте, прежде чем повторять.","contactsFound": "Найдено контактов: {{total}}",@@ -3961,7 +4013,21 @@"errors": {"open_failed": "Не удалось открыть почтовое приложение.","draft_too_long": "Слишком много получателей для ссылки на черновик.",- "invalid_address": "Нужны полные адреса электронной почты."+ "invalid_address": "Нужны полные адреса электронной почты.",+ "not_in_channel": "Вы не участник этого канала.",+ "channel_not_found": "Не удалось найти эту беседу.",+ "is_archived": "Этот канал архивирован.",+ "reconnect_needed": "Slack нужно переподключить.",+ "connection_changed": "Подключение к Slack изменилось. Ничего не было отправлено.",+ "rate_limited": "Slack сейчас перегружен.",+ "missing_scope": "Нет разрешения Slack.",+ "msg_too_long": "Сообщение слишком длинное для Slack.",+ "no_text": "Сообщение пустое.",+ "network": "Не удалось связаться со Slack. Ничего не отправлено.",+ "credential_save_failed": "Не удалось сохранить вход в Slack на этом компьютере. Ничего не отправлено.",+ "dm_failed": "Не удалось открыть личные сообщения. Ничего не отправлено.",+ "restricted": "Этот канал только для чтения или ограничен.",+ "generic": "Не получилось."}}},diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex c72d23e48..e5207564b 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -3681,6 +3681,7 @@"search_notesName": "搜索笔记","email_draftName": "邮件草稿","find_contactName": "查找联系人",+ "slack_send_messageName": "Slack 消息","get_noteName": "获取笔记","create_noteName": "创建笔记","update_noteName": "更新笔记",@@ -3695,6 +3696,7 @@"search_notesStatus": "正在搜索笔记...","email_draftStatus": "正在打开邮件草稿...","find_contactStatus": "正在查找联系人...",+ "slack_send_messageStatus": "正在准备 Slack 消息...","web_searchStatus": "正在搜索网页...","copy_to_clipboardStatus": "正在复制到剪贴板...","get_calendar_eventsStatus": "正在查看日历...",@@ -3850,7 +3852,8 @@"connectors": {"approval": {"headers": {- "default": "发送到 {{destination}}"+ "default": "发送到 {{destination}}",+ "slackPost": "发布到 {{destination}}"},"identity": "以 {{account}} 身份","identityWithWorkspace": "以 {{account}}({{workspace}})身份",@@ -3866,7 +3869,24 @@"failed": "发送失败:{{message}}","unknown": "无法确认是否已发送,请检查 {{destination}}。","cancelled": "已取消,未发送任何内容。",- "notSent": "未发送。"+ "notSent": "未发送。",+ "policyRetry": "无法检查您的组织设置,因此未发送任何内容。请点击“发送”重试。",+ "errors": {+ "not_in_channel": "您不是 {{destination}} 的成员。",+ "channel_not_found": "在 Slack 中已找不到 {{destination}}。",+ "is_archived": "{{destination}} 已归档。",+ "reconnect_needed": "需要在设置中重新连接 Slack。",+ "connection_changed": "发送前 Slack 连接发生了变化,因此未发送任何内容。",+ "rate_limited": "Slack 正忙,请稍后重试。",+ "missing_scope": "OpenWhispr 没有权限在那里发布。请在设置中重新连接 Slack。",+ "msg_too_long": "消息对 Slack 来说太长了(格式化后最多 12,000 个字符)。",+ "no_text": "消息为空。",+ "network": "无法连接到 Slack,未发送任何内容。",+ "credential_save_failed": "无法在此电脑上保存 Slack 登录信息,未发送任何内容。请重试。",+ "dm_failed": "无法打开与 {{destination}} 的私信,未发送任何内容。",+ "restricted": "{{destination}} 对您是只读或受限的。",+ "generic": "出了点问题,未发送任何内容。"+ }},"policyOff": "您的组织已关闭连接器。","email": {@@ -3883,13 +3903,46 @@"mailto": "默认邮件应用"}},+ "slack": {+ "title": "Slack",+ "description": "助手可以代表您在频道和给他人发布消息。每条消息发送前都需要您批准。",+ "connect": "连接",+ "reconnect": "重新连接",+ "disconnect": "断开连接",+ "connecting": "请在浏览器中完成连接…",+ "connectedAs": "已以 {{account}} 身份连接到 {{workspace}}",+ "needsReconnect": "需要重新连接 Slack。",+ "proRequired": "升级到付费计划,让助手为您发送 Slack 消息。",+ "errors": {+ "connect_failed": "无法连接 Slack,请重试。",+ "disconnect_failed": "无法断开 Slack 连接,请重试。",+ "oauth_denied": "由于未获得授权,Slack 未连接。",+ "oauth_timeout": "连接耗时过长,请重试。",+ "oauth_state_mismatch": "该登录链接已过期,请重试。",+ "ports_busy": "另一个应用正在使用 OpenWhispr 连接所需的端口。请关闭它后重试。",+ "token_exchange_failed": "Slack 未完成连接,请重试。",+ "not_configured": "此版本中 Slack 不可用。",+ "connection_changed": "连接过程中您的账户或 Slack 连接发生了变化,请重试。",+ "signed_out": "请登录 OpenWhispr 以连接 Slack。",+ "policy_blocked": "您的组织已关闭连接器。",+ "policy_unavailable": "无法检查您的组织设置,请重试。"+ },+ "browser": {+ "connectedTitle": "Slack 已连接",+ "connectedBody": "您可以关闭此标签页并返回 OpenWhispr。",+ "failedTitle": "Slack 未连接",+ "failedBody": "请返回 OpenWhispr 重试。"+ }+ },"recent": {"title": "最近的操作","actions": {- "email_draft": "发送给 {{destination}} 的草稿"+ "email_draft": "发送给 {{destination}} 的草稿",+ "slack_send_message": "发送给 {{destination}} 的消息"},"unlabeledActions": {- "email_draft": "邮件草稿"+ "email_draft": "邮件草稿",+ "slack_send_message": "Slack 消息"},"states": {"pending": "等待中",@@ -3908,7 +3961,6 @@"draftOpenedOnlySubjectCopied": "已打开发给 {{destination}} 的草稿。主题已在剪贴板中。","needsDetails": "需要更多信息。","unavailable": "连接器暂时不可用。",- "failed": "操作未成功。","unknown": "未确认。请先检查是否已完成,再重试。","draftUnknown": "未确认:发给 {{destination}} 的草稿可能没有打开。请先检查,再重试。","contactsFound": "找到的联系人:{{total}}",@@ -3917,7 +3969,21 @@"errors": {"open_failed": "无法打开您的邮件应用。","draft_too_long": "收件人太多,无法生成草稿链接。",- "invalid_address": "需要完整的电子邮件地址。"+ "invalid_address": "需要完整的电子邮件地址。",+ "not_in_channel": "不是该频道的成员。",+ "channel_not_found": "找不到该对话。",+ "is_archived": "该频道已归档。",+ "reconnect_needed": "需要重新连接 Slack。",+ "connection_changed": "Slack 连接已更改。未发送任何内容。",+ "rate_limited": "Slack 正忙。",+ "missing_scope": "缺少 Slack 权限。",+ "msg_too_long": "消息对 Slack 来说太长。",+ "no_text": "消息为空。",+ "network": "无法连接到 Slack。未发送任何内容。",+ "credential_save_failed": "无法在此电脑上保存 Slack 登录信息。未发送任何内容。",+ "dm_failed": "无法打开私信。未发送任何内容。",+ "restricted": "该频道为只读或受限。",+ "generic": "操作未成功。"}}},diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 961e56de5..a6ff41fae 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -3681,6 +3681,7 @@"search_notesName": "搜尋筆記","email_draftName": "郵件草稿","find_contactName": "尋找聯絡人",+ "slack_send_messageName": "Slack 訊息","get_noteName": "取得筆記","create_noteName": "建立筆記","update_noteName": "更新筆記",@@ -3695,6 +3696,7 @@"search_notesStatus": "正在搜尋筆記...","email_draftStatus": "正在開啟郵件草稿...","find_contactStatus": "正在尋找聯絡人...",+ "slack_send_messageStatus": "正在準備 Slack 訊息...","web_searchStatus": "正在搜尋網頁...","copy_to_clipboardStatus": "正在複製到剪貼簿...","get_calendar_eventsStatus": "正在查看行事曆...",@@ -3850,7 +3852,8 @@"connectors": {"approval": {"headers": {- "default": "傳送至 {{destination}}"+ "default": "傳送至 {{destination}}",+ "slackPost": "發佈到 {{destination}}"},"identity": "以 {{account}} 身分","identityWithWorkspace": "以 {{account}}({{workspace}})身分",@@ -3866,7 +3869,24 @@"failed": "無法傳送:{{message}}","unknown": "無法確認是否已傳送,請檢查 {{destination}}。","cancelled": "已取消,未傳送任何內容。",- "notSent": "未傳送。"+ "notSent": "未傳送。",+ "policyRetry": "無法檢查您的組織設定,因此未傳送任何內容。請點一下「傳送」重試。",+ "errors": {+ "not_in_channel": "您不是 {{destination}} 的成員。",+ "channel_not_found": "在 Slack 中已找不到 {{destination}}。",+ "is_archived": "{{destination}} 已封存。",+ "reconnect_needed": "需要在設定中重新連接 Slack。",+ "connection_changed": "傳送前 Slack 連線發生了變化,因此未傳送任何內容。",+ "rate_limited": "Slack 忙碌中,請稍後再試。",+ "missing_scope": "OpenWhispr 沒有權限在那裡發佈。請在設定中重新連接 Slack。",+ "msg_too_long": "訊息對 Slack 來說太長了(格式化後最多 12,000 個字元)。",+ "no_text": "訊息是空的。",+ "network": "無法連線到 Slack,未傳送任何內容。",+ "credential_save_failed": "無法在這台電腦上儲存 Slack 登入資訊,未傳送任何內容。請再試一次。",+ "dm_failed": "無法開啟與 {{destination}} 的私訊,未傳送任何內容。",+ "restricted": "{{destination}} 對您是唯讀或受限的。",+ "generic": "發生問題,未傳送任何內容。"+ }},"policyOff": "您的組織已關閉連接器。","email": {@@ -3883,13 +3903,46 @@"mailto": "預設郵件應用程式"}},+ "slack": {+ "title": "Slack",+ "description": "助理可以代表您在頻道和向他人發佈訊息。每則訊息傳送前都需要您核准。",+ "connect": "連接",+ "reconnect": "重新連接",+ "disconnect": "中斷連接",+ "connecting": "請在瀏覽器中完成連接…",+ "connectedAs": "已以 {{account}} 身分連接到 {{workspace}}",+ "needsReconnect": "需要重新連接 Slack。",+ "proRequired": "升級到付費方案,讓助理為您傳送 Slack 訊息。",+ "errors": {+ "connect_failed": "無法連接 Slack,請重試。",+ "disconnect_failed": "無法中斷 Slack 連接,請重試。",+ "oauth_denied": "由於未獲得授權,Slack 未連接。",+ "oauth_timeout": "連接耗時過長,請重試。",+ "oauth_state_mismatch": "該登入連結已過期,請重試。",+ "ports_busy": "另一個應用程式正在使用 OpenWhispr 連接所需的連接埠。請關閉它後重試。",+ "token_exchange_failed": "Slack 未完成連接,請重試。",+ "not_configured": "此版本中 Slack 不可用。",+ "connection_changed": "連接過程中您的帳戶或 Slack 連接發生了變化,請重試。",+ "signed_out": "請登入 OpenWhispr 以連接 Slack。",+ "policy_blocked": "您的組織已關閉連接器。",+ "policy_unavailable": "無法檢查您的組織設定,請重試。"+ },+ "browser": {+ "connectedTitle": "Slack 已連接",+ "connectedBody": "您可以關閉此分頁並返回 OpenWhispr。",+ "failedTitle": "Slack 未連接",+ "failedBody": "請返回 OpenWhispr 重試。"+ }+ },"recent": {"title": "近期操作","actions": {- "email_draft": "傳送給 {{destination}} 的草稿"+ "email_draft": "傳送給 {{destination}} 的草稿",+ "slack_send_message": "傳送給 {{destination}} 的訊息"},"unlabeledActions": {- "email_draft": "郵件草稿"+ "email_draft": "郵件草稿",+ "slack_send_message": "Slack 訊息"},"states": {"pending": "等待中",@@ -3908,7 +3961,6 @@"draftOpenedOnlySubjectCopied": "已開啟寄給 {{destination}} 的草稿。主旨已在剪貼簿中。","needsDetails": "需要更多資訊。","unavailable": "連接器暫時無法使用。",- "failed": "操作未成功。","unknown": "未確認。請先檢查是否已完成,再重試。","draftUnknown": "未確認:寄給 {{destination}} 的草稿可能沒有開啟。請先檢查,再重試。","contactsFound": "找到的聯絡人:{{total}}",@@ -3917,7 +3969,21 @@"errors": {"open_failed": "無法開啟您的郵件應用程式。","draft_too_long": "收件者太多,無法產生草稿連結。",- "invalid_address": "需要完整的電子郵件地址。"+ "invalid_address": "需要完整的電子郵件地址。",+ "not_in_channel": "不是該頻道的成員。",+ "channel_not_found": "找不到該對話。",+ "is_archived": "該頻道已封存。",+ "reconnect_needed": "需要重新連接 Slack。",+ "connection_changed": "Slack 連線已變更。未傳送任何內容。",+ "rate_limited": "Slack 忙碌中。",+ "missing_scope": "缺少 Slack 權限。",+ "msg_too_long": "訊息對 Slack 來說太長。",+ "no_text": "訊息是空的。",+ "network": "無法連線到 Slack。未傳送任何內容。",+ "credential_save_failed": "無法在這台電腦上儲存 Slack 登入資訊。未傳送任何內容。",+ "dm_failed": "無法開啟私訊。未傳送任何內容。",+ "restricted": "該頻道為唯讀或受限。",+ "generic": "操作未成功。"}}},diff --git a/src/services/tools/ToolRegistry.ts b/src/services/tools/ToolRegistry.tsindex 63f7e8bcd..1a1bbbc49 100644--- a/src/services/tools/ToolRegistry.ts+++ b/src/services/tools/ToolRegistry.ts@@ -17,6 +17,8 @@ export interface HoldDeliveryOptions {* tool runs outside a chat turn (tests, direct calls).*/export interface ToolExecutionContext {+ /** The assistant message the call belongs to; approval cards key on it. */+ messageId: string;toolCallId: string;/** Aborts when the turn is cancelled or its conversation ends. */signal: AbortSignal;@@ -93,7 +95,7 @@ export class ToolRegistry {* `onDisplayText` receives each call's displayText for its tool step.*/toAISDKFormat(- createContext?: (toolCallId: string) => ToolExecutionContext,+ createContext?: (toolCallId: string, abortSignal?: AbortSignal) => ToolExecutionContext,onDisplayText?: (toolCallId: string, displayText: string) => void): Record<string, Tool> {const result: Record<string, Tool> = {};@@ -106,7 +108,7 @@ export class ToolRegistry {const toolResult = await executeTool(def,args as Record<string, unknown>,- createContext?.(options.toolCallId)+ createContext?.(options.toolCallId, options.abortSignal));onDisplayText?.(options.toolCallId, toolResult.displayText);return toolResult.success ? toolResult.data : { error: toolResult.displayText };diff --git a/src/services/tools/connectors/emailDraftTool.ts b/src/services/tools/connectors/emailDraftTool.tsindex 655f4bd46..88dd7af31 100644--- a/src/services/tools/connectors/emailDraftTool.ts+++ b/src/services/tools/connectors/emailDraftTool.ts@@ -164,6 +164,7 @@ export function createEmailDraftTool(target: EmailDraftTarget): ToolDefinition {if (result.state === "unknown") {if (clipboardReserved) preserveClipboard();return unknownResult(+ to.join(", "),`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 }));diff --git a/src/services/tools/connectors/slackSendMessageTool.ts b/src/services/tools/connectors/slackSendMessageTool.tsnew file mode 100644index 000000000..b02296218--- /dev/null+++ b/src/services/tools/connectors/slackSendMessageTool.ts@@ -0,0 +1,53 @@+import type { ToolDefinition, ToolExecutionContext, ToolResult } from "../ToolRegistry";+import { runApprovalAction } from "./runApprovalAction";+import { failedResult, needsClarificationResult } from "./toolOutcome";++// By Send the card was already shown, so a channel that disappeared after+// prepare comes back as a failure. The model should ask where to send it.+function askAboutVanishedChannel(result: ToolResult, destination: string): ToolResult {+ const data = result.data as { status?: string; errorCode?: string } | null;+ if (data?.status === "failed" && data.errorCode === "channel_not_found") {+ return needsClarificationResult(+ `${destination} couldn't be found in Slack anymore. Ask the user where to send the message.`+ );+ }+ return result;+}++export const slackSendMessageTool: ToolDefinition = {+ name: "slack_send_message",+ description:+ "Post a message to Slack as the user. Nothing is sent until the user approves it on a card. `destination` is a #channel the user is in, a person's name, an @handle, or an email address. `text` is the message in Markdown.",+ parameters: {+ type: "object",+ properties: {+ destination: {+ type: "string",+ description: "#channel, a person's name, @handle, or email address",+ },+ text: { type: "string", description: "The message, in Markdown" },+ },+ required: ["destination", "text"],+ additionalProperties: false,+ },+ readOnly: false,++ async execute(+ args: Record<string, unknown>,+ context?: ToolExecutionContext+ ): Promise<ToolResult> {+ // Every outcome keeps the turn off the caret: a card, a question back and+ // a receipt all belong in the panel, never in the user's document.+ context?.onHoldDelivery();+ const destination = typeof args.destination === "string" ? args.destination.trim() : "";+ const text = typeof args.text === "string" ? args.text : "";+ if (!destination) {+ return needsClarificationResult(+ "Ask the user which Slack channel or person to send this to."+ );+ }+ if (!text.trim()) return failedResult("no_text", "The message is empty.");+ const result = await runApprovalAction(context, "slack", "send_message", { destination, text });+ return askAboutVanishedChannel(result, destination);+ },+};diff --git a/src/services/tools/connectors/toolOutcome.ts b/src/services/tools/connectors/toolOutcome.tsindex b550c6b91..82309b529 100644--- a/src/services/tools/connectors/toolOutcome.ts+++ b/src/services/tools/connectors/toolOutcome.ts@@ -1,4 +1,5 @@import i18n from "../../../i18n";+import { connectorErrorCopyKey } from "../../../utils/connectorErrorCopy";import type { ToolResult } from "../ToolRegistry";import type { ApprovalOutcome, ConnectorPrepareResult } from "../../../types/connectors";@@ -42,19 +43,21 @@ 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"),+ displayText: i18n.t(`connectors.toolStatus.errors.${connectorErrorCopyKey(errorCode)}`, {+ defaultValue: i18n.t("connectors.toolStatus.errors.generic"),}),};}+// A direct action that may already have acted: the model must not retry it.export function unknownResult(+ destination: string,guidance: string,displayText: string = i18n.t("connectors.toolStatus.unknown")): ToolResult {return {success: true,- data: { status: "unknown", guidance: `${guidance} ${NO_RETRY}` },+ data: { status: "unknown", destination, guidance: `${guidance} ${NO_RETRY}` },displayText,};}diff --git a/src/services/tools/index.ts b/src/services/tools/index.tsindex a63af205a..7db246aff 100644--- a/src/services/tools/index.ts+++ b/src/services/tools/index.ts@@ -12,6 +12,7 @@ import { createSnippetTool, createUpdateSnippetsTool, type SnippetActions } fromimport { createUpdateDictionaryTool, type DictionaryActions } from "./dictionaryTool";import { createEmailDraftTool } from "./connectors/emailDraftTool";import { findContactTool } from "./connectors/findContactTool";+import { slackSendMessageTool } from "./connectors/slackSendMessageTool";import type { ContainerScope } from "../../types/chat";import type { EmailDraftTarget } from "../../utils/emailDraftTarget";@@ -28,7 +29,7 @@ interface ToolRegistrySettings {/** 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 };+ connectors?: { emailDraftTarget: EmailDraftTarget; slackReady: boolean };}export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry {@@ -61,6 +62,7 @@ export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistryif (settings.connectors) {registry.register(findContactTool);registry.register(createEmailDraftTool(settings.connectors.emailDraftTarget));+ if (settings.connectors.slackReady) registry.register(slackSendMessageTool);}return registry;diff --git a/src/stores/connectorApprovalStore.ts b/src/stores/connectorApprovalStore.tsindex 253c36bd1..be15c0e83 100644--- a/src/stores/connectorApprovalStore.ts+++ b/src/stores/connectorApprovalStore.ts@@ -19,6 +19,9 @@ export interface ApprovalDraft {}export interface ApprovalEntry {+ /** approvalKey(messageId, toolCallId). */+ key: string;+ messageId: string;toolCallId: string;actionId: string;connectorId: string;@@ -27,6 +30,10 @@ export interface ApprovalEntry {state: ApprovalState;url?: string;message?: string;+ /** The connector's failure code, when state is "failed"; drives the card's translated copy. */+ errorCode?: string;+ /** Shown on a pending card after a Send that could not run. */+ notice?: "policy_retry";}interface ApprovalStoreState {@@ -35,10 +42,21 @@ interface ApprovalStoreState {export const useConnectorApprovalStore = create<ApprovalStoreState>(() => ({ entries: {} }));+/**+ * Providers may reuse tool-call ids across turns, so a card belongs to the+ * assistant message and the tool call together: a reused id on a new+ * message must never show, or settle, an old message's card.+ */+export function approvalKey(messageId: string, toolCallId: string): string {+ return `${messageId}::${toolCallId}`;+}+interface PendingResolution {resolve: (outcome: ApprovalOutcome) => void;timer: ReturnType<typeof setTimeout>;detach: () => void;+ signal: AbortSignal;+ expiresAt: number;}// Promise resolvers stay outside zustand state: they are not renderable.@@ -60,67 +78,80 @@ function isConnectorCommitResult(value: unknown): value is ConnectorCommitResult);}-function entryFor(toolCallId: string): ApprovalEntry | undefined {- return useConnectorApprovalStore.getState().entries[toolCallId];+function entryFor(key: string): ApprovalEntry | undefined {+ return useConnectorApprovalStore.getState().entries[key];}-function patchEntry(toolCallId: string, patch: Partial<ApprovalEntry>): void {+function patchEntry(key: string, patch: Partial<ApprovalEntry>): void {useConnectorApprovalStore.setState((state) => {- const entry = state.entries[toolCallId];+ const entry = state.entries[key];if (!entry) return state;- return { entries: { ...state.entries, [toolCallId]: { ...entry, ...patch } } };+ return { entries: { ...state.entries, [key]: { ...entry, ...patch } } };});}function settle(- toolCallId: string,+ key: string,outcome: ApprovalOutcome,state: ApprovalState,patch: Partial<ApprovalEntry> = {}): void {- const pending = resolutions.get(toolCallId);+ const pending = resolutions.get(key);if (!pending) return;- resolutions.delete(toolCallId);+ resolutions.delete(key);clearTimeout(pending.timer);pending.detach();- patchEntry(toolCallId, { state, ...patch });+ patchEntry(key, { state, notice: undefined, ...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);+function withdraw(key: string, reason: "conversation_ended" | "expired"): void {+ const entry = entryFor(key);if (!entry || entry.state !== "pending") return;void window.electronAPI?.connectorCancel?.(entry.actionId, reason);- settle(toolCallId, { state: "not_sent", reason }, "not_sent");+ settle(key, { state: "not_sent", reason }, "not_sent");+}++// A Send whose policy check couldn't finish sent nothing, so the card goes+// back to pending. An abort or expiry that fired meanwhile — when only a+// pending card can be withdrawn — is applied now.+function returnToPending(key: string): void {+ patchEntry(key, { state: "pending", notice: "policy_retry" });+ const pending = resolutions.get(key);+ if (!pending) return;+ if (pending.signal.aborted) withdraw(key, "conversation_ended");+ else if (Date.now() >= pending.expiresAt) withdraw(key, "expired");}export function requestApproval(context: ToolExecutionContext,request: { actionId: string; connectorId: string; preview: ConnectorPreview }): Promise<ApprovalOutcome> {- const { toolCallId, signal } = context;+ const { messageId, toolCallId, signal } = context;+ const key = approvalKey(messageId, toolCallId);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)) {+ // A second request for the same message and tool call must never steal+ // the first card's resolver, timer or entry — that would cross-wire two+ // actions, and the loser's promise would never resolve.+ if (resolutions.has(key)) {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");+ const onAbort = (): void => withdraw(key, "conversation_ended");signal.addEventListener("abort", onAbort, { once: true });- const timer = setTimeout(() => withdraw(toolCallId, "expired"), APPROVAL_TTL_MS);- resolutions.set(toolCallId, {+ const timer = setTimeout(() => withdraw(key, "expired"), APPROVAL_TTL_MS);+ resolutions.set(key, {resolve,timer,detach: () => signal.removeEventListener("abort", onAbort),+ signal,+ expiresAt: Date.now() + APPROVAL_TTL_MS,});const draft: ApprovalDraft = {...(request.preview.title !== undefined ? { title: request.preview.title } : {}),@@ -129,17 +160,17 @@ export function requestApproval(useConnectorApprovalStore.setState((state) => ({entries: {...state.entries,- [toolCallId]: { toolCallId, ...request, draft, state: "pending" },+ [key]: { key, messageId, toolCallId, ...request, draft, state: "pending" },},}));context.onApprovalRequested();});}-export function updateApprovalDraft(toolCallId: string, patch: Partial<ApprovalDraft>): void {- const entry = entryFor(toolCallId);+export function updateApprovalDraft(key: string, patch: Partial<ApprovalDraft>): void {+ const entry = entryFor(key);if (!entry || entry.state !== "pending") return;- patchEntry(toolCallId, {+ patchEntry(key, {draft: {...entry.draft,...(patch.body !== undefined ? { body: patch.body } : {}),@@ -150,25 +181,23 @@ export function updateApprovalDraft(toolCallId: string, patch: Partial<ApprovalD});}-export function cancelApproval(toolCallId: string): void {- const entry = entryFor(toolCallId);+export function cancelApproval(key: string): void {+ const entry = entryFor(key);if (!entry || entry.state !== "pending") return;void window.electronAPI?.connectorCancel?.(entry.actionId, "cancelled_by_user");- settle(toolCallId, { state: "cancelled" }, "cancelled");+ settle(key, { 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);+export async function approveAction(key: string): Promise<void> {+ const entry = entryFor(key);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();- }+ // The expiry timer and abort listener stay armed while sending. They only+ // withdraw a pending card, and a Send that comes back retryable returns+ // the card to pending; settle() disarms them for every final outcome.+ patchEntry(key, { state: "committing", notice: undefined });let raw: unknown;try {@@ -177,16 +206,20 @@ export async function approveAction(toolCallId: string): Promise<void> {// 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.+ // A missing or unrecognized result 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" };+ if (result.state === "not_sent" && result.retryable === true) {+ returnToPending(key);+ return;+ }+const finalText = entry.draft.body !== entry.preview.body ? entry.draft.body : undefined;switch (result.state) {case "sent":settle(- toolCallId,+ key,{ state: "sent", url: result.url, ...(finalText !== undefined ? { finalText } : {}) },"sent",{ url: result.url }@@ -194,15 +227,15 @@ export async function approveAction(toolCallId: string): Promise<void> {break;case "failed":settle(- toolCallId,+ key,{ state: "failed", errorCode: result.errorCode, message: result.message },"failed",- { message: result.message }+ { message: result.message, errorCode: result.errorCode });break;case "unknown":settle(- toolCallId,+ key,{state: "unknown",...(result.checkUrl !== undefined ? { checkUrl: result.checkUrl } : {}),@@ -212,7 +245,7 @@ export async function approveAction(toolCallId: string): Promise<void> {);break;case "not_sent":- settle(toolCallId, { state: "not_sent", reason: result.reason }, "not_sent");+ settle(key, { state: "not_sent", reason: result.reason }, "not_sent");break;}}diff --git a/src/stores/connectorStatusStore.ts b/src/stores/connectorStatusStore.tsnew file mode 100644index 000000000..6423922d4--- /dev/null+++ b/src/stores/connectorStatusStore.ts@@ -0,0 +1,61 @@+import { create } from "zustand";+import type { ConnectorStatus } from "../types/connectors";++interface ConnectorStatusState {+ statuses: Record<string, ConnectorStatus>;+ loaded: boolean;+}++export const useConnectorStatusStore = create<ConnectorStatusState>(() => ({+ statuses: {},+ loaded: false,+}));++function apply(list: ConnectorStatus[] | null | undefined): void {+ const statuses: Record<string, ConnectorStatus> = {};+ for (const status of Array.isArray(list) ? list : []) statuses[status.id] = status;+ useConnectorStatusStore.setState({ statuses, loaded: true });+}++let subscribed = false;+let loading: Promise<void> | null = null;+// Bumped by every broadcast from main. A load that started before the latest+// broadcast carries an older snapshot and is dropped.+let revision = 0;++export function refreshConnectorStatus(): Promise<void> {+ if (!loading) {+ const startedAt = revision;+ loading = (async () => {+ try {+ const list = await window.electronAPI?.connectorStatus?.();+ if (revision === startedAt) apply(list);+ } catch {+ // Unknown means not connected. `loaded` stays false, so the next+ // ensureConnectorStatus() tries again.+ if (revision === startedAt) useConnectorStatusStore.setState({ statuses: {} });+ } finally {+ loading = null;+ }+ })();+ }+ return loading;+}++/** Subscribes once per window, then loads until one load succeeds. */+export async function ensureConnectorStatus(): Promise<void> {+ if (!subscribed) {+ subscribed = true;+ window.electronAPI?.onConnectorStatusChanged?.((statuses) => {+ revision += 1;+ apply(statuses);+ });+ }+ if (!useConnectorStatusStore.getState().loaded) await refreshConnectorStatus();+}++/** Connected, and not waiting on a reconnect. */+export function isConnectorReady(id: string): boolean {+ const status = useConnectorStatusStore.getState().statuses[id];+ return Boolean(status?.connected && !status.needsReconnect);+}diff --git a/src/types/connectors.ts b/src/types/connectors.tsindex 08d4e5771..d03d213e3 100644--- a/src/types/connectors.ts+++ b/src/types/connectors.ts@@ -1,4 +1,4 @@-export type ConnectorPolicyState = "allowed" | "blocked" | "unavailable";+export type ConnectorPolicyState = "allowed" | "blocked" | "unavailable" | "signed_out";export type ConnectorCancelReason = "cancelled_by_user" | "conversation_ended" | "expired";@@ -32,8 +32,8 @@ export type ConnectorPrepareResult =export type ConnectorCommitResult =| { state: "sent"; url?: string }| { state: "failed"; errorCode: string; message: string }- | { state: "unknown"; checkUrl?: string }- | { state: "not_sent"; reason: string };+ | { state: "unknown"; checkUrl?: string; errorCode?: string }+ | { state: "not_sent"; reason: string; retryable?: boolean };export type ConnectorDirectResult =| {@@ -59,8 +59,20 @@ export interface ConnectorStatus {id: string;connected: boolean;accountLabel: string | null;+ workspaceLabel: string | null;+ needsReconnect: boolean;}+export type ConnectorConnectResult =+ | { status: "connected"; accountLabel: string | null; workspaceLabel: string | null }+ | { status: "failed"; errorCode: string }+ | { status: "unavailable"; reason: string };++export type ConnectorDisconnectResult =+ | { status: "disconnected" }+ | { status: "failed"; errorCode: string }+ | { status: "unavailable"; reason: string };+export type ConnectorActionState ="pending" | "committing" | "sent" | "failed" | "unknown" | "cancelled" | "expired";diff --git a/src/types/electron.ts b/src/types/electron.tsindex 7246fc487..94eb77483 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -15,7 +15,9 @@ import type {ConnectorActionRecord,ConnectorCancelReason,ConnectorCommitResult,+ ConnectorConnectResult,ConnectorDirectResult,+ ConnectorDisconnectResult,ConnectorEdits,ConnectorPrepareResult,ConnectorStatus,@@ -2939,6 +2941,9 @@ declare global {connectorFindContacts?: (query: string) => Promise<{ contacts: ContactMatch[]; hasMore?: boolean; unavailableReason?: string }>;+ connectorConnect?: (connectorId: string) => Promise<ConnectorConnectResult>;+ connectorDisconnect?: (connectorId: string) => Promise<ConnectorDisconnectResult>;+ onConnectorStatusChanged?: (callback: (statuses: ConnectorStatus[]) => void) => () => void;calendarGetAvailability?: (request: CalendarAvailabilityRequest) => Promise<diff --git a/src/utils/connectorErrorCopy.ts b/src/utils/connectorErrorCopy.tsnew file mode 100644index 000000000..439d3397b--- /dev/null+++ b/src/utils/connectorErrorCopy.ts@@ -0,0 +1,82 @@+/**+ * The translated copy a failed connector action shows, as a key under both+ * `connectors.approval.errors` (the approval card) and+ * `connectors.toolStatus.errors` (the tool step). One mapping for both, so+ * they can't drift. A failed action is one the provider didn't act on, so the+ * copy never says it might have been sent.+ */+export type ConnectorErrorCopyKey =+ | "not_in_channel"+ | "channel_not_found"+ | "is_archived"+ | "reconnect_needed"+ | "connection_changed"+ | "rate_limited"+ | "missing_scope"+ | "msg_too_long"+ | "no_text"+ | "credential_save_failed"+ | "network"+ | "dm_failed"+ | "restricted"+ | "generic"+ // Email drafts fail in a tool step only, never on a card.+ | "open_failed"+ | "draft_too_long"+ | "invalid_address";++const OWN_COPY: ReadonlySet<string> = new Set<ConnectorErrorCopyKey>([+ "not_in_channel",+ "channel_not_found",+ "is_archived",+ "reconnect_needed",+ "connection_changed",+ "rate_limited",+ "missing_scope",+ "msg_too_long",+ "no_text",+ "credential_save_failed",+ "open_failed",+ "draft_too_long",+ "invalid_address",+]);++const ALIASES: ReadonlyMap<string, ConnectorErrorCopyKey> = new Map([+ // Slack refused or revoked the login.+ ["invalid_auth", "reconnect_needed"],+ ["account_inactive", "reconnect_needed"],+ ["not_authed", "reconnect_needed"],+ ["token_revoked", "reconnect_needed"],+ ["ratelimited", "rate_limited"],+ ["restricted_action", "restricted"],+ ["restricted_action_read_only_channel", "restricted"],+ ["ekm_access_denied", "restricted"],+ // A request that never left, or a token refresh Slack couldn't answer,+ // before anything was posted.+ ["network_error", "network"],+ ["timeout", "network"],+ ["internal_error", "network"],+ ["service_unavailable", "network"],+ // conversations.open refusals: the DM, and so the message, never opened.+ ["user_not_found", "dm_failed"],+ ["user_not_visible", "dm_failed"],+ ["user_disabled", "dm_failed"],+ ["cannot_dm_bot", "dm_failed"],+ ["not_enough_users", "dm_failed"],+ ["too_many_users", "dm_failed"],+ ["users_list_not_supplied", "dm_failed"],+ ["method_not_supported_for_channel_type", "dm_failed"],+]);++// Transport codes: Node's (ECONNREFUSED, EAI_AGAIN), Chromium's+// (ERR_INTERNET_DISCONNECTED), undici's (UND_ERR_*), and a 5xx. Provider+// codes are lower case, so they never match.+const TRANSPORT_CODE = /^(E[A-Z0-9_]+|UND_ERR_[A-Z0-9_]+|http_5\d\d)$/;++export function connectorErrorCopyKey(errorCode: string | null | undefined): ConnectorErrorCopyKey {+ if (!errorCode) return "generic";+ if (OWN_COPY.has(errorCode)) return errorCode as ConnectorErrorCopyKey;+ const alias = ALIASES.get(errorCode);+ if (alias) return alias;+ return TRANSPORT_CODE.test(errorCode) ? "network" : "generic";+}diff --git a/test/components/approvalCard.test.js b/test/components/approvalCard.test.jsindex 853fab9b7..c9c06e93c 100644--- a/test/components/approvalCard.test.js+++ b/test/components/approvalCard.test.js@@ -72,3 +72,49 @@ test("a sent card offers Open", async (t) => {assert.match(markup, /connectors\.approval\.sent/);assert.match(markup, /connectors\.approval\.open/);});++test("a pending card after a failed policy check says why nothing was sent", async (t) => {+ const markup = await renderCard(t, {+ key: "m1::call-1",+ messageId: "m1",+ toolCallId: "call-1",+ actionId: "a1",+ connectorId: "slack",+ preview: PREVIEW,+ draft: { body: PREVIEW.body },+ state: "pending",+ notice: "policy_retry",+ });+ assert.match(markup, /aria-live="polite"[^>]*>(?:(?!<\/div>).)*connectors\.approval\.policyRetry/);+ assert.match(markup, /connectors\.approval\.send/);+});++test("every outcome is announced from one live region", async (t) => {+ for (const [state, textKey] of [+ ["committing", "sending"],+ ["sent", "sent"],+ ["failed", "failed"],+ ["unknown", "unknown"],+ ["cancelled", "cancelled"],+ ["not_sent", "notSent"],+ ]) {+ const markup = await renderCard(t, {+ key: "m1::call-1",+ messageId: "m1",+ toolCallId: "call-1",+ actionId: "a1",+ connectorId: "slack",+ preview: PREVIEW,+ draft: { body: PREVIEW.body },+ state,+ message: "reason",+ });+ assert.match(+ markup,+ new RegExp(+ `role="status" aria-live="polite"[^>]*>(?:(?!</div>).)*connectors\\.approval\\.${textKey}`+ ),+ state+ );+ }+});diff --git a/test/components/approvalCardFailureCopy.test.js b/test/components/approvalCardFailureCopy.test.jsnew file mode 100644index 000000000..5402209b3--- /dev/null+++ b/test/components/approvalCardFailureCopy.test.js@@ -0,0 +1,95 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const { createElement } = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// Kept out of approvalCard.test.js: this test initializes i18next, and+// i18next is one shared SSR module instance, so running it in the same file+// as approvalCard.test.js's raw-key tests would make their outcome depend on+// test order.+async function loadTranslatedCard(t) {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-approval-card-errors-test-",+ mockModules: {+ "/ui/button": `+ import React from "react";+ export function Button(props) { return React.createElement("button", props); }+ `,+ },+ });+ const [{ default: i18next }, { initReactI18next }] = await Promise.all([+ vite.ssrLoadModule("i18next"),+ vite.ssrLoadModule("react-i18next"),+ ]);+ if (!i18next.isInitialized) {+ const translation = JSON.parse(+ fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")+ );+ await i18next.use(initReactI18next).init({+ lng: "en",+ resources: { en: { translation } },+ interpolation: { escapeValue: false },+ });+ }+ const { ApprovalCard } = await vite.ssrLoadModule("/components/chat/ApprovalCard.tsx");+ return ApprovalCard;+}++const failed = (errorCode, message, destinationLabel = "#eng") => ({+ key: "m1::call-1",+ messageId: "m1",+ toolCallId: "call-1",+ actionId: "a1",+ connectorId: "slack",+ preview: {+ verbKey: "slackPost",+ destinationLabel,+ accountLabel: "chad",+ workspaceLabel: "Acme",+ body: "hi",+ },+ draft: { body: "hi" },+ state: "failed",+ errorCode,+ message,+});++// The connector's message is English written for the model; the card never+// shows it, whatever the code.+const MODEL_TEXT = "MODEL-ONLY TEXT";++test("a failed card explains every failure in translated copy, never the connector's message", async (t) => {+ const ApprovalCard = await loadTranslatedCard(t);+ const render = (errorCode, destinationLabel) =>+ renderToStaticMarkup(+ createElement(ApprovalCard, { entry: failed(errorCode, MODEL_TEXT, destinationLabel) })+ );++ for (const [errorCode, expected, destinationLabel] of [+ ["not_in_channel", /Couldn't send: You're not a member of #eng\./],+ ["invalid_auth", /Slack needs to be reconnected in Settings\./],+ ["token_revoked", /Slack needs to be reconnected in Settings\./],+ ["ratelimited", /Slack is busy\. Try again shortly\./],+ ["ENOTFOUND", /Slack couldn't be reached\. Nothing was sent\./],+ ["network_error", /Slack couldn't be reached\. Nothing was sent\./],+ ["timeout", /Slack couldn't be reached\. Nothing was sent\./],+ ["credential_save_failed", /couldn't be saved on this computer\. Nothing was sent\./],+ [+ "user_not_found",+ /The direct message to Gabe Smith couldn't be opened\. Nothing was sent\./,+ "Gabe Smith",+ ],+ ["restricted_action_read_only_channel", /#eng is read-only or restricted for you\./],+ ["weird_code", /Couldn't send: Something went wrong\. Nothing was sent\./],+ [undefined, /Something went wrong\. Nothing was sent\./],+ ]) {+ const markup = render(errorCode, destinationLabel);+ assert.match(markup, expected, String(errorCode));+ assert.doesNotMatch(markup, /MODEL-ONLY TEXT/, String(errorCode));+ assert.doesNotMatch(markup, /connectors\.approval/, String(errorCode));+ }+});diff --git a/test/components/approvalCardKeyboard.test.js b/test/components/approvalCardKeyboard.test.jsnew file mode 100644index 000000000..d187e7bd6--- /dev/null+++ b/test/components/approvalCardKeyboard.test.js@@ -0,0 +1,171 @@+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;+ },+ });+}++function keyDown(element, key) {+ const event = {+ type: "keydown",+ key,+ bubbles: true,+ defaultPrevented: false,+ cancelBubble: false,+ preventDefault() {+ this.defaultPrevented = true;+ },+ stopPropagation() {+ this.cancelBubble = true;+ },+ };+ element.dispatchEvent(event);+ return event;+}++// 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;+}++const textarea = (root) => findElement(root, (element) => element.tagName === "TEXTAREA");++async function mountPendingCard(t) {+ let root = null;+ let store;+ let key;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ // A test that never Sends or Cancels leaves the entry pending, which+ // leaves the store's approval-TTL timer running and the process alive.+ // Registered before installBrowserGlobals's own cleanup, which removes+ // window (and with it window.electronAPI) below.+ t.after(() => {+ if (store?.useConnectorApprovalStore.getState().entries[key]?.state === "pending") {+ store.cancelApproval(key);+ }+ });+ const calls = { commit: [], cancel: [] };+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorPrepare: async () => ({+ status: "ready",+ actionId: "a1",+ preview: {+ verbKey: "default",+ destinationLabel: "#eng",+ accountLabel: "chad",+ body: "Original text",+ },+ }),+ connectorCommit: async (actionId, edits) => {+ calls.commit.push({ actionId, edits });+ return { state: "sent", url: "https://slack.test/p/1" };+ },+ connectorCancel: async (actionId, reason) => {+ calls.cancel.push({ actionId, reason });+ return { cancelled: true };+ },+ },+ },+ });+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-approval-card-keyboard-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); }+ `,+ },+ });+ 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: {} });+ key = store.approvalKey("m1", "call-1");++ function Harness() {+ const entry = store.useConnectorApprovalStore((state) => state.entries[key]);+ 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)));++ let toolResult;+ await React.act(async () => {+ toolResult = runApprovalAction(+ {+ messageId: "m1",+ toolCallId: "call-1",+ signal: new AbortController().signal,+ onApprovalRequested() {},+ onHoldDelivery() {},+ },+ "slack",+ "send_message",+ { destination: "#eng", text: "Original text" }+ );+ await new Promise((resolve) => setImmediate(resolve));+ });+ return { container, store, key, calls, toolResult: () => toolResult };+}++test("Esc in the text field ends editing, keeps the draft, and never reaches the panel", async (t) => {+ const { container, store, key, calls } = await mountPendingCard(t);+ await React.act(async () => click(button(container, "connectors.approval.edit")));+ await React.act(async () => store.updateApprovalDraft(key, { body: "Edited text" }));++ let event;+ await React.act(async () => {+ event = keyDown(textarea(container), "Escape");+ });++ // The panel listens on document, above React's root: a stopped event never gets there.+ assert.equal(event.cancelBubble, true);+ assert.ok(!textarea(container), "edit mode ended");+ assert.match(container.textContent, /Edited text/);+ assert.equal(store.useConnectorApprovalStore.getState().entries[key].state, "pending");+ assert.deepEqual(calls.cancel, []);+});++test("Send while editing sends the edit, leaves edit mode and keeps focus on the card", async (t) => {+ const { container, store, key, calls, toolResult } = await mountPendingCard(t);+ await React.act(async () => click(button(container, "connectors.approval.edit")));+ await React.act(async () => store.updateApprovalDraft(key, { body: "Edited text" }));++ await React.act(async () => click(button(container, "connectors.approval.send")));+ await toolResult();++ assert.deepEqual(calls.commit, [{ actionId: "a1", edits: { body: "Edited text" } }]);+ assert.ok(!textarea(container), "no editable field after Send");+ assert.equal(globalThis.document.activeElement?.getAttribute("data-approval-card"), key);+});diff --git a/test/components/approvalFlow.test.js b/test/components/approvalFlow.test.jsindex 02cb34f34..42e66ebff 100644--- a/test/components/approvalFlow.test.js+++ b/test/components/approvalFlow.test.js@@ -79,7 +79,9 @@ async function mountApprovalTurn(t) {store.useConnectorApprovalStore.setState({ entries: {} });function Harness() {- const entry = store.useConnectorApprovalStore((state) => state.entries["call-1"]);+ const entry = store.useConnectorApprovalStore(+ (state) => state.entries[store.approvalKey("m1", "call-1")]+ );return entry ? React.createElement(ApprovalCard, { entry }) : null;}const { createRoot } = require("react-dom/client");@@ -91,6 +93,7 @@ async function mountApprovalTurn(t) {await React.act(async () => {toolResult = runApprovalAction({+ messageId: "m1",toolCallId: "call-1",signal: controller.signal,onApprovalRequested() {},@@ -115,7 +118,9 @@ test("Edit, change, Done editing, Send: the reviewed text is what gets sent", asassert.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 () =>+ store.updateApprovalDraft(store.approvalKey("m1", "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")));@@ -131,7 +136,9 @@ 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 () =>+ store.updateApprovalDraft(store.approvalKey("m1", "call-1"), { body: "Edited text" })+ );await React.act(async () => click(button(container, "connectors.approval.send")));await toolResult;diff --git a/test/components/chatMessageApprovals.test.js b/test/components/chatMessageApprovals.test.jsnew file mode 100644index 000000000..599a2772e--- /dev/null+++ b/test/components/chatMessageApprovals.test.js@@ -0,0 +1,81 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { createRoot } = require("react-dom/client");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");++const PREVIEW = {+ verbKey: "default",+ destinationLabel: "#eng",+ accountLabel: "chad",+ body: "Hello team",+};++function hasApprovalCard(container) {+ return Boolean(+ findElement(container, (element) => element.getAttribute?.("data-approval-card") != null)+ );+}++// zustand's react binding renders the SSR snapshot (api.getInitialState(),+// frozen at module load) under renderToStaticMarkup, so setting state on the+// real store before an SSR render never reaches a reactive selector. Mount+// with createRoot instead, like approvalFlow.test.js, to see live state.+test("a card shows only on the message whose tool call requested it", 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-chat-message-approvals-test-",+ mockModules: {+ "/ui/button": `+ import React from "react";+ export function Button(props) { return React.createElement("button", props); }+ `,+ },+ });+ const store = await vite.ssrLoadModule("/stores/connectorApprovalStore.ts");+ const { ChatMessage } = await vite.ssrLoadModule("/components/chat/ChatMessage.tsx");+ const key = store.approvalKey("msg-new", "call-1");+ store.useConnectorApprovalStore.setState({+ entries: {+ [key]: {+ key,+ messageId: "msg-new",+ toolCallId: "call-1",+ actionId: "a1",+ connectorId: "slack",+ preview: PREVIEW,+ draft: { body: PREVIEW.body },+ state: "pending",+ },+ },+ });+ const toolCalls = [+ { id: "call-1", name: "slack_send_message", arguments: "{}", status: "completed" },+ ];+ root = createRoot(container);+ const render = async (messageId) => {+ const element = React.createElement(ChatMessage, {+ messageId,+ role: "assistant",+ content: "",+ isStreaming: false,+ toolCalls,+ });+ await React.act(async () => root.render(element));+ };++ await render("msg-new");+ assert.ok(hasApprovalCard(container), "the message whose tool call requested it shows a card");++ await render("msg-old");+ assert.ok(+ !hasApprovalCard(container),+ "a different message reusing the same tool-call id shows no card"+ );+});diff --git a/test/components/connectorsSection.test.js b/test/components/connectorsSection.test.jsindex dfb6e022e..d70a34ff5 100644--- a/test/components/connectorsSection.test.js+++ b/test/components/connectorsSection.test.js@@ -50,6 +50,12 @@ const MOCKS = {import React from "react";export function Button(props) { return React.createElement("button", props); }`,+ "/stores/connectorStatusStore": `+ export function useConnectorStatusStore(selector) {+ return selector({ statuses: globalThis.__connectorStatuses ?? {} });+ }+ export async function ensureConnectorStatus() {}+ `,};const usage = (isSubscribed) => ({@@ -59,18 +65,47 @@ const usage = (isSubscribed) => ({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;+const SLACK = {+ id: "slack",+ connected: true,+ accountLabel: "chad",+ workspaceLabel: "Acme Test",+ needsReconnect: false,+};+const count = (markup, pattern) => (markup.match(pattern) ?? []).length;+// This harness's DOM nodes only expose textContent (no innerHTML), so a plain+// string like "connectors.slack.connect" can't be told apart from a longer+// key that starts with it ("connectors.slack.connecting",+// "…connectedAs"). Finding the actual <button> is unambiguous.+const buttonWithText = (container, text) =>+ findElement(container, (node) => node.tagName === "BUTTON" && node.textContent === text);++// `usageState`/`subscribedFlag` are the review round's shape; `isPaid` is a+// shortcut for tests that don't care about the usage/flag distinction. 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,+ isPaid,+ statuses = {},+ } = {}+) {+ globalThis.__usage = usageState ?? usage(Boolean(isPaid));+ globalThis.__subscribedFlag = isPaid ?? subscribedFlag;globalThis.__connectorsBlocked = blocked;globalThis.__connectorsAllowed = allowed;+ globalThis.__connectorStatuses = statuses;t.after(() => {delete globalThis.__usage;delete globalThis.__subscribedFlag;delete globalThis.__connectorsBlocked;delete globalThis.__connectorsAllowed;+ delete globalThis.__connectorStatuses;});}@@ -243,3 +278,77 @@ test("recent receipts name the recipient, or the action when a quit cut it shortassert.match(items[0], /^connectors\.recent\.actions\.email_draft/);assert.match(items[1], /^connectors\.recent\.unlabeledActions\.email_draft/);});++test("a connected Slack shows the account and Disconnect", async (t) => {+ const container = await renderSection(t, {+ isPaid: true,+ blocked: false,+ statuses: { slack: SLACK },+ });+ const markup = container.textContent;+ assert.match(markup, /connectors\.slack\.title/);+ assert.match(markup, /connectors\.slack\.connectedAs/);+ assert.match(markup, /connectors\.slack\.disconnect/);+ assert.equal(buttonWithText(container, "connectors.slack.connect"), null);+});++// Each of the pairs below is one scenario from the brief, split into two+// tests: this harness's globals (window/document) are installed and torn+// down per-test in registration order, so a second renderSection() call in+// the same test tears down the first call's globals out from under its+// still-pending root.unmount() cleanup.+test("a disconnected Slack offers Connect", async (t) => {+ const disconnected = await renderSection(t, { isPaid: true, blocked: false });+ assert.ok(buttonWithText(disconnected, "connectors.slack.connect"));+ assert.match(disconnected.textContent, /connectors\.slack\.description/);+});++test("a stale login offers Reconnect and Disconnect", async (t) => {+ const stale = await renderSection(t, {+ isPaid: true,+ blocked: false,+ statuses: { slack: { ...SLACK, needsReconnect: true } },+ });+ const staleMarkup = stale.textContent;+ assert.match(staleMarkup, /connectors\.slack\.reconnect/);+ assert.match(staleMarkup, /connectors\.slack\.disconnect/);+ assert.match(staleMarkup, /connectors\.slack\.needsReconnect/);+});++test("free users with no login see Upgrade for both rows and no Connect", async (t) => {+ const none = await renderSection(t, { isPaid: false, blocked: false });+ assert.equal(count(none.textContent, /integrations\.api\.viewPlans/g), 2);+ assert.equal(buttonWithText(none, "connectors.slack.connect"), null);+});++test("free users can always disconnect a login they have", async (t) => {+ const lapsed = await renderSection(t, {+ isPaid: false,+ blocked: false,+ statuses: { slack: SLACK },+ });+ assert.match(lapsed.textContent, /connectors\.slack\.disconnect/);+ assert.equal(+ count(lapsed.textContent, /integrations\.api\.viewPlans/g),+ 1,+ "only the email row's Upgrade"+ );+});++test("an org that turned connectors off still lets the user remove a login", async (t) => {+ const connected = await renderSection(t, {+ isPaid: true,+ blocked: true,+ statuses: { slack: SLACK },+ });+ const connectedMarkup = connected.textContent;+ assert.match(connectedMarkup, /connectors\.policyOff/);+ assert.match(connectedMarkup, /connectors\.slack\.disconnect/);+ assert.equal(buttonWithText(connected, "connectors.slack.connect"), null);+ assert.doesNotMatch(connectedMarkup, /connectors\.slack\.reconnect/);+});++test("an org that turned connectors off hides the Slack row when there's no login", async (t) => {+ const none = await renderSection(t, { isPaid: true, blocked: true });+ assert.doesNotMatch(none.textContent, /connectors\.slack\.title/);+});diff --git a/test/components/slackConnectorRow.test.js b/test/components/slackConnectorRow.test.jsnew file mode 100644index 000000000..59a277e30--- /dev/null+++ b/test/components/slackConnectorRow.test.js@@ -0,0 +1,259 @@+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;+}++test("Connect runs the browser flow once and says why it failed", async (t) => {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ const connects = [];+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorConnect: async (connectorId) => {+ connects.push(connectorId);+ return { status: "failed", errorCode: "oauth_denied" };+ },+ connectorStatus: async () => [],+ onConnectorStatusChanged: () => () => {},+ connectorRecentActions: async () => [],+ },+ },+ });+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-slack-connector-row-test-",+ mockModules: {+ "/ui/button": `+ import React from "react";+ export function Button(props) { return React.createElement("button", props); }+ `,+ "/ui/SettingsSection": `+ import React from "react";+ export const SettingsPanelRow = ({ children }) => React.createElement("div", null, children);+ export const SettingsPanel = SettingsPanelRow;+ `,+ },+ });+ const { SlackConnectorRow } = await vite.ssrLoadModule(+ "/components/connectors/SlackConnectorRow.tsx"+ );+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ await React.act(async () =>+ root.render(+ React.createElement(SlackConnectorRow, { isPaid: true, blockedByOrg: false, onUpgrade() {} })+ )+ );++ await React.act(async () => click(button(container, "connectors.slack.connect")));++ assert.deepEqual(connects, ["slack"]);+ assert.match(container.textContent, /connectors\.slack\.errors\.oauth_denied/);+});++function deferred() {+ let resolve;+ const promise = new Promise((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++// A disconnected row whose Connect answers with `connectorConnect`.+async function renderDisconnectedRow(t, { connectorConnect }) {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorConnect,+ connectorStatus: async () => [],+ onConnectorStatusChanged: () => () => {},+ connectorRecentActions: async () => [],+ },+ },+ });+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-slack-connector-row-reconnect-test-",+ mockModules: {+ "/ui/button": `+ import React from "react";+ export function Button(props) { return React.createElement("button", props); }+ `,+ "/ui/SettingsSection": `+ import React from "react";+ export const SettingsPanelRow = ({ children }) => React.createElement("div", null, children);+ export const SettingsPanel = SettingsPanelRow;+ `,+ },+ });+ const { SlackConnectorRow } = await vite.ssrLoadModule(+ "/components/connectors/SlackConnectorRow.tsx"+ );+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ await React.act(async () =>+ root.render(+ React.createElement(SlackConnectorRow, { isPaid: true, blockedByOrg: false, onUpgrade() {} })+ )+ );+ return container;+}++test("Connect stays available while the browser is open, and a new attempt replaces the old", async (t) => {+ const attempts = [];+ const container = await renderDisconnectedRow(t, {+ connectorConnect: () => {+ const attempt = deferred();+ attempts.push(attempt);+ return attempt.promise;+ },+ });++ await React.act(async () => click(button(container, "connectors.slack.connect")));+ assert.match(container.textContent, /connectors\.slack\.connecting/);+ await React.act(async () => click(button(container, "connectors.slack.connect")));+ assert.equal(attempts.length, 2, "an abandoned sign-in doesn't lock Connect");++ // Main cancels the first attempt for the second one.+ await React.act(async () =>+ attempts[0].resolve({ status: "failed", errorCode: "oauth_cancelled" })+ );+ assert.doesNotMatch(container.textContent, /connectors\.slack\.errors\./);+ assert.match(container.textContent, /connectors\.slack\.connecting/);++ await React.act(async () => attempts[1].resolve({ status: "failed", errorCode: "oauth_denied" }));+ assert.match(container.textContent, /connectors\.slack\.errors\.oauth_denied/);+ assert.doesNotMatch(container.textContent, /connectors\.slack\.connecting/);+});++test("a Connect cancelled by another window's attempt shows no error", async (t) => {+ const container = await renderDisconnectedRow(t, {+ connectorConnect: async () => ({ status: "failed", errorCode: "oauth_cancelled" }),+ });++ await React.act(async () => click(button(container, "connectors.slack.connect")));++ assert.doesNotMatch(container.textContent, /connectors\.slack\.errors\./);+ assert.doesNotMatch(container.textContent, /connectors\.slack\.connecting/);+});++// Shared setup for the Disconnect tests below: a connected row (so the+// Disconnect button renders), with `connectorDisconnect` swapped per test.+async function renderConnectedRow(t, { connectorDisconnect }) {+ let root = null;+ t.after(async () => {+ if (root) await React.act(async () => root.unmount());+ });+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorDisconnect,+ connectorStatus: async () => [+ {+ id: "slack",+ connected: true,+ accountLabel: "chad",+ workspaceLabel: "Acme Test",+ needsReconnect: false,+ },+ ],+ onConnectorStatusChanged: () => () => {},+ connectorRecentActions: async () => [],+ },+ },+ });+ const container = installInteractiveDom(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-slack-connector-row-disconnect-test-",+ mockModules: {+ "/ui/button": `+ import React from "react";+ export function Button(props) { return React.createElement("button", props); }+ `,+ "/ui/SettingsSection": `+ import React from "react";+ export const SettingsPanelRow = ({ children }) => React.createElement("div", null, children);+ export const SettingsPanel = SettingsPanelRow;+ `,+ },+ });+ const { SlackConnectorRow } = await vite.ssrLoadModule(+ "/components/connectors/SlackConnectorRow.tsx"+ );+ const { createRoot } = require("react-dom/client");+ root = createRoot(container);+ await React.act(async () =>+ root.render(+ React.createElement(SlackConnectorRow, { isPaid: true, blockedByOrg: false, onUpgrade() {} })+ )+ );+ // Let the status load fired from the row's mount effect resolve and commit+ // (so `connected` flips true and the Disconnect button renders) before+ // interacting with the row.+ await React.act(async () => {});+ return container;+}++test("Disconnect shows the row's copy for an unavailable result", async (t) => {+ const disconnects = [];+ const container = await renderConnectedRow(t, {+ connectorDisconnect: async (connectorId) => {+ disconnects.push(connectorId);+ return { status: "unavailable", reason: "signed_out" };+ },+ });++ await React.act(async () => click(button(container, "connectors.slack.disconnect")));++ assert.deepEqual(disconnects, ["slack"]);+ assert.match(container.textContent, /connectors\.slack\.errors\.signed_out/);+});++test("a Disconnect click that succeeds shows no error", async (t) => {+ const disconnects = [];+ const container = await renderConnectedRow(t, {+ connectorDisconnect: async (connectorId) => {+ disconnects.push(connectorId);+ return { status: "disconnected" };+ },+ });++ await React.act(async () => click(button(container, "connectors.slack.disconnect")));++ assert.deepEqual(disconnects, ["slack"]);+ assert.doesNotMatch(container.textContent, /connectors\.slack\.errors\./);+});diff --git a/test/helpers/assistantPanel.test.js b/test/helpers/assistantPanel.test.jsindex 339d8aae6..ddea64887 100644--- a/test/helpers/assistantPanel.test.js+++ b/test/helpers/assistantPanel.test.js@@ -98,6 +98,9 @@ async function renderAssistantPanel(export function useConnectorApprovalStore(selector) {return selector({ entries: globalThis.__assistantPanelApprovals || {} });}+ export function approvalKey(messageId, toolCallId) {+ return messageId + "::" + toolCallId;+ }`,"/chat/ApprovalCard": `import React from "react";@@ -740,7 +743,9 @@ test("a pending approval shows in the panel and replaces the tool overlay", asynagentState: "tool-executing",activeToolName: "slack_send_message",approvals: {- "call-1": {+ "assistant-1::call-1": {+ key: "assistant-1::call-1",+ messageId: "assistant-1",toolCallId: "call-1",actionId: "a1",connectorId: "slack",diff --git a/test/helpers/connectorActionsDatabase.test.js b/test/helpers/connectorActionsDatabase.test.jsindex a98714cc9..7f61cc300 100644--- a/test/helpers/connectorActionsDatabase.test.js+++ b/test/helpers/connectorActionsDatabase.test.js@@ -234,6 +234,46 @@ test("listRecent respects the limit", (t) => {db.db.close();});+test("receipts list only for their account and go with it on account deletion", (t) => {+ const db = createDb(t);+ if (!db) return;+ const log = createActionLog(db);+ db.setActiveAccountId("acct-a");++ log.insert({+ id: "a1",+ accountId: "acct-a",+ connector: "slack",+ action: "send_message",+ kind: "approval",+ destinationLabel: "#eng",+ state: "sent",+ });+ log.insert({+ id: "b1",+ accountId: "acct-b",+ connector: "slack",+ action: "send_message",+ kind: "approval",+ destinationLabel: "#ops",+ state: "sent",+ });++ assert.deepEqual(+ log.listRecent("slack", 10, "acct-a").map((row) => row.id),+ ["a1"]+ );+ assert.deepEqual(log.listRecent("slack", 10, null), []);++ db.deleteAccountData("acct-a");+ assert.deepEqual(log.listRecent("slack", 10, "acct-a"), []);+ assert.deepEqual(+ log.listRecent("slack", 10, "acct-b").map((row) => row.id),+ ["b1"]+ );+ db.db.close();+});+test("contact lookup sources cover meetings, synced contacts and the user's accounts", (t) => {const db = createDb(t);if (!db) return;diff --git a/test/helpers/connectors/connectorCredentials.test.js b/test/helpers/connectors/connectorCredentials.test.jsnew file mode 100644index 000000000..1058afe6c--- /dev/null+++ b/test/helpers/connectors/connectorCredentials.test.js@@ -0,0 +1,90 @@+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 load = () => import("../../../src/helpers/connectors/connectorCredentials.js");+const loadStore = () => import("../../../src/helpers/connectors/credentialStore.js");++const fakeCrypto = {+ isAvailable: () => true,+ encrypt: (text) => Buffer.from(`enc:${Buffer.from(text).toString("base64")}`),+ decrypt: (buf) => ({+ value: Buffer.from(buf.toString().slice(4), "base64").toString("utf8"),+ needsReencrypt: false,+ }),+};+const silentLogger = { info() {}, warn() {}, error() {} };++async function setup(initialAccount = "acct-a") {+ const [{ createConnectorCredentials }, { createCredentialStore }] = await Promise.all([+ load(),+ loadStore(),+ ]);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-connector-credentials-"));+ let accountId = initialAccount;+ const credentials = createConnectorCredentials({+ store: createCredentialStore({ dir, secretCrypto: fakeCrypto, logger: silentLogger }),+ getAccountId: () => accountId,+ });+ return { credentials, dir, switchTo: (next) => (accountId = next) };+}++const code = (expected) => (error) => error.code === expected;++test("each OpenWhispr account has its own login slot", async () => {+ const { credentials, dir } = await setup();++ credentials.replace("acct-a", "slack", { accessToken: "a" }, 0);+ credentials.replace("acct-b", "slack", { accessToken: "b" }, 0);++ assert.equal(credentials.read("acct-a", "slack").credential.accessToken, "a");+ assert.equal(credentials.read("acct-b", "slack").credential.accessToken, "b");+ const files = fs.readdirSync(dir);+ assert.equal(files.length, 2);+ assert.ok(+ files.every((name) => /^slack-[0-9a-f]{24}\.bin$/.test(name)),+ "account ids never appear in file names"+ );+});++test("a write from a stale generation is refused and changes nothing", async () => {+ const { credentials } = await setup();+ const first = credentials.replace("acct-a", "slack", { accessToken: "a" }, 0);++ assert.throws(+ () => credentials.replace("acct-a", "slack", { accessToken: "x" }, 0),+ code("connection_changed")+ );+ assert.throws(+ () => credentials.save("acct-a", "slack", { accessToken: "x" }, first - 1),+ code("connection_changed")+ );+ assert.equal(credentials.read("acct-a", "slack").credential.accessToken, "a");++ credentials.save("acct-a", "slack", { accessToken: "refreshed" }, first);+ assert.deepEqual(credentials.read("acct-a", "slack"), {+ credential: { accessToken: "refreshed" },+ generation: first,+ });++ credentials.clear("acct-a", "slack", first);+ assert.equal(credentials.read("acct-a", "slack"), null);+ assert.throws(+ () => credentials.save("acct-a", "slack", { accessToken: "late" }, first),+ code("connection_changed")+ );+ assert.equal(credentials.read("acct-a", "slack"), null);+});++test("no account means no login and no writes", async () => {+ const { credentials, switchTo } = await setup();+ switchTo(null);+ assert.equal(credentials.activeAccountId(), null);+ assert.equal(credentials.read(null, "slack"), null);+ assert.throws(+ () => credentials.replace(null, "slack", { accessToken: "a" }, 0),+ code("signed_out")+ );+});diff --git a/test/helpers/connectors/connectorIpc.test.js b/test/helpers/connectors/connectorIpc.test.jsindex f41011c6d..15882296e 100644--- a/test/helpers/connectors/connectorIpc.test.js+++ b/test/helpers/connectors/connectorIpc.test.js@@ -33,6 +33,45 @@ function fakeManager() {};}+test("connect needs policy; disconnect never does", async () => {+ const { registerConnectorIpc } = await load();+ const ipcMain = fakeIpcMain();+ const calls = [];+ const manager = {+ ...fakeManager(),+ connect: async (...args) => {+ calls.push(["connect", ...args]);+ return { status: "connected", accountLabel: "chad", workspaceLabel: "Acme" };+ },+ disconnect: async (...args) => {+ calls.push(["disconnect", ...args]);+ return { status: "disconnected" };+ },+ };+ let policyCalls = 0;+ registerConnectorIpc({+ ipcMain,+ manager,+ getPolicyState: async () => {+ policyCalls += 1;+ return "allowed";+ },+ });++ await ipcMain.handlers.get("connector-connect")({}, "slack");+ await ipcMain.handlers.get("connector-disconnect")({}, "slack");++ assert.deepEqual(calls, [+ ["connect", "slack", "allowed"],+ ["disconnect", "slack"],+ ]);+ assert.equal(policyCalls, 1);+ assert.deepEqual(await ipcMain.handlers.get("connector-connect")({}, 7), {+ status: "unavailable",+ reason: "invalid_request",+ });+});+test("each channel reaches the manager, with policy only where something can leave", async () => {const { registerConnectorIpc } = await load();const ipcMain = fakeIpcMain();@@ -140,29 +179,101 @@ test("malformed arguments never reach the manager", async () => {assert.equal(manager.calls.length, 0);});-test("the policy resolver allows signed-out users and maps snapshots", async () => {+test("signed out refuses, a lookup that can't tell fails closed, snapshots still map", async () => {const { createConnectorPolicyResolver } = await load();+ const neverCalled = async () => {+ throw new Error("must not be called");+ };+const signedOut = createConnectorPolicyResolver({getAuthHeader: async () => ({}),- getPolicy: async () => {- throw new Error("must not be called");- },+ getPolicy: neverCalled,+ getAuthGeneration: () => 1,+ });+ assert.equal(await signedOut({}), "signed_out");++ const cannotTell = createConnectorPolicyResolver({+ getAuthHeader: async () => null,+ getPolicy: neverCalled,getAuthGeneration: () => 1,});- assert.equal(await signedOut({}), "allowed");+ assert.equal(await cannotTell({}), "unavailable");const blocked = createConnectorPolicyResolver({getAuthHeader: async () => ({ Authorization: "Bearer t" }),getPolicy: async () => ({success: true,managed: true,- policy: { features: { connectorsEnabled: false } },+ policy: { features: { agentEnabled: true, connectorsEnabled: false } },}),getAuthGeneration: () => 1,});assert.equal(await blocked({}), "blocked");});+test("the auth generation is read before the header lookup", async () => {+ const { createConnectorPolicyResolver } = await load();+ let generation = 1;+ const expected = [];+ const resolver = createConnectorPolicyResolver({+ // A sign-in lands while the header lookup is running.+ getAuthHeader: async () => {+ generation = 2;+ return { Authorization: "Bearer new-session" };+ },+ getPolicy: async ({ expectedAuthGeneration }) => {+ expected.push(expectedAuthGeneration);+ return { success: false, status: "error", code: "AUTH_CONTEXT_CHANGED" };+ },+ getAuthGeneration: () => generation,+ });++ assert.equal(await resolver({}), "unavailable");+ assert.deepEqual(expected, [1]);+});++test("a slow refresh still falls back to the cached verdict for the same request", async () => {+ const { createConnectorPolicyResolver } = await load();+ let generation = 4;+ const peeked = [];+ const resolver = createConnectorPolicyResolver({+ getAuthHeader: async () => {+ generation = 5;+ return { Authorization: "Bearer t" };+ },+ getPolicy: () => new Promise(() => {}),+ peekPolicy: (request) => {+ peeked.push(request.expectedAuthGeneration);+ return { success: true, managed: false, policy: null };+ },+ getAuthGeneration: () => generation,+ timeoutMs: 20,+ });++ assert.equal(await resolver({}), "allowed");+ assert.deepEqual(peeked, [4]);+});++test("the auth lookup never reads a destroyed window as signed out", async () => {+ const { createConnectorAuthLookup } = await load();+ const live = { isDestroyed: () => false };+ const gone = { isDestroyed: () => true };+ const lookup = (hasToken, win) =>+ createConnectorAuthLookup({+ hasBearerToken: () => hasToken,+ windowFor: () => win,+ authHeaderFor: async (w) => {+ if (hasToken) return { Authorization: "Bearer t" };+ return w === live ? {} : { Cookie: "session=1" };+ },+ });++ assert.deepEqual(await lookup(true, null)({}), { Authorization: "Bearer t" });+ assert.equal(await lookup(false, null)({}), null);+ assert.equal(await lookup(false, gone)({}), null);+ assert.deepEqual(await lookup(false, live)({}), {});+});+test("a policy lookup that hangs or throws fails closed", async () => {const { createConnectorPolicyResolver } = await load();const hanging = createConnectorPolicyResolver({diff --git a/test/helpers/connectors/connectorManager.test.js b/test/helpers/connectors/connectorManager.test.jsindex 4cad196c0..0acee56e6 100644--- a/test/helpers/connectors/connectorManager.test.js+++ b/test/helpers/connectors/connectorManager.test.js@@ -1,6 +1,8 @@const test = require("node:test");const assert = require("node:assert/strict");+const { memoryCredentials } = require("./slackFixtures");+const loadManager = () => import("../../../src/helpers/connectors/connectorManager.js");const loadPending = () => import("../../../src/helpers/connectors/pendingActions.js");@@ -8,6 +10,7 @@ const silentLogger = { info() {}, warn() {}, error() {} };const ACCOUNT = "account-a";const ALLOWED = { policyState: "allowed", accountId: ACCOUNT };+const SIGNED_OUT = { policyState: "signed_out", accountId: null };function deferred() {let resolve;@@ -73,8 +76,8 @@ function fakeConnector(overrides = {}) {async getBinding() {return binding;},- async prepare(action, args) {- calls.prepare.push({ action, args });+ async prepare(action, args, context) {+ calls.prepare.push({ action, args, context });return {status: "ready",payload: { channel: "C1", text: args.text },@@ -86,8 +89,8 @@ function fakeConnector(overrides = {}) {},};},- async commit(action, payload, edits) {- calls.commit.push({ action, payload, edits });+ async commit(action, payload, edits, context) {+ calls.commit.push({ action, payload, edits, context });return { state: "sent", url: "https://example.test/p/1" };},async runDirect(action, args, runtime) {@@ -105,7 +108,7 @@ function fakeConnector(overrides = {}) {};}-async function setup(connectorOverrides, logOptions, pendingOptions) {+async function setup(connectorOverrides, logOptions, managerOptions = {}) {const [{ createConnectorManager }, { createPendingActions }] = await Promise.all([loadManager(),loadPending(),@@ -114,9 +117,11 @@ async function setup(connectorOverrides, logOptions, pendingOptions) {const log = fakeLog(logOptions);const manager = createConnectorManager({connectors: [fake.connector],- pendingActions: createPendingActions(pendingOptions),+ pendingActions: createPendingActions(),actionLog: log,logger: silentLogger,+ getAccountId: () => "acct-1",+ ...managerOptions,});return { manager, fake, log };}@@ -180,10 +185,10 @@ test("a blocked or unavailable policy refuses prepare, commit and runDirect", asconst { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);assert.deepEqual(- await manager.commit(actionId, {}, { policyState: "unavailable", accountId: ACCOUNT }),+ await manager.commit(actionId, {}, { policyState: "blocked", accountId: ACCOUNT }),{state: "not_sent",- reason: "policy_unavailable",+ reason: "policy_blocked",});assert.equal(fake.calls.commit.length, 0);@@ -204,6 +209,60 @@ test("a blocked or unavailable policy refuses prepare, commit and runDirect", as);});+test("an unavailable policy at Send leaves the action pending for another try", async () => {+ const { manager, fake, log } = await setup();+ const prepared = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);++ assert.deepEqual(+ await manager.commit(prepared.actionId, {}, { policyState: "unavailable", accountId: ACCOUNT }),+ {+ state: "not_sent",+ reason: "policy_unavailable",+ retryable: true,+ }+ );+ assert.equal(log.rows.get(prepared.actionId).state, "pending");+ assert.equal(fake.calls.commit.length, 0);++ const sent = await manager.commit(prepared.actionId, {}, ALLOWED);+ assert.equal(sent.state, "sent");+ assert.equal(fake.calls.commit.length, 1);+});++test("signed out refuses every action, and an unknown state fails closed", async () => {+ const { manager, fake, log } = await setup();++ assert.deepEqual(await manager.prepare("fake", "post", { text: "hi" }, SIGNED_OUT), {+ status: "unavailable",+ reason: "signed_out",+ });+ assert.deepEqual(await manager.runDirect("fake", "draft", {}, SIGNED_OUT, {}), {+ state: "unavailable",+ reason: "signed_out",+ });+ assert.deepEqual(+ await manager.prepare(+ "fake",+ "post",+ { text: "hi" },+ { policyState: "weird", accountId: ACCOUNT }+ ),+ {+ status: "unavailable",+ reason: "policy_unavailable",+ }+ );+ assert.equal(fake.calls.prepare.length + fake.calls.runDirect.length, 0);++ const prepared = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ assert.deepEqual(await manager.commit(prepared.actionId, {}, SIGNED_OUT), {+ state: "not_sent",+ reason: "signed_out",+ });+ assert.equal(log.rows.get(prepared.actionId).state, "cancelled");+ assert.equal(fake.calls.commit.length, 0);+});+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);@@ -246,6 +305,34 @@ test("a connector commit resolving undefined is recorded as unknown and never or});});+test("an unknown commit keeps its errorCode on the receipt and in the finish log", async () => {+ const logger = recordingLogger();+ const checkUrl = "https://app.slack.com/client/T1/C1";+ const { manager, log } = await setup(+ {+ async commit() {+ return { state: "unknown", errorCode: "internal_error", checkUrl };+ },+ },+ undefined,+ { logger }+ );+ const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);++ assert.deepEqual(await manager.commit(actionId, {}, ALLOWED), {+ state: "unknown",+ checkUrl,+ errorCode: "internal_error",+ });+ const row = log.rows.get(actionId);+ assert.equal(row.state, "unknown");+ assert.equal(row.errorCode, "internal_error");+ assert.equal(row.resultUrl, checkUrl);+ const finished = logger.lines.find((line) => line.args[0] === "connector action finished");+ assert.equal(finished.args[1].state, "unknown");+ assert.equal(finished.args[1].errorCode, "internal_error");+});+test("a connector commit resolving an unrecognized state is recorded as unknown", async () => {const { manager, log } = await setup({async commit() {@@ -363,7 +450,13 @@ test("a connector lookup that throws never hands its error to the renderer", asyreason: "not_connected",});assert.deepEqual(await bindingThrows.manager.status(), [- { id: "fake", connected: false, accountLabel: null },+ {+ id: "fake",+ connected: false,+ accountLabel: null,+ workspaceLabel: null,+ needsReconnect: false,+ },]);const { manager, fake, log } = await setup();@@ -380,9 +473,13 @@ test("a connector lookup that throws never hands its error to the renderer", asy});test("expired pending actions are swept and recorded as expired on the next call", async () => {- const { PENDING_TTL_MS } = await loadPending();+ const { PENDING_TTL_MS, createPendingActions } = await loadPending();let clock = 1_000;- const { manager, log } = await setup({}, {}, { now: () => clock });+ const { manager, log } = await setup(+ {},+ {},+ { pendingActions: createPendingActions({ now: () => clock }) }+ );const { actionId } = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);clock += PENDING_TTL_MS + 1;@@ -592,6 +689,712 @@ test("invalidate during a gated commit cancels the action without overwriting itassert.equal(row.errorCode, "connection_changed");});+function recordingLogger() {+ const lines = [];+ const capture =+ (level) =>+ (...args) =>+ lines.push({ level, args });+ return { lines, info: capture("info"), warn: capture("warn"), error: capture("error") };+}++test("connector logs carry error names and codes, never messages", async () => {+ const logger = recordingLogger();+ const leaky = () =>+ Object.assign(+ new Error("POST https://slack.com/api/chat.postMessage?token=xoxp-secret failed"),+ {+ code: "ECONNRESET",+ }+ );++ const throwing = await setup(+ {+ async prepare() {+ throw leaky();+ },+ async runDirect() {+ throw leaky();+ },+ },+ undefined,+ { logger }+ );+ await throwing.manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ await throwing.manager.runDirect("fake", "draft", {}, ALLOWED, {});++ const committing = await setup(+ {+ async commit() {+ throw leaky();+ },+ },+ undefined,+ { logger }+ );+ const prepared = await committing.manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ await committing.manager.commit(prepared.actionId, {}, ALLOWED);++ const logged = JSON.stringify(logger.lines);+ assert.doesNotMatch(logged, /xoxp-secret|slack\.com/);+ assert.match(logged, /ECONNRESET/);+});++const VALID_PREVIEW = {+ verbKey: "default",+ destinationLabel: "#eng",+ accountLabel: "chad",+ body: "hi",+};+const NOT_CONNECTED = {+ connected: false,+ accountLabel: null,+ workspaceLabel: null,+ needsReconnect: false,+};++test("a malformed prepare result fails closed with no card and no receipt", async () => {+ for (const bad of [+ undefined,+ null,+ { status: "ready" },+ { status: "ready", payload: {}, preview: { verbKey: "default" } },+ { status: "weird" },+ { status: "needs_clarification" },+ ]) {+ const { manager, log } = await setup({+ async prepare() {+ return bad;+ },+ });+ assert.deepEqual(await manager.prepare("fake", "post", { text: "hi" }, ALLOWED), {+ status: "failed",+ errorCode: "invalid_result",+ message: "Couldn't prepare that action.",+ });+ assert.equal(log.rows.size, 0);+ }++ // A failure the connector reported stays a failure, with the default code+ // and message filled in.+ const { manager, log } = await setup({+ async prepare() {+ return { status: "failed" };+ },+ });+ assert.deepEqual(await manager.prepare("fake", "post", { text: "hi" }, ALLOWED), {+ status: "failed",+ errorCode: "prepare_failed",+ message: "Couldn't prepare that action.",+ });+ assert.equal(log.rows.size, 0);+});++test("a well-formed clarification keeps only its string candidates", async () => {+ const { manager } = await setup({+ async prepare() {+ return {+ status: "needs_clarification",+ message: "Which one?",+ candidates: ["A", 7, null, "B"],+ };+ },+ });+ assert.deepEqual(await manager.prepare("fake", "post", { text: "hi" }, ALLOWED), {+ status: "needs_clarification",+ message: "Which one?",+ candidates: ["A", "B"],+ });+});++test("a status or binding that throws or is malformed reads as not connected", async () => {+ const throwing = await setup({+ async getStatus() {+ throw new Error("disk");+ },+ async getBinding() {+ throw new Error("disk");+ },+ });+ assert.deepEqual(await throwing.manager.status(), [{ id: "fake", ...NOT_CONNECTED }]);+ assert.deepEqual(await throwing.manager.prepare("fake", "post", { text: "hi" }, ALLOWED), {+ status: "unavailable",+ reason: "not_connected",+ });++ const malformed = await setup({+ async getStatus() {+ return { connected: "yes", accountLabel: 7 };+ },+ async getBinding() {+ return { accountId: 42 };+ },+ });+ assert.deepEqual((await malformed.manager.status())[0], { id: "fake", ...NOT_CONNECTED });+ assert.equal(+ (await malformed.manager.prepare("fake", "post", { text: "hi" }, ALLOWED)).reason,+ "not_connected"+ );+});++test("the main process expires a card nobody answered, but never a committing one", async () => {+ const { createPendingActions } = await loadPending();+ const clock = { now: 1_000 };+ let finishSend;+ const { manager, fake, log } = await setup(+ {+ commit(action, payload, edits) {+ fake.calls.commit.push({ action, payload, edits });+ return new Promise((resolve) => {+ finishSend = resolve;+ });+ },+ },+ undefined,+ { pendingActions: createPendingActions({ now: () => clock.now }) }+ );+ const abandoned = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ const sending = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ const inFlight = manager.commit(sending.actionId, {}, ALLOWED);+ // Let commit's own await (fetching the binding to guard beginCommit) settle+ // and flip the entry to "committing" before the sweep runs, the same way an+ // in-flight IPC call would have already reserved it by the time a real+ // 60s-interval sweep landed.+ await new Promise((resolve) => setImmediate(resolve));++ clock.now += 10 * 60 * 1000 + 1;+ manager.sweepExpired();++ assert.equal(log.rows.get(abandoned.actionId).state, "expired");+ assert.equal(log.rows.get(sending.actionId).state, "committing");+ finishSend({ state: "sent" });+ assert.equal((await inFlight).state, "sent");+ assert.deepEqual(await manager.commit(abandoned.actionId, {}, ALLOWED), {+ state: "not_sent",+ reason: "not_found",+ });+ assert.equal(fake.calls.commit.length, 1);+});++test("receipts carry the account, and no account means no action", async () => {+ const { manager, fake, log } = await setup();+ const signedIn = { policyState: "allowed", accountId: "acct-1" };++ const prepared = await manager.prepare("fake", "post", { text: "hi" }, signedIn);+ assert.equal(log.rows.get(prepared.actionId).accountId, "acct-1");+ await manager.runDirect("fake", "draft", {}, signedIn, {});+ assert.ok([...log.rows.values()].every((row) => row.accountId === "acct-1"));+ assert.equal(manager.recentActions("fake", 10, "acct-1").length, 2);++ // Signed in, but no account could be pinned to the call (a signed-out call+ // is refused as signed_out by the policy check first).+ const noAccount = { policyState: "allowed", accountId: null };+ assert.deepEqual(await manager.prepare("fake", "post", { text: "hi" }, noAccount), {+ status: "failed",+ errorCode: "receipt_unavailable",+ message: "Couldn't record this action, so nothing was prepared.",+ });+ assert.deepEqual(await manager.runDirect("fake", "draft", {}, noAccount, {}), {+ state: "unavailable",+ reason: "receipt_unavailable",+ });+ assert.deepEqual(manager.recentActions("fake", 10, null), []);+ assert.equal(fake.calls.prepare.length, 1);+});++test("the connector acts only under the binding the action was prepared with", async () => {+ const { manager, fake } = await setup();+ const prepared = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ await manager.commit(prepared.actionId, {}, ALLOWED);++ const binding = { accountId: "U1", workspaceId: "T1", generation: 1 };+ assert.deepEqual(fake.calls.prepare[0].context, { binding });+ assert.deepEqual(fake.calls.commit[0].context, { binding });+});++const connectable = (overrides = {}) => ({+ async authorize() {+ return { accessToken: "new" };+ },+ async revoke() {},+ async getStatus() {+ return { connected: true, accountLabel: "chad", workspaceLabel: "Acme" };+ },+ ...overrides,+});++test("connect saves under the account that started it, cancels old approvals and announces", async () => {+ const credentials = memoryCredentials(null, { connectorId: "fake" });+ const announced = [];+ const { manager, log } = await setup(connectable(), undefined, {+ credentials,+ onStatusChanged: (statuses) => announced.push(statuses),+ });+ const prepared = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);++ assert.deepEqual(await manager.connect("fake", "allowed"), {+ status: "connected",+ accountLabel: "chad",+ workspaceLabel: "Acme",+ });+ assert.deepEqual(credentials.read("acct-1", "fake"), {+ credential: { accessToken: "new" },+ generation: 1,+ });+ assert.equal(log.rows.get(prepared.actionId).state, "cancelled");+ assert.equal(announced.length, 1);+});++test("an account switch during the OAuth round trip saves nothing and revokes the new login", async () => {+ let accountId = "acct-a";+ const credentials = memoryCredentials();+ const flow = deferred();+ const revoked = [];+ const { manager } = await setup(+ connectable({+ authorize: () => flow.promise,+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials, getAccountId: () => accountId }+ );++ const connecting = manager.connect("fake", "allowed");+ accountId = "acct-b";+ flow.resolve({ accessToken: "a-login" });++ assert.deepEqual(await connecting, { status: "failed", errorCode: "connection_changed" });+ assert.equal(credentials.read("acct-a", "fake"), null);+ assert.equal(credentials.read("acct-b", "fake"), null);+ assert.deepEqual(revoked, [{ accessToken: "a-login" }]);+});++test("a login that changed during the round trip is kept, and the late one is revoked", async () => {+ const credentials = memoryCredentials();+ const flow = deferred();+ const revoked = [];+ const { manager } = await setup(+ connectable({+ authorize: () => flow.promise,+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials }+ );++ const connecting = manager.connect("fake", "allowed");+ credentials.replace("acct-1", "fake", { accessToken: "other-window" }, 0);+ flow.resolve({ accessToken: "late" });++ assert.deepEqual(await connecting, { status: "failed", errorCode: "connection_changed" });+ assert.equal(credentials.read("acct-1", "fake").credential.accessToken, "other-window");+ assert.deepEqual(revoked, [{ accessToken: "late" }]);+});++// The real loopback flow, with Electron's shell stubbed out.+function loadLoopbackFlow() {+ const Module = require("node:module");+ const originalLoad = Module._load;+ Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return { shell: { openExternal: async () => {} } };+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ return require("../../../src/helpers/oauthLoopbackFlow.js");+ } finally {+ Module._load = originalLoad;+ }+}++async function until(read) {+ for (let attempt = 0; attempt < 200; attempt += 1) {+ if (read()) return;+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ throw new Error("timed out waiting");+}++test("a second Connect cancels the abandoned sign-in, and only the new login is saved", async () => {+ const { runOAuthLoopbackFlow } = loadLoopbackFlow();+ const credentials = memoryCredentials(null, { connectorId: "fake" });+ const launches = [];+ const revoked = [];+ const { manager } = await setup(+ connectable({+ authorize: ({ signal } = {}) =>+ runOAuthLoopbackFlow({+ errorParam: "fake_error",+ signal,+ renderResultPage: () => "done",+ buildAuthUrl: (redirectUri, state) => {+ launches.push({ redirectUri, state });+ return "https://example.test/authorize";+ },+ handleCallback: async (code) => ({ accessToken: code }),+ }),+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials }+ );++ const first = manager.connect("fake", "allowed");+ await until(() => launches.length === 1);+ const second = manager.connect("fake", "allowed");++ assert.deepEqual(await first, { status: "failed", errorCode: "oauth_cancelled" });+ await until(() => launches.length === 2);+ const [abandoned, current] = launches;+ // The abandoned tab's server is gone.+ await assert.rejects(fetch(`${abandoned.redirectUri}/?code=late&state=${abandoned.state}`));+ await fetch(`${current.redirectUri}/?code=second&state=${current.state}`);++ assert.equal((await second).status, "connected");+ assert.deepEqual(credentials.read("acct-1", "fake").credential, { accessToken: "second" });+ assert.equal(launches.length, 2, "one browser launch per attempt");+ assert.deepEqual(revoked, [], "nothing was revoked for the cancelled attempt");+});++test("a sign-in that finishes after a newer Connect replaced it is revoked, never saved", async () => {+ const credentials = memoryCredentials(null, { connectorId: "fake" });+ const flows = [];+ const revoked = [];+ const { manager } = await setup(+ connectable({+ // Like a flow whose provider answered before the abort: it resolves.+ authorize: () => {+ const flow = deferred();+ flows.push(flow);+ return flow.promise;+ },+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials }+ );++ const first = manager.connect("fake", "allowed");+ const second = manager.connect("fake", "allowed");+ flows[0].resolve({ accessToken: "late" });++ assert.deepEqual(await first, { status: "failed", errorCode: "oauth_cancelled" });+ assert.deepEqual(revoked, [{ accessToken: "late" }]);+ assert.equal(credentials.read("acct-1", "fake"), null);++ flows[1].resolve({ accessToken: "second" });+ assert.equal((await second).status, "connected");+ assert.deepEqual(credentials.read("acct-1", "fake").credential, { accessToken: "second" });+});++test("connect refuses on policy or no account, and reports flow errors by code", async () => {+ const credentials = memoryCredentials();+ const refusing = await setup(connectable(), undefined, { credentials });+ assert.deepEqual(await refusing.manager.connect("fake", "blocked"), {+ status: "unavailable",+ reason: "policy_blocked",+ });++ const signedOut = await setup(connectable(), undefined, {+ credentials,+ getAccountId: () => null,+ });+ assert.deepEqual(await signedOut.manager.connect("fake", "allowed"), {+ status: "unavailable",+ reason: "signed_out",+ });++ for (const [thrown, errorCode] of [+ [Object.assign(new Error("OAuth flow timed out"), { code: "oauth_timeout" }), "oauth_timeout"],+ [+ Object.assign(new Error("x"), { redirectCode: "token_exchange_failed" }),+ "token_exchange_failed",+ ],+ [new Error("GET https://slack.com/api/oauth.v2.access?code=secret failed"), "connect_failed"],+ ]) {+ const failing = await setup(+ connectable({+ async authorize() {+ throw thrown;+ },+ }),+ undefined,+ { credentials }+ );+ assert.deepEqual(await failing.manager.connect("fake", "allowed"), {+ status: "failed",+ errorCode,+ });+ }+ assert.equal(credentials.read("acct-1", "fake"), null);+});++test("connect whose credential save fails for a real reason (not a race) logs it, revokes the new login, and reports credential_save_failed", async () => {+ const logger = recordingLogger();+ const credentials = memoryCredentials(null, { connectorId: "fake" });+ credentials.replace = () => {+ throw Object.assign(new Error("EIO: i/o error"), { code: "EIO" });+ };+ const revoked = [];+ const { manager } = await setup(+ connectable({+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials, logger }+ );++ assert.deepEqual(await manager.connect("fake", "allowed"), {+ status: "failed",+ errorCode: "credential_save_failed",+ });+ assert.deepEqual(revoked, [{ accessToken: "new" }]);+ const warnings = logger.lines.filter((line) => line.level === "warn");+ assert.equal(warnings.length, 1);+ const logged = JSON.stringify(warnings);+ assert.match(logged, /EIO/);+ assert.doesNotMatch(logged, /accessToken/);+});++test("disconnect revokes the stored login, clears it, cancels and announces; a failed revoke still disconnects", async () => {+ const credentials = memoryCredentials(+ { accessToken: "t", refreshToken: "r" },+ { connectorId: "fake" }+ );+ const revoked = [];+ const announced = [];+ const { manager, log } = await setup(+ connectable({+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials, onStatusChanged: (statuses) => announced.push(statuses) }+ );+ const prepared = await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);++ assert.deepEqual(await manager.disconnect("fake"), { status: "disconnected" });+ assert.deepEqual(revoked, [{ accessToken: "t", refreshToken: "r" }]);+ assert.equal(credentials.read("acct-1", "fake"), null);+ assert.equal(log.rows.get(prepared.actionId).state, "cancelled");+ assert.equal(announced.length, 1);++ const offline = await setup(+ connectable({+ async revoke() {+ throw new Error("offline");+ },+ }),+ undefined,+ { credentials: memoryCredentials({ accessToken: "t" }, { connectorId: "fake" }) }+ );+ assert.deepEqual(await offline.manager.disconnect("fake"), { status: "disconnected" });+});++test("a disconnect never deletes a login connected while it was revoking", async () => {+ const credentials = memoryCredentials({ accessToken: "old" }, { connectorId: "fake" });+ const revoking = deferred();+ const { manager } = await setup(connectable({ revoke: () => revoking.promise }), undefined, {+ credentials,+ });++ const disconnecting = manager.disconnect("fake");+ credentials.replace("acct-1", "fake", { accessToken: "new" }, 1);+ revoking.resolve();++ assert.deepEqual(await disconnecting, { status: "failed", errorCode: "connection_changed" });+ assert.equal(credentials.read("acct-1", "fake").credential.accessToken, "new");+});++test("disconnect whose credential clear fails for a real reason (not a race) logs it and reports disconnect_failed", async () => {+ const logger = recordingLogger();+ const credentials = memoryCredentials({ accessToken: "t" }, { connectorId: "fake" });+ credentials.clear = () => {+ throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });+ };+ const revoked = [];+ const { manager } = await setup(+ connectable({+ async revoke(credential) {+ revoked.push(credential);+ },+ }),+ undefined,+ { credentials, logger }+ );++ assert.deepEqual(await manager.disconnect("fake"), {+ status: "failed",+ errorCode: "disconnect_failed",+ });+ // The revoke already happened; the local slot wasn't cleared, so it isn't+ // pretended away.+ assert.deepEqual(revoked, [{ accessToken: "t" }]);+ assert.deepEqual(credentials.read("acct-1", "fake"), {+ credential: { accessToken: "t" },+ generation: 1,+ });+ const warnings = logger.lines.filter((line) => line.level === "warn");+ assert.equal(warnings.length, 1);+ const logged = JSON.stringify(warnings);+ assert.match(logged, /EPERM/);+ assert.doesNotMatch(logged, /accessToken/);+});++function loadAccountScopeBinding() {+ const Module = require("node:module");+ const originalLoad = Module._load;+ Module._load = function loadWithElectronStub(request, parent, isMain) {+ if (request === "electron") return { app: { getPath: () => require("node:os").tmpdir() } };+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ return require("../../../src/helpers/accountScopeBinding.js");+ } finally {+ Module._load = originalLoad;+ }+}++// connectorCredentials over an in-memory store.+function memoryStore() {+ const slots = new Map();+ const generations = new Map();+ const bump = (slot) => generations.set(slot, (generations.get(slot) ?? 0) + 1);+ return {+ getGeneration: (slot) => generations.get(slot) ?? 0,+ read: (slot) => slots.get(slot) ?? null,+ replace: (slot, credential) => {+ slots.set(slot, credential);+ bump(slot);+ },+ save: (slot, credential) => slots.set(slot, credential),+ clear: (slot) => {+ slots.delete(slot);+ bump(slot);+ },+ };+}++test("logins are filed under the account the credential in use is bound to, as receipts are", async () => {+ const { resolveActiveAccountScope, hashToken } = loadAccountScopeBinding();+ const { connectorAccountIdFrom } = require("../../../src/helpers/connectors/connectorIpc.js");+ const {+ createConnectorCredentials,+ } = require("../../../src/helpers/connectors/connectorCredentials.js");+ // What main.js used to read: it doesn't move when one signed-in token+ // replaces another.+ const databaseManager = { activeAccountId: "account-a" };+ const tokenState = { token: "token-b", generation: 2 };+ let binding = null;+ const getAccountId = connectorAccountIdFrom(() =>+ resolveActiveAccountScope({ ...tokenState, binding })+ );+ const credentials = createConnectorCredentials({ store: memoryStore(), getAccountId });+ let authorized = 0;+ const { manager } = await setup(+ connectable({+ async authorize() {+ authorized += 1;+ return { accessToken: "b-login" };+ },+ }),+ undefined,+ { credentials, getAccountId }+ );++ // No validated scope for the token in use: refused before any sign-in.+ assert.deepEqual(await manager.connect("fake", "allowed"), {+ status: "unavailable",+ reason: "signed_out",+ });+ assert.equal(authorized, 0);+ assert.equal(credentials.read(databaseManager.activeAccountId, "fake"), null);++ binding = { version: 1, accountId: "account-b", tokenHash: hashToken("token-b") };+ assert.equal((await manager.connect("fake", "allowed")).status, "connected");+ assert.deepEqual(credentials.read("account-b", "fake").credential, { accessToken: "b-login" });+ assert.equal(credentials.read(databaseManager.activeAccountId, "fake"), null);+});++test("main files connector logins under the credential's account scope, not the database scope", () => {+ const source = require("node:fs").readFileSync(+ require("node:path").join(__dirname, "../../../main.js"),+ "utf8"+ );+ const wiring = source.match(+ /const getConnectorAccountScope = ([\s\S]*?)\n\s+const connectorCredentials/+ );+ assert.ok(wiring, "main.js defines the connector account lookup");+ assert.match(wiring[1], /accountScopeBinding\.resolveActiveAccountScope\(/);+ assert.match(wiring[1], /require\("\.\/src\/helpers\/tokenStore"\)\.getState\(\)/);+ assert.match(+ wiring[1],+ /getConnectorAccountId = connectorAccountIdFrom\(getConnectorAccountScope\)/+ );+ assert.doesNotMatch(wiring[1], /databaseManager\.activeAccountId/);+});++test("disconnectAll disconnects every connector that can revoke", async () => {+ const credentials = memoryCredentials({ accessToken: "t" }, { connectorId: "fake" });+ const { manager } = await setup(connectable(), undefined, { credentials });+ await manager.disconnectAll();+ assert.equal(credentials.read("acct-1", "fake"), null);+});++test("only the newest status change is announced", async () => {+ const announced = [];+ const slowFirst = deferred();+ let reads = 0;+ const { manager } = await setup(+ {+ getStatus: () => {+ reads += 1;+ return reads === 1+ ? slowFirst.promise+ : Promise.resolve({ connected: false, accountLabel: null });+ },+ },+ undefined,+ { onStatusChanged: (statuses) => announced.push(statuses[0].connected) }+ );++ const older = manager.notifyStatusChanged();+ const newer = manager.notifyStatusChanged();+ await newer;+ slowFirst.resolve({ connected: true, accountLabel: "chad" });+ await older;++ assert.deepEqual(announced, [false]);+});++test("a reconnect_needed result announces the status change", async () => {+ const announced = [];+ const { manager } = await setup(+ {+ async prepare() {+ return { status: "failed", errorCode: "reconnect_needed", message: "Reconnect Slack." };+ },+ },+ undefined,+ { onStatusChanged: (statuses) => announced.push(statuses) }+ );++ await manager.prepare("fake", "post", { text: "hi" }, ALLOWED);+ await new Promise((resolve) => setImmediate(resolve));++ assert.equal(announced.length, 1);+});+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 };@@ -664,9 +1467,13 @@ test("a commit refused by policy withdraws the action for good", async () => {});test("prepare and commit each sweep other expired actions", async () => {- const { PENDING_TTL_MS } = await loadPending();+ const { PENDING_TTL_MS, createPendingActions } = await loadPending();let clock = 1_000;- const { manager, log } = await setup({}, {}, { now: () => clock });+ const { manager, log } = await setup(+ {},+ {},+ { pendingActions: createPendingActions({ now: () => clock }) }+ );const stale = await manager.prepare("fake", "post", { text: "x" }, ALLOWED);clock += PENDING_TTL_MS + 1;diff --git a/test/helpers/connectors/credentialStore.test.js b/test/helpers/connectors/credentialStore.test.jsnew file mode 100644index 000000000..72155d5d1--- /dev/null+++ b/test/helpers/connectors/credentialStore.test.js@@ -0,0 +1,164 @@+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 load = () => import("../../../src/helpers/connectors/credentialStore.js");++const fakeCrypto = {+ isAvailable: () => true,+ encrypt: (text) => Buffer.from(`enc:${Buffer.from(text).toString("base64")}`),+ decrypt: (buf) => ({+ value: Buffer.from(buf.toString().slice(4), "base64").toString("utf8"),+ needsReencrypt: false,+ }),+};+const silentLogger = { info() {}, warn() {}, error() {} };++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-credentials-"));+}++test("a credential round-trips and is never stored in plaintext", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ const store = createCredentialStore({ dir, secretCrypto: fakeCrypto, logger: silentLogger });++ store.replace("slack", { accessToken: "xoxp-secret-token", accountId: "U1" });++ assert.deepEqual(store.read("slack"), { accessToken: "xoxp-secret-token", accountId: "U1" });+ const onDisk = fs.readFileSync(path.join(dir, "slack.bin"), "utf8");+ assert.doesNotMatch(onDisk, /xoxp-secret-token/);+});++test("replace and clear bump the generation; save does not", async () => {+ const { createCredentialStore } = await load();+ const store = createCredentialStore({+ dir: tempDir(),+ secretCrypto: fakeCrypto,+ logger: silentLogger,+ });+ assert.equal(store.getGeneration("slack"), 0);++ store.replace("slack", { accessToken: "a" });+ assert.equal(store.getGeneration("slack"), 1);++ store.save("slack", { accessToken: "refreshed" });+ assert.equal(store.getGeneration("slack"), 1);+ assert.equal(store.read("slack").accessToken, "refreshed");++ store.clear("slack");+ assert.equal(store.getGeneration("slack"), 2);+ assert.equal(store.read("slack"), null);+ assert.equal(store.getGeneration("linear"), 0);+});++test("without an encryption backend the credential falls back to plaintext", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ const store = createCredentialStore({+ dir,+ secretCrypto: { ...fakeCrypto, isAvailable: () => false },+ logger: silentLogger,+ });+ store.replace("linear", { accessToken: "lin" });+ assert.deepEqual(store.read("linear"), { accessToken: "lin" });+});++test("an unreadable credential reads as disconnected", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ fs.writeFileSync(path.join(dir, "github.bin"), "garbage");+ const store = createCredentialStore({+ dir,+ secretCrypto: {+ ...fakeCrypto,+ decrypt: () => {+ throw new Error("bad blob");+ },+ },+ logger: silentLogger,+ });+ assert.equal(store.read("github"), null);+});++test("connector ids that could escape the directory are rejected", async () => {+ const { createCredentialStore } = await load();+ const store = createCredentialStore({+ dir: tempDir(),+ secretCrypto: fakeCrypto,+ logger: silentLogger,+ });+ assert.throws(() => store.replace("../evil", {}), /Invalid connector id/);+});++test("writes are atomic and leave no temp files behind", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ const store = createCredentialStore({ dir, secretCrypto: fakeCrypto, logger: silentLogger });++ store.replace("slack", { accessToken: "a" });+ store.save("slack", { accessToken: "b" });++ assert.deepEqual(fs.readdirSync(dir), ["slack.bin"]);+ assert.equal(store.read("slack").accessToken, "b");+});++test("a failed rename keeps the previous credential and removes the temp file", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ let failRename = false;+ const fsImpl = {+ ...fs,+ renameSync: (from, to) => {+ if (failRename) throw Object.assign(new Error("rename failed"), { code: "EIO" });+ return fs.renameSync(from, to);+ },+ };+ const store = createCredentialStore({+ dir,+ secretCrypto: fakeCrypto,+ logger: silentLogger,+ fsImpl,+ });+ store.replace("slack", { accessToken: "old" });++ failRename = true;+ assert.throws(+ () => store.save("slack", { accessToken: "new" }),+ (error) => error.code === "EIO"+ );++ assert.equal(store.read("slack").accessToken, "old");+ assert.deepEqual(fs.readdirSync(dir), ["slack.bin"]);+});++test(+ "the credentials directory is private to the user",+ { skip: process.platform === "win32" },+ async () => {+ const { createCredentialStore } = await load();+ const dir = path.join(tempDir(), "connectors");+ fs.mkdirSync(dir, { mode: 0o755 });+ const store = createCredentialStore({ dir, secretCrypto: fakeCrypto, logger: silentLogger });++ store.replace("slack", { accessToken: "a" });++ assert.equal(fs.statSync(dir).mode & 0o777, 0o700);+ assert.equal(fs.statSync(path.join(dir, "slack.bin")).mode & 0o777, 0o600);+ }+);++test("an unreadable credential is logged without its error message", async () => {+ const { createCredentialStore } = await load();+ const dir = tempDir();+ const lines = [];+ const logger = { info() {}, error() {}, warn: (...args) => lines.push(args) };+ fs.writeFileSync(path.join(dir, "slack.bin"), "enc:bm90IGpzb24=");+ const store = createCredentialStore({ dir, secretCrypto: fakeCrypto, logger });++ assert.equal(store.read("slack"), null);+ assert.match(JSON.stringify(lines), /SyntaxError/);+ assert.doesNotMatch(JSON.stringify(lines), /not valid JSON|Unexpected token/);+});diff --git a/test/helpers/connectors/deliveryClassifier.test.js b/test/helpers/connectors/deliveryClassifier.test.jsnew file mode 100644index 000000000..bb77548cb--- /dev/null+++ b/test/helpers/connectors/deliveryClassifier.test.js@@ -0,0 +1,57 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../../src/helpers/connectors/deliveryClassifier.js");++test("errors raised before the request can reach the provider are failed", async () => {+ const { classifyTransportError } = await load();+ assert.equal(+ classifyTransportError(Object.assign(new Error("dns"), { code: "ENOTFOUND" })),+ "failed"+ );+ assert.equal(+ classifyTransportError(new TypeError("fetch failed", { cause: { code: "ECONNREFUSED" } })),+ "failed"+ );+ assert.equal(classifyTransportError(new Error("net::ERR_INTERNET_DISCONNECTED")), "failed");+ assert.equal(classifyTransportError(new Error("net::ERR_NAME_NOT_RESOLVED")), "failed");+});++test("anything that may have reached the provider is unknown", async () => {+ const { classifyTransportError } = await load();+ assert.equal(+ classifyTransportError(Object.assign(new Error("reset"), { code: "ECONNRESET" })),+ "unknown"+ );+ assert.equal(classifyTransportError(new Error("net::ERR_CONNECTION_RESET")), "unknown");+ assert.equal(+ classifyTransportError(Object.assign(new Error("aborted"), { name: "AbortError" })),+ "unknown"+ );+ assert.equal(classifyTransportError(new Error("socket hang up")), "unknown");+ assert.equal(classifyTransportError(undefined), "unknown");+});++test("HTTP statuses: only 4xx proves the provider rejected the request", async () => {+ const { classifyHttpStatus } = await load();+ assert.equal(classifyHttpStatus(200), "ok");+ assert.equal(classifyHttpStatus(201), "ok");+ for (const status of [400, 401, 403, 404, 409, 422, 429]) {+ assert.equal(classifyHttpStatus(status), "failed", String(status));+ }+ // A 5xx says nothing about whether the provider acted before failing.+ for (const status of [500, 501, 502, 503, 504, 302, 100]) {+ assert.equal(classifyHttpStatus(status), "unknown", String(status));+ }+});++test("provider error codes are failed only when documented as rejected before acting", async () => {+ const { classifyProviderError } = await load();+ const slackRejections = new Set(["channel_not_found", "not_in_channel", "invalid_auth"]);+ assert.equal(classifyProviderError("not_in_channel", slackRejections), "failed");+ // Slack: "It's possible some aspect of the operation succeeded before the error was raised."+ assert.equal(classifyProviderError("internal_error", slackRejections), "unknown");+ assert.equal(classifyProviderError("fatal_error", slackRejections), "unknown");+ assert.equal(classifyProviderError("brand_new_code", slackRejections), "unknown");+ assert.equal(classifyProviderError(undefined, slackRejections), "unknown");+});diff --git a/test/helpers/connectors/errorSummary.test.js b/test/helpers/connectors/errorSummary.test.jsnew file mode 100644index 000000000..15bcc92d1--- /dev/null+++ b/test/helpers/connectors/errorSummary.test.js@@ -0,0 +1,23 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../../src/helpers/connectors/errorSummary.js");++test("an error summary keeps the name and code, never the message", async () => {+ const { describeError } = await load();+ const error = Object.assign(+ new TypeError("fetch failed https://slack.com/api/chat.postMessage?token=xoxp-1"),+ { cause: { code: "ECONNRESET" } }+ );++ assert.deepEqual(describeError(error), { errorName: "TypeError", errorCode: "ECONNRESET" });+ assert.deepEqual(+ describeError(Object.assign(new Error("x"), { redirectCode: "token_exchange_failed" })),+ {+ errorName: "Error",+ errorCode: "token_exchange_failed",+ }+ );+ assert.deepEqual(describeError(undefined), { errorName: "Error", errorCode: null });+ assert.doesNotMatch(JSON.stringify(describeError(error)), /xoxp|slack\.com/);+});diff --git a/test/helpers/connectors/oauthResultPage.test.js b/test/helpers/connectors/oauthResultPage.test.jsnew file mode 100644index 000000000..7ea66c3ce--- /dev/null+++ b/test/helpers/connectors/oauthResultPage.test.js@@ -0,0 +1,18 @@+const test = require("node:test");+const assert = require("node:assert/strict");++test("the browser result page escapes its text and marks the outcome", async () => {+ const { renderOAuthResultPage } =+ await import("../../../src/helpers/connectors/oauthResultPage.js");++ const html = renderOAuthResultPage({+ ok: true,+ title: "Slack is <b>connected</b>",+ body: "Close & return",+ });++ assert.match(html, /Slack is <b>connected<\/b>/);+ assert.match(html, /Close & return/);+ assert.match(html, /data-ok="true"/);+ assert.match(renderOAuthResultPage({ ok: false, title: "x", body: "y" }), /data-ok="false"/);+});diff --git a/test/helpers/connectors/pendingActions.test.js b/test/helpers/connectors/pendingActions.test.jsindex 6ceec0fce..a17159bc4 100644--- a/test/helpers/connectors/pendingActions.test.js+++ b/test/helpers/connectors/pendingActions.test.js@@ -133,3 +133,43 @@ test("the default id generator returns distinct 128-bit hex ids", async () => {assert.equal(ids.size, 50);for (const id of ids) assert.match(id, /^[0-9a-f]{32}$/);});++test("a binding for another OpenWhispr account never commits", async () => {+ const { createPendingActions } =+ await import("../../../src/helpers/connectors/pendingActions.js");+ const pending = createPendingActions();+ const approved = { ownerAccountId: "acct-a", accountId: "U1", workspaceId: "T1", generation: 1 };+ const actionId = pending.create({+ connectorId: "slack",+ action: "post",+ binding: approved,+ payload: {},+ preview: {},+ });++ assert.deepEqual(pending.beginCommit(actionId, { ...approved, ownerAccountId: "acct-b" }), {+ ok: false,+ reason: "connection_changed",+ });+});++test("sweepExpired removes only pending actions past a custom TTL", async () => {+ const { createPendingActions } =+ await import("../../../src/helpers/connectors/pendingActions.js");+ const clock = { now: 0 };+ const pending = createPendingActions({ now: () => clock.now, ttlMs: 1000 });+ const binding = { accountId: "U1", workspaceId: "T1", generation: 1 };+ const make = () =>+ pending.create({ connectorId: "slack", action: "post", binding, payload: {}, preview: {} });++ const stale = make();+ const sending = make();+ pending.beginCommit(sending, binding);+ clock.now = 1001;+ const fresh = make();++ assert.deepEqual(pending.sweepExpired(), [stale]);+ assert.equal(pending.get(stale), null);+ assert.equal(pending.get(sending).state, "committing");+ assert.equal(pending.get(fresh).state, "pending");+});diff --git a/test/helpers/connectors/slackApi.test.js b/test/helpers/connectors/slackApi.test.jsnew file mode 100644index 000000000..266a903ff--- /dev/null+++ b/test/helpers/connectors/slackApi.test.js@@ -0,0 +1,124 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ FIXTURES,+ fakeSlackFetch,+ ok,+ slackError,+ httpStatus,+ reset,+ offline,+} = require("./slackFixtures");++const load = () => import("../../../src/helpers/connectors/slackApi.js");++async function api(script, options = {}) {+ const { createSlackApi } = await load();+ const slack = fakeSlackFetch(script);+ const sleeps = [];+ const client = createSlackApi({+ fetchImpl: slack.fetchImpl,+ sleep: async (ms) => {+ sleeps.push(ms);+ },+ ...options,+ });+ return { client, slack, sleeps };+}++test("a successful call returns the body and sends the token as a bearer header", async () => {+ const { client, slack } = await api({ "chat.postMessage": [ok(FIXTURES.posted)] });++ const result = await client.call(+ "chat.postMessage",+ { channel: "C0ENG", markdown_text: "hi" },+ { token: "xoxp-t" }+ );++ assert.deepEqual(result, { ok: true, data: FIXTURES.posted });+ assert.equal(slack.calls[0].authorization, "Bearer xoxp-t");+ assert.equal(slack.calls[0].contentType, "application/x-www-form-urlencoded");+ assert.deepEqual(slack.calls[0].params, { channel: "C0ENG", markdown_text: "hi" });+});++test("documented refusals are failed; internal_error, fatal_error and new codes are unknown", async () => {+ for (const [code, outcome] of [+ ["not_in_channel", "failed"],+ ["channel_not_found", "failed"],+ ["token_expired", "failed"],+ ["is_archived", "failed"],+ ["internal_error", "unknown"],+ ["fatal_error", "unknown"],+ ["some_new_code", "unknown"],+ ]) {+ const { client } = await api({ "chat.postMessage": [slackError(code)] });+ const result = await client.call("chat.postMessage", {}, { token: "t" });+ assert.equal(result.ok, false);+ assert.equal(result.source, "slack");+ assert.equal(result.errorCode, code);+ assert.equal(result.outcome, outcome, code);+ }+});++test("a reset after sending is unknown; a DNS failure before connecting is failed", async () => {+ const afterWrite = await (+ await api({ "chat.postMessage": [reset()] })+ ).client.call("chat.postMessage");+ assert.deepEqual(+ { outcome: afterWrite.outcome, errorCode: afterWrite.errorCode, source: afterWrite.source },+ { outcome: "unknown", errorCode: "ECONNRESET", source: "network" }+ );++ const beforeConnect = await (+ await api({ "chat.postMessage": [offline()] })+ ).client.call("chat.postMessage");+ assert.equal(beforeConnect.outcome, "failed");+ assert.equal(beforeConnect.errorCode, "ENOTFOUND");+});++test("5xx and an unreadable 200 are unknown; other 4xx are failed", async () => {+ const serverError = await (+ await api({ "chat.postMessage": [httpStatus(503)] })+ ).client.call("chat.postMessage");+ assert.deepEqual([serverError.outcome, serverError.errorCode], ["unknown", "http_503"]);++ const unreadable = await (+ await api({ "chat.postMessage": [{ status: 200, rawBody: "<html>oops</html>" }] })+ ).client.call("chat.postMessage");+ assert.deepEqual([unreadable.outcome, unreadable.errorCode], ["unknown", "bad_response"]);++ const badRequest = await (+ await api({ "chat.postMessage": [httpStatus(400)] })+ ).client.call("chat.postMessage");+ assert.deepEqual([badRequest.outcome, badRequest.errorCode], ["failed", "http_400"]);+});++test("a 429 asking for 5 s or less is retried once", async () => {+ const { client, slack, sleeps } = await api({+ "chat.postMessage": [httpStatus(429, { "retry-after": "2" }), ok(FIXTURES.posted)],+ });++ const result = await client.call("chat.postMessage", {}, { token: "t" });++ assert.equal(result.ok, true);+ assert.deepEqual(sleeps, [2000]);+ assert.equal(slack.calls.length, 2);+});++test("a longer Retry-After, or a second 429, is failed with no further try", async () => {+ const long = await api({ "chat.postMessage": [httpStatus(429, { "retry-after": "30" })] });+ const longResult = await long.client.call("chat.postMessage");+ assert.deepEqual([longResult.outcome, longResult.errorCode], ["failed", "rate_limited"]);+ assert.equal(long.slack.calls.length, 1);+ assert.deepEqual(long.sleeps, []);++ const twice = await api({+ "chat.postMessage": [+ httpStatus(429, { "retry-after": "1" }),+ httpStatus(429, { "retry-after": "1" }),+ ],+ });+ const twiceResult = await twice.client.call("chat.postMessage");+ assert.equal(twiceResult.errorCode, "rate_limited");+ assert.equal(twice.slack.calls.length, 2);+});diff --git a/test/helpers/connectors/slackAuth.test.js b/test/helpers/connectors/slackAuth.test.jsnew file mode 100644index 000000000..1d65bc629--- /dev/null+++ b/test/helpers/connectors/slackAuth.test.js@@ -0,0 +1,445 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ NOW,+ FIXTURES,+ CONNECTED,+ BINDING,+ fakeSlackFetch,+ ok,+ slackError,+ httpStatus,+ offline,+ memoryCredentials,+} = require("./slackFixtures");++const loadAuth = () => import("../../../src/helpers/connectors/slackAuth.js");+const loadApi = () => import("../../../src/helpers/connectors/slackApi.js");++class FakeFlowError extends Error {+ constructor(redirectCode, message) {+ super(message);+ this.redirectCode = redirectCode;+ }+}++const EXPIRED = { ...CONNECTED, expiresAt: NOW - 1 };++async function setup({+ script = {},+ credential = CONNECTED,+ fetchImpl,+ clientId = "123.456",+ credentials: credentialsOverride,+ logger,+} = {}) {+ const [{ createSlackAuth }, { createSlackApi }] = await Promise.all([loadAuth(), loadApi()]);+ const slack = fakeSlackFetch(script);+ const credentials = credentialsOverride ?? memoryCredentials(credential);+ const flows = [];+ const auth = createSlackAuth({+ api: createSlackApi({ fetchImpl: fetchImpl ?? slack.fetchImpl, sleep: async () => {} }),+ credentials,+ getClientId: () => clientId,+ OAuthFlowError: FakeFlowError,+ now: () => NOW,+ logger,+ // Like the real flow behind a relay: the public redirect URI goes to both calls.+ runOAuthLoopbackFlow: async (options) => {+ const redirectUri = options.publicRedirectUri ?? "http://127.0.0.1:5000";+ flows.push({+ options,+ authUrl: new URL(options.buildAuthUrl(redirectUri, "state-1", "challenge-1")),+ });+ return options.handleCallback("code-1", redirectUri, "verifier-1");+ },+ });+ const slot = () => credentials.read("acct-1", "slack")?.credential;+ return { auth, slack, credentials, flows, slot };+}++test("authorize asks for user scopes only, exchanges with the PKCE verifier, and saves nothing", async () => {+ const { auth, slack, credentials, flows } = await setup({+ credential: null,+ script: { "oauth.v2.access": [ok(FIXTURES.exchange)], "auth.test": [ok(FIXTURES.authTest)] },+ });++ const credential = await auth.authorize();++ const { authUrl, options } = flows[0];+ assert.equal(options.errorParam, "slack_error");+ assert.equal(options.publicRedirectUri, "https://openwhispr.com/auth/slack/callback");+ assert.deepEqual(options.ports, [0]);+ assert.equal(options.callbackPath, "/slack/callback");+ assert.equal(options.timeoutMs, 300000);+ assert.equal(authUrl.origin + authUrl.pathname, "https://slack.com/oauth/v2/authorize");+ assert.equal(+ authUrl.searchParams.get("redirect_uri"),+ "https://openwhispr.com/auth/slack/callback"+ );+ assert.match(authUrl.searchParams.get("user_scope"), /chat:write/);+ assert.equal(authUrl.searchParams.get("scope"), null, "no bot scopes");+ assert.equal(authUrl.searchParams.get("code_challenge_method"), "S256");+ assert.deepEqual(slack.calls[0].params, {+ client_id: "123.456",+ code: "code-1",+ code_verifier: "verifier-1",+ redirect_uri: "https://openwhispr.com/auth/slack/callback",+ });+ assert.equal(slack.calls[1].authorization, "Bearer xoxe.xoxp-1-test-access");+ assert.deepEqual(credential, {+ accessToken: "xoxe.xoxp-1-test-access",+ refreshToken: "xoxe-1-test-refresh",+ expiresAt: NOW + 43200 * 1000,+ refreshIssuedAt: NOW,+ userId: "U0CHAD",+ userName: "chad",+ teamId: "T0TEST",+ teamName: "Acme Test",+ teamUrl: "https://acme-test.slack.com/",+ needsReconnect: false,+ });+ assert.equal(credentials.saves.length, 0);+});++test("authorize hands the connect's cancel signal to the loopback flow", async () => {+ const { auth, flows } = await setup({+ credential: null,+ script: { "oauth.v2.access": [ok(FIXTURES.exchange)], "auth.test": [ok(FIXTURES.authTest)] },+ });+ const controller = new AbortController();++ await auth.authorize({ signal: controller.signal });++ assert.equal(flows[0].options.signal, controller.signal);+});++test("authorize without a client id fails fast with not_configured", async () => {+ const { auth, flows } = await setup({ credential: null, clientId: "" });+ await assert.rejects(auth.authorize(), (error) => error.code === "not_configured");+ assert.equal(flows.length, 0);+});++test("the redirect override accepts only an https URL", async () => {+ const { slackRedirectUri, SLACK_RELAY_REDIRECT_URI } = await loadAuth();+ const preview =+ "https://openwhispr-website-git-feat-slack-oauth-relay.vercel.app/auth/slack/callback";++ assert.equal(slackRedirectUri({}), SLACK_RELAY_REDIRECT_URI);+ assert.equal(slackRedirectUri({ SLACK_OAUTH_REDIRECT_URI: preview }), preview);+ for (const rejected of [+ "http://127.0.0.1:5000/slack/callback",+ "javascript:alert(1)",+ "not a url",+ "",+ ]) {+ assert.equal(+ slackRedirectUri({ SLACK_OAUTH_REDIRECT_URI: rejected }),+ SLACK_RELAY_REDIRECT_URI,+ rejected+ );+ }+});++test("a token is handed out only for the login the action is bound to", async () => {+ const { auth, credentials, slack } = await setup();+ assert.equal((await auth.getAccessToken(BINDING)).token, "xoxe.xoxp-1-test-access");++ credentials.replace(+ "acct-1",+ "slack",+ { ...CONNECTED, userId: "U0BOB", accessToken: "xoxe.xoxp-bob" },+ 1+ );+ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "connection_changed",+ });+ assert.deepEqual(await auth.getAccessToken({ ...BINDING, ownerAccountId: "acct-2" }), {+ ok: false,+ errorCode: "connection_changed",+ });+ assert.deepEqual(slack.calls, []);+});++test("concurrent callers share one refresh, and the rotated token is saved before use", async () => {+ const { auth, slack, credentials } = await setup({+ credential: EXPIRED,+ script: { "oauth.v2.access": [ok(FIXTURES.refresh)] },+ });++ const [first, second] = await Promise.all([+ auth.getAccessToken(BINDING),+ auth.getAccessToken(BINDING),+ ]);++ assert.equal(slack.calls.length, 1);+ assert.deepEqual(slack.calls[0].params, {+ client_id: "123.456",+ grant_type: "refresh_token",+ refresh_token: "xoxe-1-test-refresh",+ });+ assert.equal(first.token, "xoxe.xoxp-1-test-access-2");+ assert.equal(second.token, "xoxe.xoxp-1-test-access-2");+ assert.equal(credentials.saves.length, 1);+ assert.equal(credentials.saves[0].refreshToken, "xoxe-1-test-refresh-2");+ assert.equal(credentials.generation("acct-1", "slack"), 1, "a refresh is not a new login");+});++test("forceRefresh refreshes a token that still looks valid", async () => {+ const { auth, slack } = await setup({ script: { "oauth.v2.access": [ok(FIXTURES.refresh)] } });+ const result = await auth.getAccessToken(BINDING, { forceRefresh: true });+ assert.equal(result.token, "xoxe.xoxp-1-test-access-2");+ assert.equal(slack.calls.length, 1);+});++test("Slack refusing the refresh token needs a reconnect, with no second attempt", async () => {+ const { auth, slack, slot } = await setup({+ credential: EXPIRED,+ script: { "oauth.v2.access": [slackError("invalid_refresh_token")] },+ });++ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "reconnect_needed",+ });+ assert.equal(slot().needsReconnect, true);+ assert.equal(auth.statusOf(slot()).needsReconnect, true);+ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "reconnect_needed",+ });+ assert.equal(slack.calls.length, 1);+});++test("rate limits and temporary Slack failures keep the login", async () => {+ for (const [reply, expectedCalls] of [+ [slackError("ratelimited"), 1],+ [slackError("service_unavailable"), 2],+ [slackError("internal_error"), 2],+ [httpStatus(503), 2],+ [offline(), 1],+ ]) {+ const { auth, slack, slot } = await setup({+ credential: EXPIRED,+ script: { "oauth.v2.access": [reply] },+ });+ const result = await auth.getAccessToken(BINDING);+ assert.equal(result.ok, false);+ assert.notEqual(result.errorCode, "reconnect_needed");+ assert.equal(slot().needsReconnect, false);+ assert.equal(auth.statusOf(slot()).needsReconnect, false);+ assert.equal(+ slack.calls.length,+ expectedCalls,+ JSON.stringify(reply.body ?? reply.status ?? "offline")+ );+ }+});++test("an uncertain refresh is asked once more at once, inside the grace period", async () => {+ const { auth, slack } = await setup({+ credential: EXPIRED,+ script: { "oauth.v2.access": [slackError("internal_error"), ok(FIXTURES.refresh)] },+ });+ assert.equal((await auth.getAccessToken(BINDING)).token, "xoxe.xoxp-1-test-access-2");+ assert.equal(slack.calls.length, 2);+});++test("a reconnect during a refresh is never overwritten by the old login", async () => {+ let release;+ const gate = new Promise((resolve) => {+ release = resolve;+ });+ let started = false;+ const fetchImpl = async () => {+ started = true;+ await gate;+ return new Response(JSON.stringify(FIXTURES.refresh), { status: 200 });+ };+ const { auth, credentials, slot } = await setup({ credential: EXPIRED, fetchImpl });++ const pending = auth.getAccessToken(BINDING);+ while (!started) await new Promise((resolve) => setImmediate(resolve));+ credentials.replace(+ "acct-1",+ "slack",+ { ...CONNECTED, userId: "U0OTHER", accessToken: "xoxe.xoxp-other" },+ 1+ );+ release();++ assert.deepEqual(await pending, { ok: false, errorCode: "connection_changed" });+ assert.equal(slot().accessToken, "xoxe.xoxp-other");+ assert.equal(credentials.saves.length, 0);+});++test("the status asks for a reconnect 30 days after the last refresh token", async () => {+ const { auth } = await setup();+ assert.deepEqual(auth.statusOf(CONNECTED), {+ connected: true,+ accountLabel: "chad",+ workspaceLabel: "Acme Test",+ needsReconnect: false,+ });+ const stale = { ...CONNECTED, refreshIssuedAt: NOW - 31 * 24 * 60 * 60 * 1000 };+ assert.equal(auth.statusOf(stale).needsReconnect, true);+});++test("revoke revokes the refresh token and the access token, and never throws offline", async () => {+ const online = await setup({ script: { "auth.revoke": [ok({ ok: true, revoked: true })] } });+ await online.auth.revoke(CONNECTED);+ assert.deepEqual(+ online.slack.calls.map((call) => [call.method, call.authorization]),+ [+ ["auth.revoke", "Bearer xoxe-1-test-refresh"],+ ["auth.revoke", "Bearer xoxe.xoxp-1-test-access"],+ ]+ );++ const offlineRevoke = await setup({ script: { "auth.revoke": [offline()] } });+ await assert.doesNotReject(offlineRevoke.auth.revoke(CONNECTED));+});++test("a login-gone refresh code during a reconnect race reports connection_changed, not reconnect_needed", async () => {+ const credentials = memoryCredentials(EXPIRED);+ const { auth, slack } = await setup({+ credentials,+ script: {+ "oauth.v2.access": [+ {+ ...slackError("invalid_refresh_token"),+ // Mid-flight: a reconnect lands while the refresh call is still out.+ during: () =>+ credentials.replace(+ "acct-1",+ "slack",+ { ...CONNECTED, userId: "U0OTHER", accessToken: "xoxe.xoxp-other" },+ 1+ ),+ },+ ],+ },+ });++ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "connection_changed",+ });+ assert.equal(credentials.read("acct-1", "slack").credential.needsReconnect, false);+ assert.equal(credentials.saves.length, 0, "nothing was written to the new login");+ assert.equal(slack.calls.length, 1);+});++test("a transient refresh failure during a reconnect race reports connection_changed, not the transient code", async () => {+ const credentials = memoryCredentials(EXPIRED);+ let replaced = false;+ const { auth } = await setup({+ credentials,+ script: {+ "oauth.v2.access": [+ {+ ...httpStatus(503),+ // Only replace once: an uncertain result is retried once more.+ during: () => {+ if (replaced) return;+ replaced = true;+ credentials.replace(+ "acct-1",+ "slack",+ { ...CONNECTED, userId: "U0OTHER", accessToken: "xoxe.xoxp-other" },+ 1+ );+ },+ },+ ],+ },+ });++ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "connection_changed",+ });+ assert.equal(credentials.saves.length, 0, "nothing was written to the new login");+});++test("markReconnect flags only the bound login and reports reconnect_needed", async () => {+ const { auth, credentials, slot, slack } = await setup();++ assert.deepEqual(auth.markReconnect(BINDING), { ok: false, errorCode: "reconnect_needed" });++ assert.equal(slot().needsReconnect, true);+ assert.equal(slot().accessToken, CONNECTED.accessToken, "the rest of the login is kept");+ assert.equal(credentials.generation("acct-1", "slack"), 1, "a flag is not a new login");+ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "reconnect_needed",+ });+ assert.deepEqual(slack.calls, []);+});++test("markReconnect after a reconnect reports connection_changed and writes nothing", async () => {+ const { auth, credentials, slot } = await setup();+ credentials.replace(+ "acct-1",+ "slack",+ { ...CONNECTED, userId: "U0OTHER", accessToken: "xoxe.xoxp-other" },+ 1+ );++ assert.deepEqual(auth.markReconnect(BINDING), { ok: false, errorCode: "connection_changed" });+ assert.equal(slot().needsReconnect, false);+ assert.equal(credentials.saves.length, 0);+});++test("a reconnect flag that can't be saved for a real reason is logged without the token", async () => {+ const warnings = [];+ const logger = { warn: (...args) => warnings.push(args) };+ const credentials = {+ read: () => ({ credential: EXPIRED, generation: 1 }),+ save: () => {+ throw Object.assign(new Error("no space left on device"), { code: "ENOSPC" });+ },+ };+ const { auth } = await setup({+ credentials,+ logger,+ script: { "oauth.v2.access": [slackError("invalid_refresh_token")] },+ });++ // Slack's answer stands even though the flag couldn't be written.+ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "reconnect_needed",+ });+ assert.deepEqual(auth.markReconnect(BINDING), { ok: false, errorCode: "reconnect_needed" });+ assert.equal(warnings.length, 2);+ const serialized = JSON.stringify(warnings);+ assert.match(serialized, /ENOSPC/);+ assert.doesNotMatch(serialized, /xoxe|no space left/);+});++test("a save failure that isn't a login race is reported as credential_save_failed and logged without the token", async () => {+ const warnings = [];+ const logger = { warn: (...args) => warnings.push(args) };+ const credentials = {+ read: () => ({ credential: EXPIRED, generation: 1 }),+ save: () => {+ throw Object.assign(new Error("no space left on device"), { code: "ENOSPC" });+ },+ };+ const { auth } = await setup({+ credentials,+ logger,+ script: { "oauth.v2.access": [ok(FIXTURES.refresh)] },+ });++ assert.deepEqual(await auth.getAccessToken(BINDING), {+ ok: false,+ errorCode: "credential_save_failed",+ });+ assert.equal(warnings.length, 1);+ const serialized = JSON.stringify(warnings[0]);+ assert.match(serialized, /ENOSPC/);+ assert.doesNotMatch(serialized, /xoxe/);+});diff --git a/test/helpers/connectors/slackConnector.test.js b/test/helpers/connectors/slackConnector.test.jsnew file mode 100644index 000000000..86eeeae0e--- /dev/null+++ b/test/helpers/connectors/slackConnector.test.js@@ -0,0 +1,555 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {+ NOW,+ FIXTURES,+ CONNECTED,+ BINDING,+ fakeSlackFetch,+ ok,+ slackError,+ httpStatus,+ reset,+ memoryCredentials,+} = require("./slackFixtures");++const BOUND = { binding: BINDING };+const NOT_CONNECTED = {+ connected: false,+ accountLabel: null,+ workspaceLabel: null,+ needsReconnect: false,+};++async function setupSlack(script, { credential = CONNECTED } = {}) {+ const [connectorModule, { createSlackApi }, { createSlackAuth }, { createSlackDirectory }] =+ await Promise.all([+ import("../../../src/helpers/connectors/slackConnector.js"),+ import("../../../src/helpers/connectors/slackApi.js"),+ import("../../../src/helpers/connectors/slackAuth.js"),+ import("../../../src/helpers/connectors/slackDirectory.js"),+ ]);+ const slack = fakeSlackFetch(script);+ const api = createSlackApi({ fetchImpl: slack.fetchImpl, sleep: async () => {} });+ const credentials = memoryCredentials(credential);+ const auth = createSlackAuth({+ api,+ credentials,+ getClientId: () => "123.456",+ OAuthFlowError: Error,+ runOAuthLoopbackFlow: async () => {+ throw new Error("not used in these tests");+ },+ now: () => NOW,+ });+ const connector = connectorModule.createSlackConnector({+ api,+ auth,+ directory: createSlackDirectory({ api, now: () => NOW }),+ credentials,+ });+ return { connector, slack, credentials, ...connectorModule };+}++const posts = (slack) => slack.calls.filter((call) => call.method === "chat.postMessage");+const postedText = (params) => params.markdown_text ?? params.text;+const channelsOnly = { "users.conversations": [ok(FIXTURES.channels)] };+const BOB = { ...CONNECTED, userId: "U0BOB", accessToken: "xoxe.xoxp-bob" };++async function prepareEng(connector, text = "Ship it") {+ const prepared = await connector.prepare("send_message", { destination: "#eng", text }, BOUND);+ assert.equal(prepared.status, "ready");+ return prepared;+}++test("a channel post: prepare only reads, and Send posts once with a permalink", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [ok(FIXTURES.posted)],+ });++ const prepared = await prepareEng(connector);+ assert.deepEqual(prepared.preview, {+ verbKey: "slackPost",+ destinationLabel: "#eng",+ accountLabel: "chad",+ workspaceLabel: "Acme Test",+ body: "Ship it",+ });+ assert.deepEqual(slack.methods(), ["users.conversations"]);++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.deepEqual(result, {+ state: "sent",+ url: "https://acme-test.slack.com/archives/C0ENG/p1727200000123456",+ });+ assert.deepEqual(slack.methods(), ["users.conversations", "chat.postMessage"]);+ assert.equal(posts(slack)[0].params.channel, "C0ENG");+});++test("a DM is opened only after Send, never while preparing", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "users.list": [ok(FIXTURES.people)],+ "conversations.open": [ok(FIXTURES.dmOpen)],+ "chat.postMessage": [ok(FIXTURES.postedDm)],+ });++ const prepared = await connector.prepare(+ "send_message",+ { destination: "Gabe Smith", text: "Lunch?" },+ BOUND+ );+ assert.equal(prepared.status, "ready");+ assert.equal(prepared.preview.destinationLabel, "Gabe Smith");+ assert.equal(slack.methods().includes("conversations.open"), false);++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "sent");+ assert.deepEqual(slack.methods().slice(-2), ["conversations.open", "chat.postMessage"]);+ assert.deepEqual(slack.calls.at(-2).params, { users: "U0GABE" });+ assert.equal(posts(slack)[0].params.channel, "D0GABE");+});++test("an ambiguous name asks which one and prepares nothing", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "users.list": [ok(FIXTURES.people)],+ });++ const prepared = await connector.prepare(+ "send_message",+ { destination: "gab", text: "hi" },+ BOUND+ );++ assert.equal(prepared.status, "needs_clarification");+ assert.deepEqual(prepared.candidates, ["Gabe Smith (@gabe)", "Gabriel Stone (@gstone)"]);+ assert.equal(+ slack+ .methods()+ .some((method) => method === "chat.postMessage" || method === "conversations.open"),+ false+ );+});++test("an unknown #channel or email asks the user instead of guessing", async () => {+ const { connector } = await setupSlack({+ ...channelsOnly,+ "users.lookupByEmail": [slackError("users_not_found")],+ });++ const channel = await connector.prepare(+ "send_message",+ { destination: "#random", text: "hi" },+ BOUND+ );+ assert.equal(channel.status, "needs_clarification");+ assert.match(channel.message, /#random/);++ const email = await connector.prepare(+ "send_message",+ { destination: "[email protected]", text: "hi" },+ BOUND+ );+ assert.equal(email.status, "needs_clarification");+});++test("a directory cut off at the page cap never claims a unique name", async () => {+ const sam = {+ id: "U0SAM",+ name: "sam",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Sam Lee", display_name: "sam" },+ };+ const endless = (key, item) => ({+ ok: true,+ [key]: [item],+ response_metadata: { next_cursor: "more" },+ });++ const people = await setupSlack({ ...channelsOnly, "users.list": [ok(endless("members", sam))] });+ const byName = await people.connector.prepare(+ "send_message",+ { destination: "Sam", text: "hi" },+ BOUND+ );+ assert.equal(byName.status, "needs_clarification");+ assert.match(byName.message, /email/);++ const exact = await setupSlack({+ "users.conversations": [ok(endless("channels", FIXTURES.channels.channels[0]))],+ });+ assert.equal(+ (await exact.connector.prepare("send_message", { destination: "#eng", text: "hi" }, BOUND))+ .status,+ "ready"+ );++ const prefixOnly = await setupSlack({+ "users.conversations": [ok(endless("channels", FIXTURES.channels.channels[1]))],+ });+ assert.equal(+ (await prefixOnly.connector.prepare("send_message", { destination: "#eng", text: "hi" }, BOUND))+ .status,+ "needs_clarification"+ );+});++test("Slack refusing an expired token refreshes the same login once and posts once", async () => {+ const { connector, slack, credentials } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [slackError("token_expired"), ok(FIXTURES.posted)],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });+ const prepared = await prepareEng(connector);++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "sent");+ assert.deepEqual(+ posts(slack).map((call) => call.authorization),+ ["Bearer xoxe.xoxp-1-test-access", "Bearer xoxe.xoxp-1-test-access-2"]+ );+ assert.equal(credentials.saves.at(-1).accessToken, "xoxe.xoxp-1-test-access-2");+ assert.equal(+ credentials.generation("acct-1", "slack"),+ 1,+ "a refresh keeps pending approvals valid"+ );+});++test("an HTTP 401 takes the same refresh-then-retry path", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [httpStatus(401), ok(FIXTURES.posted)],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });+ const prepared = await prepareEng(connector);++ assert.equal((await connector.commit("send_message", prepared.payload, {}, BOUND)).state, "sent");+ assert.equal(posts(slack).length, 2);+});++test("a reconnect before Send refuses the send without calling Slack", async () => {+ const { connector, slack, credentials } = await setupSlack(channelsOnly);+ const prepared = await prepareEng(connector);+ credentials.replace("acct-1", "slack", BOB, 1);++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "failed");+ assert.equal(result.errorCode, "connection_changed");+ assert.equal(posts(slack).length, 0);+});++test("a reconnect while refreshing after a token refusal never sends as the new login", async () => {+ let credentials;+ const setup = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [slackError("token_expired"), ok(FIXTURES.posted)],+ "oauth.v2.access": [+ { body: FIXTURES.refresh, during: () => credentials.replace("acct-1", "slack", BOB, 1) },+ ],+ });+ credentials = setup.credentials;+ const prepared = await prepareEng(setup.connector);++ const result = await setup.connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "failed");+ assert.equal(result.errorCode, "connection_changed");+ assert.deepEqual(+ posts(setup.slack).map((call) => call.authorization),+ ["Bearer xoxe.xoxp-1-test-access"]+ );+});++const slot = (credentials) => credentials.read("acct-1", "slack").credential;++test("a login Slack revoked at Send flips to Reconnect, with one post", async () => {+ for (const code of ["token_revoked", "account_inactive", "not_authed"]) {+ const { connector, slack, credentials } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [slackError(code)],+ "oauth.v2.access": [slackError("invalid_refresh_token")],+ });+ const prepared = await prepareEng(connector);++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "failed", code);+ assert.equal(result.errorCode, "reconnect_needed", code);+ assert.equal(slot(credentials).needsReconnect, true, code);+ assert.equal(posts(slack).length, 1, `${code}: a refused post is never repeated`);+ }+});++test("a login Slack revoked while preparing flips to Reconnect", async () => {+ const { connector, slack, credentials } = await setupSlack({+ "users.conversations": [slackError("token_revoked")],+ "oauth.v2.access": [slackError("invalid_refresh_token")],+ });++ const prepared = await connector.prepare(+ "send_message",+ { destination: "#eng", text: "hi" },+ BOUND+ );++ assert.equal(prepared.status, "failed");+ assert.equal(prepared.errorCode, "reconnect_needed");+ assert.equal(slot(credentials).needsReconnect, true);+ assert.deepEqual(slack.methods(), ["users.conversations", "oauth.v2.access"]);+});++test("a lookup refused for its token is asked once more after refreshing the same login", async () => {+ const { connector, slack, credentials } = await setupSlack({+ "users.conversations": [slackError("invalid_auth"), ok(FIXTURES.channels)],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });++ const prepared = await prepareEng(connector);++ assert.equal(prepared.payload.target.id, "C0ENG");+ assert.deepEqual(+ slack.calls+ .filter((call) => call.method === "users.conversations")+ .map((call) => call.authorization),+ ["Bearer xoxe.xoxp-1-test-access", "Bearer xoxe.xoxp-1-test-access-2"]+ );+ assert.equal(slot(credentials).needsReconnect, false);+});++test("a token refused again right after a successful refresh needs a reconnect", async () => {+ const atSend = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [slackError("invalid_auth"), slackError("invalid_auth")],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });+ const prepared = await prepareEng(atSend.connector);++ const sent = await atSend.connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(sent.state, "failed");+ assert.equal(sent.errorCode, "reconnect_needed");+ assert.equal(slot(atSend.credentials).needsReconnect, true);+ assert.equal(slot(atSend.credentials).accessToken, "xoxe.xoxp-1-test-access-2");+ assert.equal(posts(atSend.slack).length, 2);++ const atPrepare = await setupSlack({+ "users.conversations": [slackError("token_revoked"), slackError("token_revoked")],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });+ const refused = await atPrepare.connector.prepare(+ "send_message",+ { destination: "#eng", text: "hi" },+ BOUND+ );+ assert.equal(refused.status, "failed");+ assert.equal(refused.errorCode, "reconnect_needed");+ assert.equal(slot(atPrepare.credentials).needsReconnect, true);+});++test("a reconnect racing the reconnect flag reports connection_changed and leaves the new login alone", async () => {+ let credentials;+ const setup = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [+ slackError("invalid_auth"),+ {+ ...slackError("invalid_auth"),+ during: () => credentials.replace("acct-1", "slack", BOB, 1),+ },+ ],+ "oauth.v2.access": [ok(FIXTURES.refresh)],+ });+ credentials = setup.credentials;+ const prepared = await prepareEng(setup.connector);++ const result = await setup.connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "failed");+ assert.equal(result.errorCode, "connection_changed");+ assert.deepEqual(slot(credentials), BOB, "nothing was written to the new login");+ assert.equal(credentials.saves.length, 1, "only the old login's refresh was saved");+ assert.equal(posts(setup.slack).length, 2);+});++test("a short 429 is retried once and posts once", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [httpStatus(429, { "retry-after": "1" }), ok(FIXTURES.posted)],+ });+ const prepared = await prepareEng(connector);++ assert.equal((await connector.commit("send_message", prepared.payload, {}, BOUND)).state, "sent");+ assert.equal(posts(slack).length, 2);+});++test("permission and membership errors are failed with a specific reason", async () => {+ for (const [code, message] of [+ ["not_in_channel", "You're not a member of #eng."],+ ["is_archived", "#eng is archived."],+ ["missing_scope", /permission/],+ ]) {+ const { connector } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [slackError(code)],+ });+ const prepared = await prepareEng(connector);+ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);+ assert.equal(result.state, "failed", code);+ assert.equal(result.errorCode, code);+ if (message instanceof RegExp) assert.match(result.message, message);+ else assert.equal(result.message, message);+ }+});++test("a reset after the write, a 5xx or internal_error is unknown, with a link to check, and never retried", async () => {+ for (const reply of [reset(), httpStatus(503), slackError("internal_error")]) {+ const { connector, slack } = await setupSlack({ ...channelsOnly, "chat.postMessage": [reply] });+ const prepared = await prepareEng(connector);+ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);+ assert.equal(result.state, "unknown");+ assert.equal(result.checkUrl, "https://app.slack.com/client/T0TEST/C0ENG");+ assert.equal(posts(slack).length, 1);+ }+});++test("a reset while opening a DM is failed: the message was never posted", async () => {+ const { connector, slack } = await setupSlack({+ ...channelsOnly,+ "users.list": [ok(FIXTURES.people)],+ "conversations.open": [reset()],+ });+ const prepared = await connector.prepare(+ "send_message",+ { destination: "Gabe Smith", text: "hi" },+ BOUND+ );++ const result = await connector.commit("send_message", prepared.payload, {}, BOUND);++ assert.equal(result.state, "failed");+ assert.equal(posts(slack).length, 0);+});++test("edited text that is empty or too long is refused without calling Slack", async () => {+ const { connector, slack, SLACK_MESSAGE_LIMIT } = await setupSlack(channelsOnly);+ const prepared = await prepareEng(connector);++ assert.deepEqual(+ await connector.commit("send_message", prepared.payload, { body: " " }, BOUND),+ {+ state: "failed",+ errorCode: "no_text",+ message: "The message is empty.",+ }+ );+ const tooLong = await connector.commit(+ "send_message",+ prepared.payload,+ { body: "x".repeat(SLACK_MESSAGE_LIMIT + 1) },+ BOUND+ );+ assert.equal(tooLong.errorCode, "msg_too_long");+ assert.deepEqual(slack.methods(), ["users.conversations"]);+});++test("the length limit applies to what Slack receives, after escaping", async () => {+ const { connector, slack, formatMessage, SLACK_MESSAGE_LIMIT, SLACK_ESCAPE_SPECIALS } =+ await setupSlack(channelsOnly);+ const ampersands = "&".repeat(3000);++ if (!SLACK_ESCAPE_SPECIALS) {+ assert.equal(formatMessage(ampersands), ampersands, "nothing expands without escaping");+ return;+ }+ assert.ok(formatMessage(ampersands).length > SLACK_MESSAGE_LIMIT);+ const refused = await connector.prepare(+ "send_message",+ { destination: "#eng", text: ampersands },+ BOUND+ );+ assert.equal(refused.errorCode, "msg_too_long");+ const prepared = await prepareEng(connector);+ const atSend = await connector.commit(+ "send_message",+ prepared.payload,+ { body: ampersands },+ BOUND+ );+ assert.equal(atSend.errorCode, "msg_too_long");+ assert.deepEqual(slack.methods(), ["users.conversations"]);+});++test("mentions and special characters post exactly as the card showed them", async () => {+ const { connector, slack, escapeSpecials, SLACK_ESCAPE_SPECIALS } = await setupSlack({+ ...channelsOnly,+ "chat.postMessage": [ok(FIXTURES.posted)],+ });+ assert.equal(escapeSpecials("5 < 6 & 7 > 3 <!here>"), "5 < 6 & 7 > 3 <!here>");+ const text = "5 < 6 & <!here> <@U0GABE>";++ const prepared = await prepareEng(connector, text);+ assert.equal(prepared.preview.body, text, "the card shows what the model wrote");+ await connector.commit("send_message", prepared.payload, {}, BOUND);++ const posted = postedText(posts(slack)[0].params);+ assert.equal(posted, SLACK_ESCAPE_SPECIALS ? escapeSpecials(text) : text);+ if (SLACK_ESCAPE_SPECIALS) assert.equal(posted.includes("<!"), false);+});++test("a login that needs reconnecting fails prepare without calling Slack", async () => {+ const { connector, slack } = await setupSlack(+ {},+ { credential: { ...CONNECTED, needsReconnect: true } }+ );++ const prepared = await connector.prepare(+ "send_message",+ { destination: "#eng", text: "hi" },+ BOUND+ );++ assert.equal(prepared.status, "failed");+ assert.equal(prepared.errorCode, "reconnect_needed");+ assert.deepEqual(slack.calls, []);+});++test("authorize passes the connect's cancel signal on to Slack auth", async () => {+ const { createSlackConnector } =+ await import("../../../src/helpers/connectors/slackConnector.js");+ const seen = [];+ const connector = createSlackConnector({+ api: null,+ auth: { authorize: async (options) => seen.push(options) },+ directory: null,+ credentials: null,+ });+ const controller = new AbortController();++ await connector.authorize({ signal: controller.signal });++ assert.equal(seen[0].signal, controller.signal);+});++test("the binding and status follow the active account's login", async () => {+ const { connector, credentials } = await setupSlack({});+ assert.deepEqual(await connector.getBinding(), BINDING);++ credentials.replace("acct-1", "slack", { ...CONNECTED, userId: "U0OTHER" }, 1);+ assert.deepEqual(await connector.getBinding(), {+ ...BINDING,+ accountId: "U0OTHER",+ generation: 2,+ });++ credentials.switchAccount("acct-2");+ assert.equal(await connector.getBinding(), null);+ assert.deepEqual(await connector.getStatus(), NOT_CONNECTED);+});diff --git a/test/helpers/connectors/slackDirectory.test.js b/test/helpers/connectors/slackDirectory.test.jsnew file mode 100644index 000000000..ce97590de--- /dev/null+++ b/test/helpers/connectors/slackDirectory.test.js@@ -0,0 +1,121 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { NOW, FIXTURES, fakeSlackFetch, ok, slackError } = require("./slackFixtures");++const loadDirectory = () => import("../../../src/helpers/connectors/slackDirectory.js");+const loadApi = () => import("../../../src/helpers/connectors/slackApi.js");++async function setup(script) {+ const [{ createSlackDirectory }, { createSlackApi }] = await Promise.all([+ loadDirectory(),+ loadApi(),+ ]);+ const slack = fakeSlackFetch(script);+ const clock = { now: NOW };+ const directory = createSlackDirectory({+ api: createSlackApi({ fetchImpl: slack.fetchImpl, sleep: async () => {} }),+ now: () => clock.now,+ });+ return { directory, slack, clock };+}++test("channels page through cursors, skip archived ones, and stay cached for ten minutes", async () => {+ const page1 = {+ ok: true,+ channels: [FIXTURES.channels.channels[0]],+ response_metadata: { next_cursor: "c2" },+ };+ const page2 = {+ ok: true,+ channels: [+ FIXTURES.channels.channels[1],+ { id: "C0OLD", name: "old", is_archived: true, is_member: true },+ ],+ response_metadata: { next_cursor: "" },+ };+ const { directory, slack, clock } = await setup({+ "users.conversations": [ok(page1), ok(page2), ok(FIXTURES.channels)],+ });++ const first = await directory.channels("t", "k1");+ assert.deepEqual(+ first.items.map((channel) => channel.label),+ ["#eng", "#eng-backend"]+ );+ assert.equal(first.truncated, false);+ assert.equal(slack.calls[0].params.types, "public_channel,private_channel");+ assert.equal(slack.calls[0].params.exclude_archived, "true");+ assert.equal(slack.calls[1].params.cursor, "c2");++ await directory.channels("t", "k1");+ assert.equal(slack.calls.length, 2, "served from the cache");++ clock.now += 10 * 60 * 1000 + 1;+ const reloaded = await directory.channels("t", "k1");+ assert.equal(slack.calls.length, 3);+ assert.equal(reloaded.items.length, 3);+});++test("people skip bots, deleted users and Slackbot, and carry a handle hint", async () => {+ const { directory } = await setup({ "users.list": [ok(FIXTURES.people)] });++ const people = await directory.people("t", "k");++ assert.deepEqual(+ people.items.map((person) => person.id),+ ["U0CHAD", "U0GABE", "U0GABRIEL"]+ );+ assert.deepEqual(people.items[1], {+ id: "U0GABE",+ kind: "user",+ label: "Gabe Smith",+ hint: "Gabe Smith (@gabe)",+ names: ["gabe", "Gabe Smith"],+ });+});++test("a directory longer than ten pages is marked truncated", async () => {+ const endless = {+ ok: true,+ channels: [FIXTURES.channels.channels[0]],+ response_metadata: { next_cursor: "more" },+ };+ const { directory, slack } = await setup({ "users.conversations": [ok(endless)] });++ const result = await directory.channels("t", "k");++ assert.equal(result.truncated, true);+ assert.equal(slack.calls.length, 10);+});++test("a failed load is reported and not cached", async () => {+ const { directory, slack } = await setup({+ "users.conversations": [slackError("missing_scope"), ok(FIXTURES.channels)],+ });++ assert.deepEqual(await directory.channels("t", "k"), { ok: false, errorCode: "missing_scope" });+ assert.equal((await directory.channels("t", "k")).ok, true);+ assert.equal(slack.calls.length, 2);+});++test("an email finds a person; an unknown email is no match, not an error", async () => {+ const found = await setup({ "users.lookupByEmail": [ok(FIXTURES.lookupGabe)] });+ assert.equal(+ (await found.directory.personByEmail("t", "[email protected]")).candidate.id,+ "U0GABE"+ );+ assert.deepEqual(found.slack.calls[0].params, { email: "[email protected]" });++ const missing = await setup({ "users.lookupByEmail": [slackError("users_not_found")] });+ assert.deepEqual(await missing.directory.personByEmail("t", "[email protected]"), {+ ok: true,+ candidate: null,+ });+});++test("a new login never reads the old login's cache", async () => {+ const { directory, slack } = await setup({ "users.list": [ok(FIXTURES.people)] });+ await directory.people("t", "acct-1:T0TEST:U0CHAD:1");+ await directory.people("t", "acct-1:T0TEST:U0CHAD:2");+ assert.equal(slack.calls.length, 2);+});diff --git a/test/helpers/connectors/slackFixtures.js b/test/helpers/connectors/slackFixtures.jsnew file mode 100644index 000000000..4cfa153b5--- /dev/null+++ b/test/helpers/connectors/slackFixtures.js@@ -0,0 +1,261 @@+// Slack Web API replies for the connector tests. The shapes match responses+// recorded from the test workspace (plan Task 3); ids, names and tokens are+// synthetic. Never paste a real token, id or workspace name here.+const NOW = 1_800_000_000_000;++const FIXTURES = {+ exchange: {+ ok: true,+ app_id: "A0TEST",+ authed_user: {+ id: "U0CHAD",+ scope: "chat:write,channels:read,groups:read,im:write,users:read,users:read.email",+ access_token: "xoxe.xoxp-1-test-access",+ token_type: "user",+ refresh_token: "xoxe-1-test-refresh",+ expires_in: 43200,+ },+ team: { id: "T0TEST", name: "Acme Test" },+ enterprise: null,+ is_enterprise_install: false,+ },+ refresh: {+ ok: true,+ app_id: "A0TEST",+ user_id: "U0CHAD",+ scope: "chat:write,channels:read,groups:read,im:write,users:read,users:read.email",+ token_type: "user",+ access_token: "xoxe.xoxp-1-test-access-2",+ refresh_token: "xoxe-1-test-refresh-2",+ expires_in: 43200,+ team: { id: "T0TEST", name: "Acme Test" },+ enterprise: null,+ is_enterprise_install: false,+ },+ authTest: {+ ok: true,+ url: "https://acme-test.slack.com/",+ team: "Acme Test",+ user: "chad",+ team_id: "T0TEST",+ user_id: "U0CHAD",+ is_enterprise_install: false,+ },+ channels: {+ ok: true,+ channels: [+ {+ id: "C0ENG",+ name: "eng",+ is_channel: true,+ is_private: false,+ is_archived: false,+ },+ {+ id: "C0ENGBE",+ name: "eng-backend",+ is_channel: true,+ is_private: false,+ is_archived: false,+ },+ {+ id: "G0LEADS",+ name: "leads",+ is_channel: true,+ is_private: true,+ is_archived: false,+ },+ ],+ response_metadata: { next_cursor: "" },+ },+ people: {+ ok: true,+ members: [+ {+ id: "U0CHAD",+ name: "chad",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Chad Test", display_name: "chad" },+ },+ {+ id: "U0GABE",+ name: "gabe",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Gabe Smith", display_name: "gabe" },+ },+ {+ id: "U0GABRIEL",+ name: "gstone",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Gabriel Stone", display_name: "gstone" },+ },+ {+ id: "USLACKBOT",+ name: "slackbot",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Slackbot", display_name: "Slackbot" },+ },+ {+ id: "B0HELPER",+ name: "helper",+ deleted: false,+ is_bot: true,+ profile: { real_name: "Helper Bot", display_name: "helper" },+ },+ {+ id: "U0GONE",+ name: "gformer",+ deleted: true,+ is_bot: false,+ profile: { real_name: "Gabe Former", display_name: "gformer" },+ },+ ],+ response_metadata: { next_cursor: "" },+ },+ lookupGabe: {+ ok: true,+ user: {+ id: "U0GABE",+ name: "gabe",+ deleted: false,+ is_bot: false,+ profile: { real_name: "Gabe Smith", display_name: "gabe" },+ },+ },+ dmOpen: { ok: true, channel: { id: "D0GABE" } },+ posted: {+ ok: true,+ channel: "C0ENG",+ ts: "1727200000.123456",+ message: { type: "message", user: "U0CHAD", ts: "1727200000.123456" },+ },+ postedDm: {+ ok: true,+ channel: "D0GABE",+ ts: "1727200001.000100",+ message: { type: "message", user: "U0CHAD", ts: "1727200001.000100" },+ },+};++const CONNECTED = {+ accessToken: "xoxe.xoxp-1-test-access",+ refreshToken: "xoxe-1-test-refresh",+ expiresAt: NOW + 60 * 60 * 1000,+ refreshIssuedAt: NOW - 60 * 1000,+ userId: "U0CHAD",+ userName: "chad",+ teamId: "T0TEST",+ teamName: "Acme Test",+ teamUrl: "https://acme-test.slack.com/",+ needsReconnect: false,+};++// What a pending Slack action carries for CONNECTED in its slot at generation 1.+const BINDING = {+ ownerAccountId: "acct-1",+ accountId: "U0CHAD",+ workspaceId: "T0TEST",+ generation: 1,+};++// A scripted Slack: each method answers with its queued replies in order,+// and the last reply repeats.+function fakeSlackFetch(script) {+ const calls = [];+ const queues = new Map(Object.entries(script).map(([method, replies]) => [method, [...replies]]));+ const fetchImpl = async (url, init) => {+ const method = url.slice("https://slack.com/api/".length);+ calls.push({+ method,+ params: Object.fromEntries(new URLSearchParams(init.body)),+ authorization: init.headers.Authorization ?? null,+ contentType: init.headers["Content-Type"] ?? null,+ });+ const queue = queues.get(method);+ if (!queue || queue.length === 0) throw new Error(`unscripted Slack call: ${method}`);+ const reply = queue.length > 1 ? queue.shift() : queue[0];+ // Lets a test change state while this request is in flight.+ if (typeof reply.during === "function") reply.during();+ if (reply.throw) throw reply.throw;+ return new Response(reply.rawBody ?? JSON.stringify(reply.body ?? {}), {+ status: reply.status ?? 200,+ headers: { "content-type": "application/json", ...(reply.headers ?? {}) },+ });+ };+ return { fetchImpl, calls, methods: () => calls.map((call) => call.method) };+}++const ok = (body) => ({ body });+const slackError = (error, extra = {}) => ({ body: { ok: false, error, ...extra } });+const httpStatus = (status, headers = {}) => ({+ status,+ headers,+ body: { ok: false, error: status === 429 ? "ratelimited" : "http_error" },+});+const reset = () => ({ throw: Object.assign(new Error("socket hang up"), { code: "ECONNRESET" }) });+const offline = () => ({+ throw: Object.assign(new Error("getaddrinfo ENOTFOUND slack.com"), { code: "ENOTFOUND" }),+});++// Same shape as connectorCredentials (plan Task 12), in memory. `initial`+// becomes the `connectorId` login of `accountId` at generation 1.+function memoryCredentials(initial = null, { accountId = "acct-1", connectorId = "slack" } = {}) {+ const slots = new Map();+ let active = accountId;+ const saves = [];+ const keyOf = (account, connectorId) => `${account}:${connectorId}`;+ const generation = (account, connectorId) =>+ account ? (slots.get(keyOf(account, connectorId))?.generation ?? 0) : 0;+ const refuse = (code) => {+ throw Object.assign(new Error(code), { code });+ };+ const expect = (account, connectorId, expected) => {+ if (!account) refuse("signed_out");+ if (generation(account, connectorId) !== expected) refuse("connection_changed");+ };+ if (initial) slots.set(keyOf(accountId, connectorId), { credential: initial, generation: 1 });+ return {+ saves,+ switchAccount: (next) => {+ active = next;+ },+ activeAccountId: () => active,+ generation,+ read: (account, connectorId) => {+ const slot = account ? slots.get(keyOf(account, connectorId)) : null;+ return slot?.credential ? { credential: slot.credential, generation: slot.generation } : null;+ },+ replace: (account, connectorId, credential, expected) => {+ expect(account, connectorId, expected);+ slots.set(keyOf(account, connectorId), { credential, generation: expected + 1 });+ return expected + 1;+ },+ save: (account, connectorId, credential, expected) => {+ expect(account, connectorId, expected);+ saves.push(credential);+ slots.set(keyOf(account, connectorId), { credential, generation: expected });+ },+ clear: (account, connectorId, expected) => {+ expect(account, connectorId, expected);+ slots.set(keyOf(account, connectorId), { credential: null, generation: expected + 1 });+ },+ };+}++module.exports = {+ NOW,+ FIXTURES,+ CONNECTED,+ BINDING,+ fakeSlackFetch,+ ok,+ slackError,+ httpStatus,+ reset,+ offline,+ memoryCredentials,+};diff --git a/test/helpers/connectors/targetResolution.test.js b/test/helpers/connectors/targetResolution.test.jsnew file mode 100644index 000000000..c9a7fd94d--- /dev/null+++ b/test/helpers/connectors/targetResolution.test.js@@ -0,0 +1,72 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../../src/helpers/connectors/targetResolution.js");++const eng = { id: "C1", label: "#eng", names: ["eng"] };+const engBackend = { id: "C2", label: "#eng-backend", names: ["eng-backend"] };+const gabe = { id: "U1", label: "Gabe Smith", names: ["gabe", "Gabe Smith"] };+const gabriel = { id: "U2", label: "Gabriel Stone", names: ["gstone", "Gabriel Stone"] };+const zoe = { id: "U3", label: "Zoë Adams", names: ["zoe", "Zoë Adams"] };++test("an exact name wins over a longer one that starts the same", async () => {+ const { resolveTarget } = await load();+ assert.deepEqual(resolveTarget("eng", [engBackend, eng]), { status: "match", candidate: eng });+});++test("case, accents, spaces and punctuation don't matter", async () => {+ const { resolveTarget } = await load();+ assert.equal(resolveTarget("Eng Backend", [eng, engBackend]).candidate, engBackend);+ assert.equal(resolveTarget("zoe adams", [zoe, gabe]).candidate, zoe);+ assert.equal(resolveTarget("GABE SMITH", [gabe, gabriel]).candidate, gabe);+});++test("two prefix matches are ambiguous, never guessed", async () => {+ const { resolveTarget } = await load();+ assert.deepEqual(resolveTarget("gab", [gabe, gabriel]), {+ status: "ambiguous",+ candidates: [gabe, gabriel],+ });+});++test("a channel and a person with the same name are ambiguous", async () => {+ const { resolveTarget } = await load();+ const channel = { id: "C9", label: "#design", names: ["design"] };+ const person = { id: "U9", label: "Design Team", names: ["design", "Design Team"] };+ assert.equal(resolveTarget("design", [channel, person]).status, "ambiguous");+});++test("one candidate matched through two of its names counts once", async () => {+ const { resolveTarget } = await load();+ const twice = { id: "U4", label: "Sam", names: ["sam", "Sam"] };+ assert.deepEqual(resolveTarget("SAM", [twice]), { status: "match", candidate: twice });+});++test("exactOnly accepts only a character-for-character name", async () => {+ const { resolveTarget } = await load();+ assert.deepEqual(resolveTarget("eng", [eng], { exactOnly: true }), {+ status: "match",+ candidate: eng,+ });+ assert.deepEqual(resolveTarget("eng", [engBackend], { exactOnly: true }), { status: "none" });+ assert.deepEqual(resolveTarget("Eng", [eng], { exactOnly: true }), { status: "none" });+});++test("no match, or a query of punctuation only, is none", async () => {+ const { resolveTarget } = await load();+ assert.deepEqual(resolveTarget("ops", [eng, gabe]), { status: "none" });+ assert.deepEqual(resolveTarget("#!", [eng]), { status: "none" });+ assert.deepEqual(resolveTarget("", [eng]), { status: "none" });+});++test("an ambiguous result lists at most five candidates", async () => {+ const { resolveTarget, MAX_CANDIDATES } = await load();+ const teams = Array.from({ length: 7 }, (_, index) => ({+ id: `C${index}`,+ label: `#team-${index}`,+ names: [`team-${index}`],+ }));+ const result = resolveTarget("team", teams);+ assert.equal(result.status, "ambiguous");+ assert.equal(result.candidates.length, MAX_CANDIDATES);+});diff --git a/test/helpers/deviceCleanupContract.test.js b/test/helpers/deviceCleanupContract.test.jsindex e07231f75..d3b5f17ba 100644--- a/test/helpers/deviceCleanupContract.test.js+++ b/test/helpers/deviceCleanupContract.test.js@@ -37,4 +37,6 @@ test("explicit device cleanup covers models, credentials, caches, and browser sesource.includes('"account-scope-binding.json"'),"device cleanup removes the account scope binding");++ assert.ok(source.includes('"connectors"'), "device cleanup removes encrypted connector logins");});diff --git a/test/helpers/oauthLoopbackFlow.test.js b/test/helpers/oauthLoopbackFlow.test.jsindex 5885f6f77..cfaed8074 100644--- a/test/helpers/oauthLoopbackFlow.test.js+++ b/test/helpers/oauthLoopbackFlow.test.js@@ -22,10 +22,11 @@ function loadLoopback() {}}-function startFlow(handleCallback = async () => ({ ok: true })) {+function startFlow(handleCallback = async () => ({ ok: true }), options = {}) {const { runOAuthLoopbackFlow } = loadLoopback();let redirectUri;let state;+ let authUrlCalls = 0;let server;const originalCreateServer = http.createServer;http.createServer = (...args) => {@@ -36,14 +37,22 @@ function startFlow(handleCallback = async () => ({ ok: true })) {try {const flow = runOAuthLoopbackFlow({errorParam: "gcal_error",+ ...options,buildAuthUrl: (uri, flowState) => {redirectUri = uri;state = flowState;+ authUrlCalls += 1;return "https://example.test/auth";},handleCallback,});- return { flow, server, getRedirectUri: () => redirectUri, getState: () => state };+ return {+ flow,+ server,+ getRedirectUri: () => redirectUri,+ getState: () => state,+ getAuthUrlCalls: () => authUrlCalls,+ };} finally {http.createServer = originalCreateServer;}@@ -184,9 +193,7 @@ async function parkPartialRequest(redirectUri, server) {return {complete: (path) => {- socket.end(- `${path} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`- );+ socket.end(`${path} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`);return status;},destroy: () => socket.destroy(),@@ -244,13 +251,8 @@ test("a provider error query still fails the flow immediately", async () => {});test("a late state mismatch cannot reject a valid callback already in progress", async () => {- const {- flow,- getRedirectUri,- getState,- callbackStarted,- releaseHandleCallback,- } = startBlockedFlow();+ const { flow, getRedirectUri, getState, callbackStarted, releaseHandleCallback } =+ startBlockedFlow();const redirectUri = await waitForListen(getRedirectUri);const flowOutcome = flow.then(() => "resolved",@@ -284,13 +286,8 @@ test("a late state mismatch cannot reject a valid callback already in progress",});test("a late malformed request cannot reject a valid callback already in progress", async () => {- const {- flow,- getRedirectUri,- getState,- callbackStarted,- releaseHandleCallback,- } = startBlockedFlow();+ const { flow, getRedirectUri, getState, callbackStarted, releaseHandleCallback } =+ startBlockedFlow();const redirectUri = await waitForListen(getRedirectUri);const flowOutcome = flow.then(() => "resolved",@@ -411,3 +408,271 @@ test("an accepted callback cannot run after the flow times out", async () => {parkedRequest.destroy();}});++function freePort() {+ return new Promise((resolve, reject) => {+ const probe = net.createServer();+ probe.once("error", reject);+ probe.listen(0, "127.0.0.1", () => {+ const { port } = probe.address();+ probe.close(() => resolve(port));+ });+ });+}++function getLocal(url) {+ return new Promise((resolve, reject) => {+ http+ .get(url, (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (chunk) => {+ body += chunk;+ });+ res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body }));+ })+ .on("error", reject);+ });+}++async function until(read) {+ for (let attempt = 0; attempt < 200; attempt += 1) {+ const value = read();+ if (value) return value;+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ throw new Error("timed out waiting");+}++test("a fixed port, redirect host and path shape the redirect uri both times", async () => {+ const port = await freePort();+ const started = startFlow(async (code, redirectUri) => ({ code, redirectUri }), {+ redirectHost: "localhost",+ ports: [port],+ callbackPath: "/slack/callback",+ });+ const redirectUri = await until(started.getRedirectUri);+ assert.equal(redirectUri, `http://localhost:${port}/slack/callback`);++ await getLocal(`http://127.0.0.1:${port}/slack/callback?code=c1&state=${started.getState()}`);++ assert.deepEqual(await started.flow, {+ code: "c1",+ redirectUri: `http://localhost:${port}/slack/callback`,+ });+});++test("a busy fixed port falls through to the next with one browser launch; all busy rejects ports_busy", async () => {+ const blocker = net.createServer();+ await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve));+ const busy = blocker.address().port;+ const free = await freePort();+ try {+ const started = startFlow(async (code) => ({ code }), { ports: [busy, free] });+ assert.equal(await until(started.getRedirectUri), `http://127.0.0.1:${free}`);+ await getLocal(`http://127.0.0.1:${free}/?code=c2&state=${started.getState()}`);+ assert.deepEqual(await started.flow, { code: "c2" });+ assert.equal(started.getAuthUrlCalls(), 1, "exactly one browser launch");++ const allBusy = startFlow(async () => ({}), { ports: [busy] });+ await assert.rejects(allBusy.flow, (error) => error.code === "ports_busy");+ assert.equal(allBusy.getAuthUrlCalls(), 0);+ } finally {+ blocker.close();+ }+});++test("a local result page replaces the hosted desktop-callback redirect", async () => {+ const started = startFlow(async () => ({ ok: true }), {+ renderResultPage: ({ ok }) => `<p>${ok ? "connected" : "failed"}</p>`,+ });+ const redirectUri = await until(started.getRedirectUri);++ const response = await getLocal(`${redirectUri}/?code=c3&state=${started.getState()}`);++ assert.equal(response.status, 200);+ assert.equal(response.headers.location, undefined);+ assert.equal(response.body, "<p>connected</p>");+ await started.flow;+});++test("a denied consent rejects with oauth_denied and shows the failure page", async () => {+ const started = startFlow(async () => ({}), {+ renderResultPage: ({ ok }) => (ok ? "yes" : "no"),+ });+ const redirectUri = await until(started.getRedirectUri);+ const outcome = started.flow.catch((error) => error);++ const response = await getLocal(+ `${redirectUri}/?error=access_denied&state=${started.getState()}`+ );++ assert.equal(response.body, "no");+ const error = await outcome;+ assert.equal(error.code, "oauth_denied");+ assert.equal(error.providerError, "access_denied");+});++const RELAY = "https://openwhispr.com/auth/slack/callback";++test("behind a relay, the public redirect URI goes to the provider and the exchange, and state carries the port", async () => {+ const started = startFlow(async (code, redirectUri) => ({ code, redirectUri }), {+ publicRedirectUri: RELAY,+ callbackPath: "/slack/callback",+ });+ assert.equal(await until(started.getRedirectUri), RELAY);+ const port = started.server.address().port;+ assert.match(started.getState(), new RegExp(`^v1\\.${port}\\.[0-9a-f]{64}$`));++ // What the relay does with Slack's redirect.+ await getLocal(`http://127.0.0.1:${port}/slack/callback?code=c4&state=${started.getState()}`);++ assert.deepEqual(await started.flow, { code: "c4", redirectUri: RELAY });+ assert.equal(started.getAuthUrlCalls(), 1);+});++test("behind a relay, the right port with another nonce is a state mismatch", async () => {+ const started = startFlow(async () => ({ ok: true }), { publicRedirectUri: RELAY });+ await until(started.getRedirectUri);+ const port = started.server.address().port;+ const outcome = started.flow.catch((error) => error);++ await getLocal(`http://127.0.0.1:${port}/?code=c5&state=v1.${port}.${"0".repeat(64)}`);++ assert.equal((await outcome).code, "oauth_state_mismatch");+});++test("without a relay, the state stays a bare nonce", async () => {+ const started = startFlow(async (code) => ({ code }));+ await until(started.getRedirectUri);+ assert.match(started.getState(), /^[0-9a-f]{64}$/);++ await getLocal(`${started.getRedirectUri()}/?code=c6&state=${started.getState()}`);++ assert.deepEqual(await started.flow, { code: "c6" });+});++test("timeoutMs bounds how long the flow waits", { timeout: 5000 }, async () => {+ const started = startFlow(async () => ({}), { timeoutMs: 30 });+ await assert.rejects(started.flow, (error) => error.code === "oauth_timeout");+});++test("an abort closes the server and rejects oauth_cancelled", async () => {+ const controller = new AbortController();+ let callbackCount = 0;+ const started = startFlow(+ async () => {+ callbackCount += 1;+ return {};+ },+ { signal: controller.signal }+ );+ const redirectUri = await until(started.getRedirectUri);+ const outcome = started.flow.catch((error) => error);++ controller.abort();++ assert.equal((await outcome).code, "oauth_cancelled");+ assert.equal(started.server.listening, false);+ await assert.rejects(getLocal(`${redirectUri}/?code=late&state=${started.getState()}`));+ assert.equal(callbackCount, 0);+});++test("a flow whose signal is already aborted never opens the browser", async () => {+ const controller = new AbortController();+ controller.abort();+ const started = startFlow(async () => ({}), { signal: controller.signal });++ await assert.rejects(started.flow, (error) => error.code === "oauth_cancelled");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(started.getAuthUrlCalls(), 0);+});++test("an abort after the provider answered lets the exchange finish", async () => {+ const controller = new AbortController();+ let release;+ let markStarted;+ const exchangeStarted = new Promise((resolve) => {+ markStarted = resolve;+ });+ const started = startFlow(+ async (code) => {+ markStarted();+ await new Promise((resolve) => {+ release = resolve;+ });+ return { code };+ },+ { signal: controller.signal }+ );+ const redirectUri = await until(started.getRedirectUri);++ const response = getLocal(`${redirectUri}/?code=c9&state=${started.getState()}`);+ await exchangeStarted;+ controller.abort();+ release();++ // The caller decides what to do with a login it no longer wants; the flow+ // never drops one the provider already issued.+ assert.deepEqual(await started.flow, { code: "c9" });+ assert.equal((await response).status, 302);+});++async function stillWaiting(flow) {+ return Promise.race([+ flow.then(+ () => "resolved",+ () => "rejected"+ ),+ new Promise((resolve) => setTimeout(() => resolve("pending"), 100)),+ ]);+}++test("behind a relay, an error without this flow's state is a stray request, not a denial", async () => {+ const started = startFlow(async (code) => ({ code }), { publicRedirectUri: RELAY });+ await until(started.getRedirectUri);+ const port = started.server.address().port;++ const bare = await getLocal(`http://127.0.0.1:${port}/anything?error=access_denied`);+ const otherState = await getLocal(+ `http://127.0.0.1:${port}/?error=access_denied&state=v1.${port}.${"0".repeat(64)}`+ );++ assert.equal(bare.status, 400);+ assert.equal(otherState.status, 400);+ assert.equal(await stillWaiting(started.flow), "pending");+ await getLocal(`http://127.0.0.1:${port}/?code=c7&state=${started.getState()}`);+ assert.deepEqual(await started.flow, { code: "c7" });+});++test("behind a relay, an error with this flow's state still denies", async () => {+ const started = startFlow(async () => ({}), { publicRedirectUri: RELAY });+ await until(started.getRedirectUri);+ const port = started.server.address().port;+ const outcome = started.flow.catch((error) => error);++ await getLocal(`http://127.0.0.1:${port}/?error=access_denied&state=${started.getState()}`);++ assert.equal((await outcome).code, "oauth_denied");+});++test("with a callback path, only that path is a callback", async () => {+ const started = startFlow(async (code) => ({ code }), {+ publicRedirectUri: RELAY,+ callbackPath: "/slack/callback",+ });+ await until(started.getRedirectUri);+ const port = started.server.address().port;+ const state = started.getState();++ const wrongPathCode = await getLocal(`http://127.0.0.1:${port}/other?code=stray&state=${state}`);+ const wrongPathError = await getLocal(+ `http://127.0.0.1:${port}/other?error=access_denied&state=${state}`+ );++ assert.equal(wrongPathCode.status, 400);+ assert.equal(wrongPathError.status, 400);+ assert.equal(await stillWaiting(started.flow), "pending");+ await getLocal(`http://127.0.0.1:${port}/slack/callback?code=c8&state=${state}`);+ assert.deepEqual(await started.flow, { code: "c8" });+});diff --git a/test/helpers/useChatStreamingConnectors.test.js b/test/helpers/useChatStreamingConnectors.test.jsnew file mode 100644index 000000000..7e2f162c7--- /dev/null+++ b/test/helpers/useChatStreamingConnectors.test.js@@ -0,0 +1,107 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++// Plan 1's final review asked for this once a real approval tool existed: a+// send whose stream throws while a Slack card waits must withdraw the card+// (not_sent, conversation_ended) rather than leave it for its 10-minute expiry.+// Same harness technique as useChatStreamingCancellation.test.js: one SSR+// render yields sendToAI, which is then called like any closure.+test("a send that throws withdraws a pending approval", async (t) => {+ const cancels = [];+ installBrowserGlobals(t, {+ initialStorage: { isSubscribed: "true" },+ window: {+ electronAPI: {+ connectorStatus: async () => [+ {+ id: "slack",+ connected: true,+ accountLabel: "chad",+ workspaceLabel: "Acme",+ needsReconnect: false,+ },+ ],+ onConnectorStatusChanged: () => () => {},+ connectorPrepare: async () => ({+ status: "ready",+ actionId: "a1",+ preview: {+ verbKey: "slackPost",+ destinationLabel: "#eng",+ accountLabel: "chad",+ workspaceLabel: "Acme",+ body: "Hi team",+ },+ }),+ connectorCancel: async (actionId, reason) => {+ cancels.push({ actionId, reason });+ return { cancelled: true };+ },+ },+ },+ });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-chat-streaming-connectors-test-",+ });+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ const approvals = await vite.ssrLoadModule("/stores/connectorApprovalStore.ts");+ approvals.useConnectorApprovalStore.setState({ entries: {} });+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.8.3", policy: null });+ // A tool-eligible self-hosted (LAN) agent, as in the cancellation tests.+ useSettingsStore.setState({+ chatAgentMode: "self-hosted",+ chatAgentProvider: "lan",+ chatAgentModel: "qwen3-4b-q4_k_m",+ chatAgentRemoteUrl: "http://127.0.0.1:11434/v1",+ chatAgentDisableThinking: true,+ isSignedIn: true,+ });++ const { useChatStreaming } = await vite.ssrLoadModule("/components/chat/useChatStreaming.ts");+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;+ t.after(() => reasoningService.destroy());++ let sawSlackTool = false;+ t.mock.method(+ reasoningService,+ "processTextStreamingAI",+ (_messages, _model, _provider, _config, tools) => {+ sawSlackTool = Boolean(tools?.slack_send_message);+ // Must stay an async generator so the hook's `for await` sees it; it+ // throws before ever reaching a yield, which is the point of this test.+ // eslint-disable-next-line require-yield+ return (async function* () {+ void tools.slack_send_message.execute(+ { destination: "#eng", text: "Hi team" },+ { toolCallId: "call-1", messages: [] }+ );+ while (Object.keys(approvals.useConnectorApprovalStore.getState().entries).length === 0) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ throw new Error("provider stream failed");+ })();+ }+ );++ let messages = [];+ const setMessages = (updater) => {+ messages = typeof updater === "function" ? updater(messages) : updater;+ };+ let captured = null;+ function Harness() {+ captured = useChatStreaming({ messages, setMessages, allowConnectors: true });+ return null;+ }+ renderToStaticMarkup(React.createElement(Harness));++ await captured.sendToAI("post hi to eng", []).catch(() => {});++ assert.equal(sawSlackTool, true);+ const [entry] = Object.values(approvals.useConnectorApprovalStore.getState().entries);+ assert.equal(entry.state, "not_sent");+ assert.deepEqual(cancels, [{ actionId: "a1", reason: "conversation_ended" }]);+});diff --git a/test/lib/interactiveDom.js b/test/lib/interactiveDom.jsindex 9e74891e7..a2eb5a96d 100644--- a/test/lib/interactiveDom.js+++ b/test/lib/interactiveDom.js@@ -149,6 +149,12 @@ function installInteractiveDom(t) {nodeType: 9,nodeName: "#document",activeElement: null,+ // Tells react-dom's feature detection ("oninput" in document) that native+ // input events are supported, so it skips its legacy IE9-and-below+ // keydown/keyup value-change polyfill — that path calls attachEvent,+ // which this fake DOM doesn't implement, and crashes on any keydown+ // dispatched at a text input or textarea.+ oninput: null,createElement: (tagName) => new FakeElement(tagName, document),createElementNS: (namespaceURI, tagName) => new FakeElement(tagName, document, namespaceURI),createTextNode: (value) => new FakeText(String(value), document),diff --git a/test/services/connectorToolOutcome.test.js b/test/services/connectorToolOutcome.test.jsindex 6bfdf986f..c928352f5 100644--- a/test/services/connectorToolOutcome.test.js+++ b/test/services/connectorToolOutcome.test.js@@ -14,17 +14,29 @@ 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.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.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,+ approvalOutcomeResult(+ { state: "failed", errorCode: "not_in_channel", message: "Not a member" },+ "#eng"+ ).data.error,"Not a member");const unknown = approvalOutcomeResult({ state: "unknown" }, "#eng").data;@@ -36,7 +48,13 @@ test("every approval outcome tells the model what happened and whether to retry"test("runApprovalAction without a chat context refuses to prepare", async (t) => {let prepared = 0;installBrowserGlobals(t, {- window: { electronAPI: { connectorPrepare: async () => { prepared += 1; } } },+ window: {+ electronAPI: {+ connectorPrepare: async () => {+ prepared += 1;+ },+ },+ },});const { runApprovalAction } = await loadRun();const result = await runApprovalAction(undefined, "slack", "send_message", {});@@ -59,7 +77,7 @@ test("runApprovalAction passes clarifications straight back to the model", asyncconst { runApprovalAction } = await loadRun();const controller = new AbortController();const result = await runApprovalAction(- { toolCallId: "call-1", signal: controller.signal, onApprovalRequested() {} },+ { messageId: "m1", toolCallId: "call-1", signal: controller.signal, onApprovalRequested() {} },"slack","send_message",{ destination: "#eng" }@@ -78,7 +96,12 @@ test("runApprovalAction waits for the card and returns the send", async (t) => {connectorPrepare: async () => ({status: "ready",actionId: "a1",- preview: { verbKey: "default", destinationLabel: "#eng", accountLabel: "chad", body: "hi" },+ preview: {+ verbKey: "default",+ destinationLabel: "#eng",+ accountLabel: "chad",+ body: "hi",+ },}),connectorCommit: async () => ({ state: "sent", url: "https://slack.test/p/9" }),connectorCancel: async () => ({ cancelled: true }),@@ -86,18 +109,18 @@ test("runApprovalAction waits for the card and returns the send", async (t) => {},});const { runApprovalAction } = await loadRun();- const { approveAction, useConnectorApprovalStore } = await loadStore();+ const { approvalKey, approveAction, useConnectorApprovalStore } = await loadStore();useConnectorApprovalStore.setState({ entries: {} });const controller = new AbortController();const pending = runApprovalAction(- { toolCallId: "call-2", signal: controller.signal, onApprovalRequested() {} },+ { messageId: "m1", toolCallId: "call-2", signal: controller.signal, onApprovalRequested() {} },"slack","send_message",{ destination: "#eng", text: "hi" });await new Promise((resolve) => setImmediate(resolve));- await approveAction("call-2");+ await approveAction(approvalKey("m1", "call-2"));const result = await pending;assert.equal(result.data.status, "sent");@@ -105,19 +128,68 @@ test("runApprovalAction waits for the card and returns the send", async (t) => {});test("tool steps show the user plain, localized outcomes instead of codes", async () => {- const { unavailableResult, failedResult, needsClarificationResult, notSentResult, approvalOutcomeResult } =- await loadOutcome();+ 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(+ 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."+ );+ // A code with no toolStatus.errors translation falls back to the generic text.+ assert.equal(failedResult("mystery_error", "raw provider text").displayText, "That didn't work.");+ // The tool step maps codes exactly as the card does.+ assert.equal(failedResult("token_revoked", "raw").displayText, "Slack needs to be reconnected.");+ assert.equal(failedResult("ratelimited", "raw").displayText, "Slack is busy.");+ assert.equal(+ failedResult("ENOTFOUND", "raw").displayText,+ "Couldn't reach Slack. Nothing was sent."+ );+ assert.equal(+ failedResult("user_not_found", "raw").displayText,+ "Couldn't open the direct message. Nothing was sent."+ );+ assert.equal(+ failedResult("restricted_action", "raw").displayText,+ "That channel is read-only or restricted."+ );+ assert.equal(+ failedResult("credential_save_failed", "raw").displayText,+ "Couldn't save the Slack login on this computer. Nothing was sent."+ );+ // The model still gets the connector's own code and message.+ assert.deepEqual(failedResult("token_revoked", "raw").data, {+ status: "failed",+ errorCode: "token_revoked",+ error: "raw",+ });+ 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.");+ 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.");+ 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.jsindex 523784cc4..d6ff73223 100644--- a/test/services/connectorTools.test.js+++ b/test/services/connectorTools.test.js@@ -4,6 +4,8 @@ const { installBrowserGlobals, createRendererServer } = require("../lib/rendererconst loadEmail = () => import("../../src/services/tools/connectors/emailDraftTool.ts");const loadContact = () => import("../../src/services/tools/connectors/findContactTool.ts");+const loadSlack = () => import("../../src/services/tools/connectors/slackSendMessageTool.ts");+const loadApprovals = () => import("../../src/stores/connectorApprovalStore.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.@@ -142,6 +144,7 @@ test("email_draft keeps only the address from a display-name recipient", async (function countingContext(signal = new AbortController().signal) {const context = {holds: 0,+ messageId: "m1",preservesClipboard: false,toolCallId: "call-1",signal,@@ -156,6 +159,139 @@ function countingContext(signal = new AbortController().signal) {return context;}+function toolContext(messageId, toolCallId, held = { count: 0 }) {+ return {+ messageId,+ toolCallId,+ signal: new AbortController().signal,+ onApprovalRequested() {},+ onHoldDelivery() {+ held.count += 1;+ },+ claimTurnSlot: () => true,+ };+}++test("slack_send_message prepares in main, passes a clarification through, and holds delivery", async (t) => {+ const prepared = [];+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorPrepare: async (...args) => {+ prepared.push(args);+ return {+ status: "needs_clarification",+ message: 'More than one match for "gab". Ask the user which one they meant.',+ candidates: ["Gabe Smith (@gabe)", "Gabriel Stone (@gstone)"],+ };+ },+ },+ },+ });+ const { slackSendMessageTool } = await loadSlack();+ const held = { count: 0 };++ const result = await slackSendMessageTool.execute(+ { destination: " gab ", text: "hi" },+ toolContext("m1", "call-1", held)+ );++ assert.deepEqual(prepared, [["slack", "send_message", { destination: "gab", text: "hi" }]]);+ assert.equal(result.data.status, "needs_clarification");+ assert.deepEqual(result.data.candidates, ["Gabe Smith (@gabe)", "Gabriel Stone (@gstone)"]);+ assert.equal(held.count, 1, "the question stays in the panel, never pasted at the caret");+});++test("slack_send_message turns a channel that vanished by Send into a question", async (t) => {+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorPrepare: async () => ({+ status: "ready",+ actionId: "a9",+ preview: {+ verbKey: "slackPost",+ destinationLabel: "#eng",+ accountLabel: "chad",+ workspaceLabel: "Acme",+ body: "hi",+ },+ }),+ connectorCommit: async () => ({+ state: "failed",+ errorCode: "channel_not_found",+ message: "#eng couldn't be found in Slack anymore.",+ }),+ connectorCancel: async () => ({ cancelled: true }),+ },+ },+ });+ const [{ slackSendMessageTool }, approvals] = await Promise.all([loadSlack(), loadApprovals()]);+ approvals.useConnectorApprovalStore.setState({ entries: {} });+ const key = approvals.approvalKey("m9", "call-9");++ const pending = slackSendMessageTool.execute(+ { destination: "#eng", text: "hi" },+ toolContext("m9", "call-9")+ );+ while (!approvals.useConnectorApprovalStore.getState().entries[key]) {+ await new Promise((resolve) => setImmediate(resolve));+ }+ await approvals.approveAction(key);+ const result = await pending;++ assert.equal(result.data.status, "needs_clarification");+ assert.match(result.data.message, /#eng/);+ assert.equal(+ approvals.useConnectorApprovalStore.getState().entries[key].errorCode,+ "channel_not_found"+ );+});++test("slack_send_message refuses empty text without preparing", async (t) => {+ let prepared = 0;+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorPrepare: async () => {+ prepared += 1;+ },+ },+ },+ });+ const { slackSendMessageTool } = await loadSlack();++ const result = await slackSendMessageTool.execute(+ { destination: "#eng", text: " " },+ toolContext("m1", "call-2")+ );++ assert.equal(result.data.status, "failed");+ assert.equal(result.data.errorCode, "no_text");+ assert.equal(prepared, 0);+});++test("slack_send_message registers only when Slack is ready", async () => {+ const { createToolRegistry } = await loadRegistry();+ const base = {+ isSignedIn: true,+ calendarConnected: false,+ cloudBackupEnabled: false,+ webSearchEnabled: false,+ };+ const names = (connectors) =>+ createToolRegistry({ ...base, connectors })+ .getAll()+ .map((tool) => tool.name);++ assert.ok(names({ emailDraftTarget: "gmail", slackReady: true }).includes("slack_send_message"));+ assert.equal(+ names({ emailDraftTarget: "gmail", slackReady: false }).includes("slack_send_message"),+ false+ );+ assert.equal(names(undefined).includes("slack_send_message"), false);+});+const loadScope = () => import("../../src/components/chat/toolExecutionScope.ts");test("email_draft opens at most three drafts per turn", async (t) => {@@ -175,7 +311,10 @@ test("email_draft opens at most three drafts per turn", async (t) => {const scope = createToolExecutionScope();const tool = createEmailDraftTool("gmail");const draft = (id) =>- tool.execute({ to: ["[email protected]"], subject: "s", body: "b" }, scope.createContext(id));+ tool.execute(+ { to: ["[email protected]"], subject: "s", body: "b" },+ scope.createContext({ messageId: "m1", toolCallId: id })+ );// The AI SDK runs a step's tool calls in parallel.const results = await Promise.all(["1", "2", "3", "4"].map(draft));@@ -187,7 +326,7 @@ test("email_draft opens at most three drafts per turn", async (t) => {);assert.equal(results[3].data.reason, "draft_limit");// A new turn starts over.- const next = createToolExecutionScope().createContext("5");+ const next = createToolExecutionScope().createContext({ messageId: "m1", toolCallId: "5" });assert.equal((await tool.execute({ to: ["[email protected]"], subject: "s", body: "b" }, next)).data.status,"draft_opened"@@ -220,15 +359,18 @@ test("only one draft per turn may put its text on the clipboard", async (t) => {const [first, second] = await Promise.all([tool.execute({ to: ["[email protected]"], subject: "Recap", body: longBody },- scope.createContext("1")+ scope.createContext({ messageId: "m1", toolCallId: "1" })),tool.execute({ to: ["[email protected]"], subject: "Recap", body: longBody },- scope.createContext("2")+ scope.createContext({ messageId: "m1", toolCallId: "2" })),]);const short = (id, address) =>- tool.execute({ to: [address], subject: "Hi", body: "Short one." }, scope.createContext(id));+ tool.execute(+ { to: [address], subject: "Hi", body: "Short one." },+ scope.createContext({ messageId: "m1", toolCallId: 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]");@@ -269,7 +411,12 @@ test("a draft that didn't open gives back its draft and clipboard slots", asyncconst statuses = [];for (const id of ["1", "2", "3", "4"]) {statuses.push(- (await createEmailDraftTool("mailto").execute(draft, scope.createContext(id))).data.status+ (+ await createEmailDraftTool("mailto").execute(+ draft,+ scope.createContext({ messageId: "m1", toolCallId: id })+ )+ ).data.status);}@@ -300,8 +447,14 @@ test("a draft whose outcome is unknown says so, and keeps the clipboard claimed"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"));+ const first = await tool.execute(+ draft,+ scope.createContext({ messageId: "m1", toolCallId: "1" })+ );+ const second = await tool.execute(+ draft,+ scope.createContext({ messageId: "m1", toolCallId: "2" })+ );assert.equal(first.data.status, "unknown");assert.match(first.data.guidance, /The draft to josh@example\.com may or may not have opened/);@@ -343,6 +496,41 @@ test("email_draft tells the model when content went to the clipboard", async (t));});+test("email_draft reports an uncertain direct result as unknown, and still holds delivery", async (t) => {+ installBrowserGlobals(t, {+ window: {+ electronAPI: {+ connectorRunDirect: async () => ({+ state: "unknown",+ errorCode: "direct_failed",+ message: "That action may have gone through. Ask the user to check before trying again.",+ }),+ },+ },+ });+ const { createEmailDraftTool } = await loadEmail();+ let held = 0;+ const context = {+ messageId: "m1",+ toolCallId: "call-1",+ signal: new AbortController().signal,+ onApprovalRequested() {},+ onHoldDelivery() {+ held += 1;+ },+ claimTurnSlot: () => true,+ };++ const result = await createEmailDraftTool("mailto").execute(+ { to: ["[email protected]"], subject: "s", body: "b" },+ context+ );++ assert.equal(result.data.status, "unknown");+ assert.equal(result.data.destination, "[email protected]");+ assert.equal(held, 1);+});+test("email_draft guidance names exactly what went to the clipboard", async (t) => {const results = [{ subjectCopied: true, bodyCopied: false }, { copyFailed: true }];installBrowserGlobals(t, {@@ -683,4 +871,8 @@ test("the system prompt adds connector rules only when a connector tool is prese// 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/);++ const withSlack = getAgentSystemPrompt(["slack_send_message"]);+ assert.match(withSlack, /Use slack_send_message/);+ assert.match(withSlack, /needs_clarification/);});diff --git a/test/services/toolExecutionContext.test.js b/test/services/toolExecutionContext.test.jsindex 526850b31..09980b5a3 100644--- a/test/services/toolExecutionContext.test.js+++ b/test/services/toolExecutionContext.test.js@@ -26,6 +26,7 @@ test("toAISDKFormat gives each call its own tool-call id and the shared scope",const controller = new AbortController();const onApprovalRequested = () => {};const tools = registry.toAISDKFormat((toolCallId) => ({+ messageId: "m1",toolCallId,signal: controller.signal,onApprovalRequested,@@ -81,8 +82,8 @@ test("a tool execution scope shares one signal and aborts it once", async () =>holds.push(options);},});- const first = scope.createContext("call-a");- const second = scope.createContext("call-b");+ const first = scope.createContext({ messageId: "m1", toolCallId: "call-a" });+ const second = scope.createContext({ messageId: "m1", toolCallId: "call-b" });assert.equal(first.toolCallId, "call-a");assert.equal(first.signal, second.signal);@@ -108,7 +109,7 @@ test("a scope's notices do nothing once its turn has ended", async () => {notices += 1;},});- const context = scope.createContext("call-d");+ const context = scope.createContext({ messageId: "m1", toolCallId: "call-d" });// A slow tool result arriving after Esc must not reopen a dismissed panel.scope.abort();@@ -121,15 +122,20 @@ test("a scope's notices do nothing once its turn has ended", async () => {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");+ const first = scope.createContext({ messageId: "m1", toolCallId: "call-e" });+ const second = scope.createContext({ messageId: "m1", toolCallId: "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);+ assert.equal(+ createToolExecutionScope()+ .createContext({ messageId: "m1", toolCallId: "call-g" })+ .claimTurnSlot("draft", 2),+ true+ );});test("executeTool settles an aborted call at once and never runs one after the abort", async () => {@@ -146,14 +152,21 @@ test("executeTool settles an aborted call at once and never runs one after the a};const scope = createToolExecutionScope();- const pending = executeTool(hanging, {}, scope.createContext("call-h"));+ const pending = executeTool(+ hanging,+ {},+ scope.createContext({ messageId: "m1", toolCallId: "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.deepEqual(+ await executeTool(hanging, {}, scope.createContext({ messageId: "m1", toolCallId: "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));@@ -162,7 +175,10 @@ test("executeTool settles an aborted call at once and never runs one after the atest("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");+ const context = createToolExecutionScope().createContext({+ messageId: "m1",+ toolCallId: "call-j",+ });assert.deepEqual(await executeTool(recordingTool([]), { a: 1 }, context), {success: true,data: { ok: true },@@ -215,7 +231,9 @@ test("an aborted AI SDK turn ends even when a tool never settles", async () => {const result = streamText({model,messages: [{ role: "user", content: "hi" }],- tools: registry.toAISDKFormat(scope.createContext),+ tools: registry.toAISDKFormat((toolCallId, signal) =>+ scope.createContext({ messageId: "m1", toolCallId, signal })+ ),stopWhen: stepCountIs(5),abortSignal: streamAbort.signal,});@@ -239,7 +257,10 @@ test("an aborted AI SDK turn ends even when a tool never settles", async () => {test("a scope without handlers ignores approval and delivery notices", async () => {const { createToolExecutionScope } = await loadScope();- const context = createToolExecutionScope().createContext("call-c");+ const context = createToolExecutionScope().createContext({+ messageId: "m1",+ toolCallId: "call-c",+ });assert.doesNotThrow(() => context.onApprovalRequested());assert.doesNotThrow(() => context.onHoldDelivery());});@@ -282,3 +303,47 @@ test("the cloud tool loop passes each call's id to executeToolCall", async (t) =assert.deepEqual(received, [{ name: "record_context", toolCallId: "call-9" }]);});++test("toAISDKFormat hands the SDK's own abort signal to the context factory", async () => {+ const { ToolRegistry } = await loadRegistry();+ const seen = [];+ const registry = new ToolRegistry();+ registry.register(recordingTool(seen));+ const factoryCalls = [];+ const tools = registry.toAISDKFormat((toolCallId, abortSignal) => {+ factoryCalls.push({ toolCallId, abortSignal });+ return {+ messageId: "m1",+ toolCallId,+ signal: abortSignal ?? new AbortController().signal,+ onApprovalRequested() {},+ onHoldDelivery() {},+ };+ });+ const sdk = new AbortController();++ await tools.record_context.execute(+ {},+ { toolCallId: "call-1", messages: [], abortSignal: sdk.signal }+ );++ assert.equal(factoryCalls[0].toolCallId, "call-1");+ assert.equal(factoryCalls[0].abortSignal, sdk.signal);+});++test("a context signal aborts when either its turn or its own SDK call aborts", async () => {+ const { createToolExecutionScope } = await loadScope();+ const scope = createToolExecutionScope();+ const sdk = new AbortController();+ const linked = scope.createContext({ messageId: "m1", toolCallId: "call-a", signal: sdk.signal });+ const plain = scope.createContext({ messageId: "m1", toolCallId: "call-b" });++ assert.equal(linked.messageId, "m1");+ assert.equal(linked.signal.aborted, false);+ sdk.abort();+ assert.equal(linked.signal.aborted, true);+ assert.equal(plain.signal.aborted, false, "one call's SDK abort leaves the other calls alone");++ scope.abort();+ assert.equal(plain.signal.aborted, true);+});diff --git a/test/stores/connectorApprovalStore.test.js b/test/stores/connectorApprovalStore.test.jsindex cdfd53852..a951693d0 100644--- a/test/stores/connectorApprovalStore.test.js+++ b/test/stores/connectorApprovalStore.test.js@@ -28,12 +28,13 @@ function fakeElectron(commitImpl) {};}-function context(toolCallId, controller = new AbortController()) {+function context(toolCallId, controller = new AbortController(), messageId = "m1") {let requested = 0;return {controller,requestedCount: () => requested,value: {+ messageId,toolCallId,signal: controller.signal,onApprovalRequested: () => {@@ -43,6 +44,8 @@ function context(toolCallId, controller = new AbortController()) {};}+const keyOf = (store, toolCallId, messageId = "m1") => store.approvalKey(messageId, toolCallId);+async function freshStore() {const store = await load();store.useConnectorApprovalStore.setState({ entries: {} });@@ -57,10 +60,13 @@ test("a request shows a pending card and tells the surface", async (t) => {void store.requestApproval(ctx.value, { actionId: "a1", connectorId: "slack", preview: PREVIEW });- assert.equal(store.useConnectorApprovalStore.getState().entries["call-1"].state, "pending");+ assert.equal(+ store.useConnectorApprovalStore.getState().entries[keyOf(store, "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");+ store.cancelApproval(keyOf(store, "call-1"));});test("Send commits the edited draft once and reports the edited text", async (t) => {@@ -73,8 +79,11 @@ test("Send commits the edited draft once and reports the edited text", async (t)preview: PREVIEW,});- store.updateApprovalDraft("call-2", { body: "Hello team!" });- await Promise.all([store.approveAction("call-2"), store.approveAction("call-2")]);+ store.updateApprovalDraft(keyOf(store, "call-2"), { body: "Hello team!" });+ await Promise.all([+ store.approveAction(keyOf(store, "call-2")),+ store.approveAction(keyOf(store, "call-2")),+ ]);assert.deepEqual(await outcome, {state: "sent",@@ -82,7 +91,10 @@ test("Send commits the edited draft once and reports the edited text", async (t)finalText: "Hello team!",});assert.deepEqual(electron.calls.commit, [{ actionId: "a2", edits: { body: "Hello team!" } }]);- assert.equal(store.useConnectorApprovalStore.getState().entries["call-2"].state, "sent");+ assert.equal(+ store.useConnectorApprovalStore.getState().entries[keyOf(store, "call-2")].state,+ "sent"+ );});test("an unedited send commits the preview text and reports no edit", async (t) => {@@ -95,7 +107,7 @@ test("an unedited send commits the preview text and reports no edit", async (t)preview: PREVIEW,});- await store.approveAction("call-8");+ await store.approveAction(keyOf(store, "call-8"));assert.deepEqual(await outcome, { state: "sent", url: "https://slack.test/p/1" });assert.deepEqual(electron.calls.commit[0].edits, { body: "Hello team" });@@ -111,9 +123,9 @@ test("the draft is frozen once sending starts, and a title needs a titled previepreview: PREVIEW,});- store.updateApprovalDraft("call-9", { title: "Not allowed" });- const sending = store.approveAction("call-9");- store.updateApprovalDraft("call-9", { body: "Too late" });+ store.updateApprovalDraft(keyOf(store, "call-9"), { title: "Not allowed" });+ const sending = store.approveAction(keyOf(store, "call-9"));+ store.updateApprovalDraft(keyOf(store, "call-9"), { body: "Too late" });await sending;await outcome;@@ -130,7 +142,7 @@ test("Cancel withdraws a pending card", async (t) => {preview: PREVIEW,});- store.cancelApproval("call-3");+ store.cancelApproval(keyOf(store, "call-3"));assert.deepEqual(await outcome, { state: "cancelled" });assert.deepEqual(electron.calls.cancel, [{ actionId: "a3", reason: "cancelled_by_user" }]);@@ -170,7 +182,7 @@ test("ending the conversation during Send keeps the real result", async (t) => {preview: PREVIEW,});- const sending = store.approveAction("call-5");+ const sending = store.approveAction(keyOf(store, "call-5"));ctx.controller.abort();releaseCommit();await sending;@@ -191,7 +203,7 @@ test("a commit IPC failure is reported as unknown, never as not sent", async (t)preview: PREVIEW,});- await store.approveAction("call-6");+ await store.approveAction(keyOf(store, "call-6"));assert.deepEqual(await outcome, { state: "unknown" });});@@ -223,10 +235,13 @@ test("a commit result with the wrong key settles as unknown instead of hanging",preview: PREVIEW,});- await store.approveAction("call-10");+ await store.approveAction(keyOf(store, "call-10"));assert.deepEqual(await outcome, { state: "unknown" });- assert.equal(store.useConnectorApprovalStore.getState().entries["call-10"].state, "unknown");+ assert.equal(+ store.useConnectorApprovalStore.getState().entries[keyOf(store, "call-10")].state,+ "unknown"+ );});test("a commit result with an unknown state settles as unknown instead of hanging", async (t) => {@@ -239,10 +254,13 @@ test("a commit result with an unknown state settles as unknown instead of hanginpreview: PREVIEW,});- await store.approveAction("call-12");+ await store.approveAction(keyOf(store, "call-12"));assert.deepEqual(await outcome, { state: "unknown" });- assert.equal(store.useConnectorApprovalStore.getState().entries["call-12"].state, "unknown");+ assert.equal(+ store.useConnectorApprovalStore.getState().entries[keyOf(store, "call-12")].state,+ "unknown"+ );});test("a commit result that resolves undefined settles as unknown", async (t) => {@@ -255,10 +273,13 @@ test("a commit result that resolves undefined settles as unknown", async (t) =>preview: PREVIEW,});- await store.approveAction("call-11");+ await store.approveAction(keyOf(store, "call-11"));assert.deepEqual(await outcome, { state: "unknown" });- assert.equal(store.useConnectorApprovalStore.getState().entries["call-11"].state, "unknown");+ assert.equal(+ store.useConnectorApprovalStore.getState().entries[keyOf(store, "call-11")].state,+ "unknown"+ );});test("a duplicate request for the same tool call cancels the new action and leaves the first alone", async (t) => {@@ -283,14 +304,96 @@ test("a duplicate request for the same tool call cancels the new action and leav{ actionId: "a12-second", reason: "cancelled_by_user" },]);- const entry = store.useConnectorApprovalStore.getState().entries["call-12"];+ const entry = store.useConnectorApprovalStore.getState().entries[keyOf(store, "call-12")];assert.equal(entry.state, "pending");assert.equal(entry.actionId, "a12-first");- await store.approveAction("call-12");+ await store.approveAction(keyOf(store, "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" } },]);});++test("a policy check that couldn't finish returns the card to pending", async (t) => {+ let attempt = 0;+ const electron = fakeElectron(() => {+ attempt += 1;+ return attempt === 1+ ? { state: "not_sent", reason: "policy_unavailable", retryable: true }+ : { state: "sent", url: "https://slack.test/p/2" };+ });+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });+ const store = await freshStore();+ const outcome = store.requestApproval(context("call-r").value, {+ actionId: "ar",+ connectorId: "slack",+ preview: PREVIEW,+ });+ const key = keyOf(store, "call-r");++ await store.approveAction(key);+ const afterFirst = store.useConnectorApprovalStore.getState().entries[key];+ assert.equal(afterFirst.state, "pending");+ assert.equal(afterFirst.notice, "policy_retry");++ await store.approveAction(key);+ assert.deepEqual(await outcome, { state: "sent", url: "https://slack.test/p/2" });+ assert.equal(store.useConnectorApprovalStore.getState().entries[key].notice, undefined);+ assert.equal(electron.calls.commit.length, 2);+});++test("a conversation that ended during a retryable Send withdraws the card", async (t) => {+ const controller = new AbortController();+ const electron = fakeElectron(() => {+ controller.abort();+ return { state: "not_sent", reason: "policy_unavailable", retryable: true };+ });+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });+ const store = await freshStore();+ const outcome = store.requestApproval(context("call-s", controller).value, {+ actionId: "as",+ connectorId: "slack",+ preview: PREVIEW,+ });++ await store.approveAction(keyOf(store, "call-s"));++ assert.deepEqual(await outcome, { state: "not_sent", reason: "conversation_ended" });+ assert.deepEqual(+ electron.calls.cancel.map((call) => call.reason),+ ["conversation_ended"]+ );+});++test("the same tool-call id on two messages gets two separate cards", async (t) => {+ const electron = fakeElectron();+ installBrowserGlobals(t, { window: { electronAPI: electron.api } });+ const store = await freshStore();+ const first = store.requestApproval(context("call-1", undefined, "msg-a").value, {+ actionId: "a1",+ connectorId: "slack",+ preview: PREVIEW,+ });+ const second = store.requestApproval(context("call-1", undefined, "msg-b").value, {+ actionId: "a2",+ connectorId: "slack",+ preview: PREVIEW,+ });++ const entries = store.useConnectorApprovalStore.getState().entries;+ assert.equal(entries[keyOf(store, "call-1", "msg-a")].actionId, "a1");+ assert.equal(entries[keyOf(store, "call-1", "msg-b")].actionId, "a2");+ assert.deepEqual(electron.calls.cancel, [], "a reused id on a new message is not a duplicate");++ await store.approveAction(keyOf(store, "call-1", "msg-b"));+ assert.deepEqual(+ electron.calls.commit.map((call) => call.actionId),+ ["a2"]+ );+ assert.equal((await second).state, "sent");++ store.cancelApproval(keyOf(store, "call-1", "msg-a"));+ assert.equal((await first).state, "cancelled");+});diff --git a/test/stores/connectorStatusStore.test.js b/test/stores/connectorStatusStore.test.jsnew file mode 100644index 000000000..f49e85565--- /dev/null+++ b/test/stores/connectorStatusStore.test.js@@ -0,0 +1,96 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const SLACK = {+ id: "slack",+ connected: true,+ accountLabel: "chad",+ workspaceLabel: "Acme",+ needsReconnect: false,+};++async function loadStore(t, electronAPI) {+ installBrowserGlobals(t, { window: { electronAPI } });+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-connector-status-store-test-",+ });+ return vite.ssrLoadModule("/stores/connectorStatusStore.ts");+}++test("status loads once, follows broadcasts, and a pending reconnect is not ready", async (t) => {+ let listener = null;+ let loads = 0;+ const store = await loadStore(t, {+ connectorStatus: async () => {+ loads += 1;+ return [SLACK];+ },+ onConnectorStatusChanged: (callback) => {+ listener = callback;+ return () => {};+ },+ });++ await store.ensureConnectorStatus();+ await store.ensureConnectorStatus();+ assert.equal(loads, 1);+ assert.equal(store.isConnectorReady("slack"), true);++ listener([{ ...SLACK, needsReconnect: true }]);+ assert.equal(store.isConnectorReady("slack"), false);++ listener([+ {+ id: "email",+ connected: true,+ accountLabel: null,+ workspaceLabel: null,+ needsReconnect: false,+ },+ ]);+ assert.equal(store.isConnectorReady("slack"), false);+ assert.equal(store.isConnectorReady("email"), true);+});++test("an older status response never overwrites a newer broadcast", async (t) => {+ let listener = null;+ let answerLoad;+ const store = await loadStore(t, {+ connectorStatus: () =>+ new Promise((resolve) => {+ answerLoad = resolve;+ }),+ onConnectorStatusChanged: (callback) => {+ listener = callback;+ return () => {};+ },+ });++ const loading = store.ensureConnectorStatus();+ listener([{ ...SLACK, connected: false }]); // Disconnect announced while the load is in flight+ answerLoad([SLACK]); // the load's older snapshot, still connected+ await loading;++ assert.equal(store.isConnectorReady("slack"), false);+});++test("a failed load leaves connectors off and is retried by the next ensure", async (t) => {+ let attempts = 0;+ const store = await loadStore(t, {+ connectorStatus: async () => {+ attempts += 1;+ if (attempts === 1) throw new Error("ipc down");+ return [SLACK];+ },+ onConnectorStatusChanged: () => () => {},+ });++ await store.ensureConnectorStatus();+ assert.equal(store.isConnectorReady("slack"), false);+ assert.equal(store.useConnectorStatusStore.getState().loaded, false);++ await store.ensureConnectorStatus();+ assert.equal(store.isConnectorReady("slack"), true);+ assert.equal(attempts, 2);+});diff --git a/test/utils/connectorErrorCopy.test.js b/test/utils/connectorErrorCopy.test.jsnew file mode 100644index 000000000..b588a0c79--- /dev/null+++ b/test/utils/connectorErrorCopy.test.js@@ -0,0 +1,130 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");++let connectorErrorCopyKey;++test.before(async () => {+ ({ connectorErrorCopyKey } = await import("../../src/utils/connectorErrorCopy.ts"));+});++const en = JSON.parse(+ fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")+).connectors;++test("codes with their own copy map to themselves", () => {+ for (const code of [+ "not_in_channel",+ "channel_not_found",+ "is_archived",+ "reconnect_needed",+ "connection_changed",+ "rate_limited",+ "missing_scope",+ "msg_too_long",+ "no_text",+ "credential_save_failed",+ "open_failed",+ "draft_too_long",+ "invalid_address",+ ]) {+ assert.equal(connectorErrorCopyKey(code), code);+ }+});++test("a refused or revoked login reads as reconnect_needed, Slack's other spelling as rate_limited", () => {+ for (const code of ["invalid_auth", "account_inactive", "not_authed", "token_revoked"]) {+ assert.equal(connectorErrorCopyKey(code), "reconnect_needed", code);+ }+ assert.equal(connectorErrorCopyKey("ratelimited"), "rate_limited");+});++test("a request that never reached Slack, or a refresh Slack couldn't answer, reads as network", () => {+ for (const code of [+ "ENOTFOUND",+ "ECONNREFUSED",+ "EAI_AGAIN",+ "ECONNRESET",+ "ERR_INTERNET_DISCONNECTED",+ "UND_ERR_CONNECT_TIMEOUT",+ "network_error",+ "timeout",+ "http_500",+ "http_503",+ "internal_error",+ "service_unavailable",+ ]) {+ assert.equal(connectorErrorCopyKey(code), "network", code);+ }+});++test("a DM Slack wouldn't open reads as dm_failed", () => {+ for (const code of [+ "user_not_found",+ "user_not_visible",+ "user_disabled",+ "cannot_dm_bot",+ "not_enough_users",+ "too_many_users",+ "users_list_not_supplied",+ "method_not_supported_for_channel_type",+ ]) {+ assert.equal(connectorErrorCopyKey(code), "dm_failed", code);+ }+});++test("a read-only or restricted channel reads as restricted", () => {+ for (const code of [+ "restricted_action",+ "restricted_action_read_only_channel",+ "ekm_access_denied",+ ]) {+ assert.equal(connectorErrorCopyKey(code), "restricted", code);+ }+});++test("everything else, including a missing code, reads as generic", () => {+ for (const code of [+ "invalid_arguments",+ "http_400",+ "http_404",+ "bad_response",+ "action_failed",+ "clipboard_unreserved",+ "weird_code",+ "constructor",+ "__proto__",+ "",+ undefined,+ null,+ ]) {+ assert.equal(connectorErrorCopyKey(code), "generic", String(code));+ }+});++test("every key the card and the tool step can show has English copy", () => {+ const cardKeys = [+ "not_in_channel",+ "channel_not_found",+ "is_archived",+ "reconnect_needed",+ "connection_changed",+ "rate_limited",+ "missing_scope",+ "msg_too_long",+ "no_text",+ "credential_save_failed",+ "network",+ "dm_failed",+ "restricted",+ "generic",+ ];+ const emailOnlyKeys = ["open_failed", "draft_too_long", "invalid_address"];+ for (const key of cardKeys) {+ assert.equal(typeof en.approval.errors[key], "string", `approval.errors.${key}`);+ }+ for (const key of [...cardKeys, ...emailOnlyKeys]) {+ assert.equal(typeof en.toolStatus.errors[key], "string", `toolStatus.errors.${key}`);+ }+});