Skip to content

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

fix(meetings): offer sign-in when a Cloud note recording has no valid session (#2435)

void9a115143efb2
diff --git a/src/components/MeetingRecordingMount.tsx b/src/components/MeetingRecordingMount.tsx
index abc2e87b0..49db6d8bd 100644
--- a/src/components/MeetingRecordingMount.tsx
+++ b/src/components/MeetingRecordingMount.tsx
@@ -11,6 +11,7 @@ import {
} from "../stores/meetingRecordingStore";
import { requestMeetingRecordingAutoEnd } from "../helpers/meetingRecordingSession";
import logger from "../utils/logger";
+import { requestSignIn } from "../utils/requestSignIn";
const EMA_PREV = 0.5;
const EMA_NEXT = 0.5;
@@ -23,6 +24,9 @@ const MEETING_ERROR_KEYS: Record<string, string> = {
unsupportedSelfHosted: "notes.meeting.unsupportedSelfHosted",
unsupportedProvider: "notes.meeting.unsupportedProvider",
noProviderSelected: "notes.meeting.noProviderSelected",
+ signInRequired: "notes.meeting.signInRequired",
+ // Mid-recording, so no Sign in action: signing in reloads this window and the recording with it.
+ signInExpired: "notes.meeting.signInExpired",
};
export default function MeetingRecordingMount(): null {
@@ -75,10 +79,14 @@ export default function MeetingRecordingMount(): null {
if (!error) return;
const [sentinel, argument] = error.split(":");
const errorKey = MEETING_ERROR_KEYS[sentinel];
+ const needsSignIn = sentinel === "signInRequired";
toast({
title: t("notes.meeting.title"),
description: errorKey ? t(errorKey, { provider: argument }) : error,
variant: "destructive",
+ duration: needsSignIn || sentinel === "signInExpired" ? 8000 : undefined,
+ actions: needsSignIn ? [{ label: t("common.signIn"), onClick: requestSignIn }] : undefined,
+ actionsAlign: needsSignIn ? "end" : undefined,
});
// errorNonce re-fires this toast when the same error repeats back-to-back.
}, [error, errorNonce, toast, t]);
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index d9dcc311e..47c72cff5 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -575,7 +575,7 @@ function TranscriptionSection({
description: t("settingsPage.transcription.modes.openwhisprDesc"),
icon: <Cloud className="w-4 h-4" />,
disabled: !isSignedIn,
- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
+ signInRequired: !isSignedIn,
},
{
id: "providers",
@@ -2235,22 +2235,20 @@ export default function SettingsPage({
}}
/>
- <SettingsPanel>
- <SettingsPanelRow>
- <Button
- onClick={handleSignOut}
- variant="outline"
- disabled={isSigningOut}
- size="sm"
- className="w-full text-destructive border-destructive/30 hover:bg-destructive/10 hover:border-destructive/50"
- >
- <LogOut className="me-1.5 h-3.5 w-3.5" />
- {isSigningOut
- ? t("settingsPage.account.signOut.signingOut")
- : t("settingsPage.account.signOut.signOut")}
- </Button>
- </SettingsPanelRow>
- </SettingsPanel>
+ <div className="flex justify-end">
+ <Button
+ onClick={handleSignOut}
+ variant="outline"
+ disabled={isSigningOut}
+ size="sm"
+ className="text-destructive border-destructive/30 hover:bg-destructive/10 hover:border-destructive/50"
+ >
+ <LogOut className="me-1.5 h-3.5 w-3.5" />
+ {isSigningOut
+ ? t("settingsPage.account.signOut.signingOut")
+ : t("settingsPage.account.signOut.signOut")}
+ </Button>
+ </div>
<SettingsPanel>
<SettingsPanelRow>
@@ -4654,156 +4652,158 @@ EOF`,
</SettingsPanelRow>
)}
- <SettingsPanelRow>
- <div className="space-y-2.5">
- <Button
- onClick={async () => {
- try {
- const result = await checkForUpdates();
- if (result && !result.updateAvailable) {
- toast({
- title: t("settingsPage.general.updates.dialogs.noUpdates.title"),
+ {(isUpdateAvailable ||
+ updateStatus.updateDownloaded ||
+ updateInfo?.releaseNotes) && (
+ <SettingsPanelRow>
+ <div className="space-y-2.5">
+ {isUpdateAvailable && !updateStatus.updateDownloaded && (
+ <div className="space-y-2">
+ <Button
+ onClick={async () => {
+ try {
+ await downloadUpdate();
+ } catch {
+ showAlertDialog({
+ title: t(
+ "settingsPage.general.updates.dialogs.downloadFailed.title"
+ ),
+ description: t(
+ "settingsPage.general.updates.dialogs.downloadFailed.description"
+ ),
+ });
+ }
+ }}
+ disabled={downloadingUpdate}
+ variant="success"
+ className="w-full"
+ size="sm"
+ >
+ <Download
+ size={13}
+ className={`me-1.5 ${downloadingUpdate ? "animate-pulse" : ""}`}
+ />
+ {downloadingUpdate
+ ? t("settingsPage.general.updates.downloading", {
+ progress: Math.round(updateDownloadProgress),
+ })
+ : t("settingsPage.general.updates.downloadUpdate", {
+ version: updateInfo?.version || "",
+ })}
+ </Button>
+
+ {downloadingUpdate && (
+ <div className="h-1 w-full overflow-hidden rounded-full bg-muted/50">
+ <div
+ className="h-full bg-success transition-[width] duration-200 rounded-full"
+ style={{
+ width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%`,
+ }}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
+ {updateStatus.updateDownloaded && (
+ <Button
+ onClick={() => {
+ showConfirmDialog({
+ title: t("settingsPage.general.updates.dialogs.installUpdate.title"),
description: t(
- "settingsPage.general.updates.dialogs.noUpdates.description"
+ "settingsPage.general.updates.dialogs.installUpdate.description",
+ { version: updateInfo?.version || "" }
+ ),
+ confirmText: t(
+ "settingsPage.general.updates.dialogs.installUpdate.confirmText"
),
+ onConfirm: async () => {
+ try {
+ await installUpdateAction();
+ } catch {
+ showAlertDialog({
+ title: t(
+ "settingsPage.general.updates.dialogs.installFailed.title"
+ ),
+ description: t(
+ "settingsPage.general.updates.dialogs.installFailed.description"
+ ),
+ });
+ }
+ },
});
- }
- } catch {
- showAlertDialog({
- title: t("settingsPage.general.updates.dialogs.checkFailed.title"),
- description: t(
- "settingsPage.general.updates.dialogs.checkFailed.description"
- ),
- });
- }
- }}
- disabled={
- checkingForUpdates ||
- updateStatus.isDevelopment ||
- !updateStatus.isSupported
- }
- variant="outline"
- className="w-full"
- size="sm"
- >
- <RefreshCw
- size={13}
- className={`me-1.5 ${checkingForUpdates ? "animate-spin" : ""}`}
- />
- {checkingForUpdates
- ? t("settingsPage.general.updates.checking")
- : t("settingsPage.general.updates.checkForUpdates")}
- </Button>
-
- {isUpdateAvailable && !updateStatus.updateDownloaded && (
- <div className="space-y-2">
- <Button
- onClick={async () => {
- try {
- await downloadUpdate();
- } catch {
- showAlertDialog({
- title: t(
- "settingsPage.general.updates.dialogs.downloadFailed.title"
- ),
- description: t(
- "settingsPage.general.updates.dialogs.downloadFailed.description"
- ),
- });
- }
}}
- disabled={downloadingUpdate}
- variant="success"
+ disabled={installInitiated}
className="w-full"
size="sm"
>
- <Download
- size={13}
- className={`me-1.5 ${downloadingUpdate ? "animate-pulse" : ""}`}
+ <RefreshCw
+ size={14}
+ className={`me-2 ${installInitiated ? "animate-spin" : ""}`}
/>
- {downloadingUpdate
- ? t("settingsPage.general.updates.downloading", {
- progress: Math.round(updateDownloadProgress),
- })
- : t("settingsPage.general.updates.downloadUpdate", {
- version: updateInfo?.version || "",
- })}
+ {installInitiated
+ ? t("settingsPage.general.updates.restarting")
+ : t("settingsPage.general.updates.installAndRestart")}
</Button>
+ )}
+ </div>
- {downloadingUpdate && (
- <div className="h-1 w-full overflow-hidden rounded-full bg-muted/50">
- <div
- className="h-full bg-success transition-[width] duration-200 rounded-full"
- style={{
- width: `${Math.min(100, Math.max(0, updateDownloadProgress))}%`,
- }}
- />
- </div>
- )}
- </div>
- )}
-
- {updateStatus.updateDownloaded && (
- <Button
- onClick={() => {
- showConfirmDialog({
- title: t("settingsPage.general.updates.dialogs.installUpdate.title"),
- description: t(
- "settingsPage.general.updates.dialogs.installUpdate.description",
- { version: updateInfo?.version || "" }
- ),
- confirmText: t(
- "settingsPage.general.updates.dialogs.installUpdate.confirmText"
- ),
- onConfirm: async () => {
- try {
- await installUpdateAction();
- } catch {
- showAlertDialog({
- title: t(
- "settingsPage.general.updates.dialogs.installFailed.title"
- ),
- description: t(
- "settingsPage.general.updates.dialogs.installFailed.description"
- ),
- });
- }
- },
- });
- }}
- disabled={installInitiated}
- className="w-full"
- size="sm"
- >
- <RefreshCw
- size={14}
- className={`me-2 ${installInitiated ? "animate-spin" : ""}`}
+ {updateInfo?.releaseNotes && (
+ <div className="mt-4 pt-4 border-t border-border/70">
+ <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
+ <BidiInterpolatedText
+ text={t("settingsPage.general.updates.whatsNew", {
+ version: BIDI_VALUE_TOKEN,
+ })}
+ value={updateInfo.version}
+ />
+ </p>
+ <div
+ className="text-xs text-muted-foreground [&_ul]:list-disc [&_ul]:ps-4 [&_ul]:space-y-1 [&_ol]:list-decimal [&_ol]:ps-4 [&_ol]:space-y-1 [&_li]:ps-1 [&_p]:mb-2 [&_p:last-child]:mb-0 [&_a]:text-link [&_a]:underline"
+ dangerouslySetInnerHTML={{ __html: updateInfo.releaseNotes }}
/>
- {installInitiated
- ? t("settingsPage.general.updates.restarting")
- : t("settingsPage.general.updates.installAndRestart")}
- </Button>
+ </div>
)}
- </div>
-
- {updateInfo?.releaseNotes && (
- <div className="mt-4 pt-4 border-t border-border/70">
- <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
- <BidiInterpolatedText
- text={t("settingsPage.general.updates.whatsNew", {
- version: BIDI_VALUE_TOKEN,
- })}
- value={updateInfo.version}
- />
- </p>
- <div
- className="text-xs text-muted-foreground [&_ul]:list-disc [&_ul]:ps-4 [&_ul]:space-y-1 [&_ol]:list-decimal [&_ol]:ps-4 [&_ol]:space-y-1 [&_li]:ps-1 [&_p]:mb-2 [&_p:last-child]:mb-0 [&_a]:text-link [&_a]:underline"
- dangerouslySetInnerHTML={{ __html: updateInfo.releaseNotes }}
- />
- </div>
- )}
- </SettingsPanelRow>
+ </SettingsPanelRow>
+ )}
</SettingsPanel>
+ <div className="mt-5 flex justify-end">
+ <Button
+ onClick={async () => {
+ try {
+ const result = await checkForUpdates();
+ if (result && !result.updateAvailable) {
+ toast({
+ title: t("settingsPage.general.updates.dialogs.noUpdates.title"),
+ description: t(
+ "settingsPage.general.updates.dialogs.noUpdates.description"
+ ),
+ });
+ }
+ } catch {
+ showAlertDialog({
+ title: t("settingsPage.general.updates.dialogs.checkFailed.title"),
+ description: t(
+ "settingsPage.general.updates.dialogs.checkFailed.description"
+ ),
+ });
+ }
+ }}
+ disabled={
+ checkingForUpdates || updateStatus.isDevelopment || !updateStatus.isSupported
+ }
+ variant="outline"
+ size="sm"
+ >
+ <RefreshCw
+ size={13}
+ className={`me-1.5 ${checkingForUpdates ? "animate-spin" : ""}`}
+ />
+ {checkingForUpdates
+ ? t("settingsPage.general.updates.checking")
+ : t("settingsPage.general.updates.checkForUpdates")}
+ </Button>
+ </div>
</div>
{/* Developer Tools */}
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 261f908fe..239df3444 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -88,7 +88,7 @@ export default function InferenceConfigEditor({
description: t(`${prefix}.openwhisprDesc`),
icon: <Cloud className="w-4 h-4" />,
disabled: !isSignedIn,
- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
+ signInRequired: !isSignedIn,
},
{
id: "providers",
diff --git a/src/components/settings/MeetingSettings.tsx b/src/components/settings/MeetingSettings.tsx
index 0acbc4c14..b71c3895d 100644
--- a/src/components/settings/MeetingSettings.tsx
+++ b/src/components/settings/MeetingSettings.tsx
@@ -5,6 +5,7 @@ import { useSettingsStore } from "../../stores/settingsStore";
import { usePolicyModeOptions, usePolicySnapshot } from "../../hooks/usePolicy";
import { isModeAllowedByPolicy } from "../../stores/policyRules";
import { requestSignIn } from "../../utils/requestSignIn";
+import { Button } from "../ui/button";
import { InferenceModeSelector, SettingsRow } from "../ui/SettingsSection";
import type { InferenceModeOption } from "../ui/SettingsSection";
import { Toggle } from "../ui/toggle";
@@ -85,7 +86,7 @@ export function MeetingTranscriptionPanel() {
description: t("settingsPage.transcription.modes.openwhisprDesc"),
icon: <Cloud className="w-4 h-4" />,
disabled: !isSignedIn,
- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
+ signInRequired: !isSignedIn,
},
{
id: "providers",
@@ -191,6 +192,14 @@ export function MeetingTranscriptionPanel() {
onSelect={handleTranscriptionModeSelect}
/>
+ {effectiveTranscriptionMode === "openwhispr" && !isSignedIn && (
+ <p className="text-sm text-muted-foreground">
+ {t("settingsPage.transcription.meetingCloudSignedOut")}{" "}
+ <Button variant="link" className="h-auto p-0" onClick={requestSignIn}>
+ {t("common.signIn")}
+ </Button>
+ </p>
+ )}
{effectiveTranscriptionMode === "providers" && renderTranscriptionPicker("cloud")}
{effectiveTranscriptionMode === "local" && renderTranscriptionPicker("local")}
<MeetingSpeakerDetectionRow />
diff --git a/src/components/settings/UploadSettings.tsx b/src/components/settings/UploadSettings.tsx
index 295bc0df2..0844c69de 100644
--- a/src/components/settings/UploadSettings.tsx
+++ b/src/components/settings/UploadSettings.tsx
@@ -57,7 +57,7 @@ export function UploadTranscriptionPanel() {
description: t("settingsPage.transcription.modes.openwhisprDesc"),
icon: <Cloud className="w-4 h-4" />,
disabled: !isSignedIn,
- badge: !isSignedIn ? t("common.freeAccountRequired") : undefined,
+ signInRequired: !isSignedIn,
},
{
id: "providers",
diff --git a/src/components/ui/SettingsSection.tsx b/src/components/ui/SettingsSection.tsx
index e8c3e69ba..d661adefd 100644
--- a/src/components/ui/SettingsSection.tsx
+++ b/src/components/ui/SettingsSection.tsx
@@ -148,6 +148,8 @@ export interface InferenceModeOption {
id: InferenceMode;
disabled?: boolean;
badge?: string;
+ /** Clicking the tile asks the user to sign in, so it reads as an action, not as disabled. */
+ signInRequired?: boolean;
label: string;
description: string;
icon: React.ReactNode;
@@ -169,17 +171,18 @@ export function InferenceModeSelector({
{modes.map((mode) => {
const isActive = activeMode === mode.id;
const isDisabled = !!mode.disabled;
+ const isDimmed = isDisabled && !mode.signInRequired;
return (
<SettingsPanelRow
key={mode.id}
className={`transition-colors ${
- isDisabled ? "" : "hover:bg-foreground/3 dark:hover:bg-white/3"
+ isDimmed ? "" : "hover:bg-foreground/3 dark:hover:bg-white/3"
}`}
>
<button
onClick={() => onSelect(mode.id)}
className={`w-full flex items-center gap-3 text-start cursor-pointer group ${
- isDisabled ? "opacity-60" : ""
+ isDimmed ? "opacity-60" : ""
}`}
>
<div
@@ -203,6 +206,11 @@ export function InferenceModeSelector({
{t("common.active")}
</span>
)}
+ {mode.signInRequired && (
+ <span className="text-xs font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm group-hover:underline">
+ {t("common.signInRequired")}
+ </span>
+ )}
{isDisabled && mode.badge && (
<span className="text-xs font-medium text-muted-foreground bg-muted/80 dark:bg-surface-3 px-1.5 py-px rounded-sm">
{mode.badge}
diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsx
index 54cf73558..a00d9cd96 100644
--- a/src/components/ui/Toast.tsx
+++ b/src/components/ui/Toast.tsx
@@ -328,6 +328,7 @@ const Toast: React.FC<
technicalDetails,
action,
actions,
+ actionsAlign = "start",
presentation = "standard",
variant = "default",
duration = 3500,
@@ -503,7 +504,12 @@ const Toast: React.FC<
)}
<TechnicalErrorDetails details={technicalDetails} onDark />
{rowActions && (
- <div className="mt-2 flex items-center gap-1.5">
+ <div
+ className={cn(
+ "mt-2 flex items-center gap-1.5",
+ actionsAlign === "end" && "justify-end"
+ )}
+ >
{rowActions.map((rowAction, index) => (
<StandardToastAction
key={`${rowAction.label}-${index}`}
diff --git a/src/components/ui/useToast.ts b/src/components/ui/useToast.ts
index 623311045..3c80fa924 100644
--- a/src/components/ui/useToast.ts
+++ b/src/components/ui/useToast.ts
@@ -30,6 +30,8 @@ export interface ToastProps {
technicalDetails?: TechnicalErrorDetailsData;
action?: React.ReactNode;
actions?: ToastActionConfig[];
+ /** Which side of a standard toast its `actions` row sits on; start by default. */
+ actionsAlign?: "start" | "end";
presentation?: ToastPresentation;
variant?: "default" | "destructive" | "success";
duration?: number;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 5e6794f18..8ed38c978 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -180,7 +180,11 @@ const {
getMeetingStreamingClient,
getMeetingConnectionKey,
} = require("./meetingStreamingProviders");
-const { fetchRealtimeTokenForProvider } = require("./realtimeTokenProviders");
+const {
+ createServerTokenPoster,
+ fetchRealtimeTokenForProvider,
+ isSignInRefusal,
+} = require("./realtimeTokenProviders");
const { getCalendarAvailability } = require("./calendarAvailabilityService");
// Meeting capture runs at 24 kHz (see meetingRecordingStore AudioContext); cloud
@@ -7600,7 +7604,12 @@ class IPCHandlers {
}
resetMeetingReconnectAudio();
if (!win.isDestroyed()) {
- win.webContents.send("meeting-transcription-error", error.message);
+ // A renewal refused for the session gets a sentinel the renderer explains,
+ // instead of the API's bare "Invalid session" (#2427).
+ win.webContents.send(
+ "meeting-transcription-error",
+ isSignInRefusal(error) ? "signInExpired" : error.message
+ );
}
return canRestoreOld;
}
@@ -7613,39 +7622,13 @@ class IPCHandlers {
};
const fetchRealtimeToken = async (event, options, { streams } = {}) => {
- const postServerToken = async (path, body = {}) => {
- const apiUrl = getApiUrl();
- if (!apiUrl) {
- const err = new Error("OpenWhispr API URL not configured");
- err.code = "NO_API";
- throw err;
- }
- const authHeader = await getAuthHeader(event);
- if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
- const url = `${apiUrl}${path}`;
- let response;
- try {
- response = await proxyFetch(url, {
- method: "POST",
- headers: withPolicyHeaders({ "Content-Type": "application/json", ...authHeader }),
- body: JSON.stringify(body),
- });
- } catch (err) {
- const classified = classifyAndLog(err, url);
- if (classified.isNetworkError) {
- throw Object.assign(new Error(err.message || "Network request failed"), {
- code: "NETWORK_ERROR",
- networkCode: classified.code,
- messageKey: classified.messageKey,
- });
- }
- throw err;
- }
- if (!response.ok) {
- throw await readPolicyResponseError(response, `Token request failed: ${response.status}`);
- }
- return response.json();
- };
+ const postServerToken = createServerTokenPoster({
+ getApiUrl,
+ getAuthHeader: () => getAuthHeader(event),
+ proxyFetch,
+ withPolicyHeaders,
+ classifyAndLog,
+ });
return fetchRealtimeTokenForProvider(
options.provider,
diff --git a/src/helpers/realtimeTokenProviders.js b/src/helpers/realtimeTokenProviders.js
index 1bac8a58c..a157c463b 100644
--- a/src/helpers/realtimeTokenProviders.js
+++ b/src/helpers/realtimeTokenProviders.js
@@ -5,6 +5,8 @@
// dictationStreamingRouting.js respectively. Dependencies are injected so the
// table is unit-testable without Electron.
+const { readPolicyResponseError } = require("./policyResponseError");
+
const dual = (streams, factory) =>
streams === 2 ? Promise.all([factory(), factory()]) : factory();
const duplicate = (streams, value) => (streams === 2 ? [value, value] : value);
@@ -120,7 +122,64 @@ async function fetchRealtimeTokenForProvider(provider, deps, options, { streams
return acquire(deps, options, streams);
}
+// Managed tokens are minted by the OpenWhispr API. The API answers a stale session
+// with a code-less 401 ("Invalid session"), so refusals are tagged with the codes
+// the renderer offers sign-in for: AUTH_REQUIRED (no credential) and AUTH_EXPIRED.
+function createServerTokenPoster({
+ getApiUrl,
+ getAuthHeader,
+ proxyFetch,
+ withPolicyHeaders,
+ classifyAndLog,
+}) {
+ return async (path, body = {}) => {
+ const apiUrl = getApiUrl();
+ if (!apiUrl) {
+ const err = new Error("OpenWhispr API URL not configured");
+ err.code = "NO_API";
+ throw err;
+ }
+ const authHeader = await getAuthHeader();
+ if (!Object.keys(authHeader).length) {
+ throw Object.assign(new Error("Not authenticated"), { code: "AUTH_REQUIRED" });
+ }
+ const url = `${apiUrl}${path}`;
+ let response;
+ try {
+ response = await proxyFetch(url, {
+ method: "POST",
+ headers: withPolicyHeaders({ "Content-Type": "application/json", ...authHeader }),
+ body: JSON.stringify(body),
+ });
+ } catch (err) {
+ const classified = classifyAndLog(err, url);
+ if (classified.isNetworkError) {
+ throw Object.assign(new Error(err.message || "Network request failed"), {
+ code: "NETWORK_ERROR",
+ networkCode: classified.code,
+ messageKey: classified.messageKey,
+ });
+ }
+ throw err;
+ }
+ if (!response.ok) {
+ const error = await readPolicyResponseError(
+ response,
+ `Token request failed: ${response.status}`
+ );
+ if (response.status === 401 && !error.code) error.code = "AUTH_EXPIRED";
+ throw error;
+ }
+ return response.json();
+ };
+}
+
+const isSignInRefusal = (error) =>
+ error?.code === "AUTH_EXPIRED" || error?.code === "AUTH_REQUIRED";
+
module.exports = {
REALTIME_TOKEN_PROVIDERS,
+ createServerTokenPoster,
fetchRealtimeTokenForProvider,
+ isSignInRefusal,
};
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index e7574d1d7..8e0517776 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -2268,6 +2268,8 @@
"unsupportedSelfHosted": "لا يمكن لتسجيل الملاحظات استخدام نقطة نهاية مستضافة ذاتيًا بعد. افتح الإعدادات واختر «محلي» أو مزودًا يدعم البث.",
"unsupportedProvider": "لا يمكن لتسجيل الملاحظات استخدام {{provider}} للتفريغ المباشر. افتح الإعدادات واختر «محلي» أو مزودًا يدعم البث.",
"noProviderSelected": "لم يتم اختيار أي مزود لتسجيل الملاحظات. افتح الإعدادات واختر «محلي» أو مزودًا يدعم البث.",
+ "signInRequired": "يتطلب تسجيل الملاحظات تسجيل الدخول. يرجى تسجيل الدخول.",
+ "signInExpired": "انتهت صلاحية تسجيل الدخول، لذا لا يمكن لتسجيل الملاحظات تجديد اتصاله وقد يتوقف. سجّل الدخول مجددًا بعد انتهاء هذا التسجيل.",
"systemAudioInterrupted": {
"title": "انقطع صوت الاجتماع",
"description": "توقف التقاط صوت النظام وتجري إعادة تشغيله. قد تفقد بضع ثوانٍ من المكالمة في النص المفرَّغ."
@@ -3985,7 +3987,8 @@
}
}
},
- "meetingEnterpriseOnly": "لا تسمح مؤسستك إلا بالتفريغ عبر السحابة المؤسسية، وهو لا يشمل تسجيل الاجتماعات بعد."
+ "meetingEnterpriseOnly": "لا تسمح مؤسستك إلا بالتفريغ عبر السحابة المؤسسية، وهو لا يشمل تسجيل الاجتماعات بعد.",
+ "meetingCloudSignedOut": "لا يمكن بدء تسجيل الملاحظات عبر OpenWhispr Cloud وأنت غير مسجل الدخول. اختر محركًا آخر أعلاه."
},
"intelligence": {
"gpuDevice": {
@@ -4210,7 +4213,8 @@
"recommended": "موصى به",
"active": "نشط",
"managedByOrg": "مُدار بواسطة مؤسستك",
- "freeAccountRequired": "حساب مجاني مطلوب",
+ "signInRequired": "تسجيل الدخول مطلوب",
+ "signIn": "تسجيل الدخول",
"comingSoon": "قريبًا",
"cloud": "سحابي",
"local": "محلي",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 30210b283..59828b6c6 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -179,7 +179,8 @@
"recommended": "Empfohlen",
"active": "Aktiv",
"managedByOrg": "Von Ihrer Organisation verwaltet",
- "freeAccountRequired": "Kostenloses Konto erforderlich",
+ "signInRequired": "Anmeldung erforderlich",
+ "signIn": "Anmelden",
"comingSoon": "Demnächst verfügbar",
"cloud": "Cloud",
"local": "Lokal",
@@ -2629,7 +2630,8 @@
}
}
},
- "meetingEnterpriseOnly": "Ihre Organisation erlaubt nur Unternehmens-Cloud-Transkription, die Besprechungsaufnahmen noch nicht abdeckt."
+ "meetingEnterpriseOnly": "Ihre Organisation erlaubt nur Unternehmens-Cloud-Transkription, die Besprechungsaufnahmen noch nicht abdeckt.",
+ "meetingCloudSignedOut": "Notizaufnahmen mit OpenWhispr Cloud können nicht starten, solange Sie abgemeldet sind. Wählen Sie oben eine andere Engine."
},
"intelligence": {
"gpuDevice": {
@@ -3492,6 +3494,8 @@
"unsupportedSelfHosted": "Die Notizaufnahme kann noch keinen selbst gehosteten Endpunkt verwenden. Öffne die Einstellungen und wähle Lokal oder einen Streaming-Anbieter.",
"unsupportedProvider": "Die Notizaufnahme kann {{provider}} nicht für die Live-Transkription verwenden. Öffne die Einstellungen und wähle Lokal oder einen Streaming-Anbieter.",
"noProviderSelected": "Für die Notizaufnahme ist kein Anbieter ausgewählt. Öffne die Einstellungen und wähle Lokal oder einen Streaming-Anbieter.",
+ "signInRequired": "Für die Notizaufnahme musst du angemeldet sein. Bitte melde dich an.",
+ "signInExpired": "Deine Anmeldung ist abgelaufen, daher kann die Notizaufnahme ihre Verbindung nicht erneuern und stoppt möglicherweise. Melde dich nach dem Ende dieser Aufnahme erneut an.",
"systemAudioSilent": {
"title": "Noch kein Meeting-Ton erkannt",
"description": "Bisher hat nur Ihr Mikrofon Ton aufgenommen. Sie sind in einem Videoanruf? Prüfen Sie, ob der Meeting-Ton auf diesem Computer wiedergegeben wird und nicht stummgeschaltet ist. Sie nehmen vor Ort auf? Dann können Sie diesen Hinweis ignorieren – Ihr Mikrofon nimmt den Raum auf."
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 44483ce61..10b2a8f19 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -179,7 +179,8 @@
"recommended": "Recommended",
"active": "Active",
"managedByOrg": "Managed by your organization",
- "freeAccountRequired": "Free account required",
+ "signInRequired": "Sign in Required",
+ "signIn": "Sign in",
"comingSoon": "Coming Soon",
"cloud": "Cloud",
"local": "Local",
@@ -2629,7 +2630,8 @@
}
}
},
- "meetingEnterpriseOnly": "Your organization only allows enterprise cloud transcription, which does not cover meeting recording yet."
+ "meetingEnterpriseOnly": "Your organization only allows enterprise cloud transcription, which does not cover meeting recording yet.",
+ "meetingCloudSignedOut": "Note recordings can't start on OpenWhispr Cloud while you're signed out. Choose another engine above."
},
"intelligence": {
"gpuDevice": {
@@ -3492,6 +3494,8 @@
"unsupportedSelfHosted": "Note Recording can't use a self-hosted endpoint yet. Open Settings and choose Local or a streaming provider.",
"unsupportedProvider": "Note Recording can't use {{provider}} for live transcription. Open Settings and choose Local or a streaming provider.",
"noProviderSelected": "No provider is selected for Note Recording. Open Settings and choose Local or a streaming provider.",
+ "signInRequired": "Note Recording requires you to be signed in. Please sign in.",
+ "signInExpired": "Your sign-in has expired, so Note Recording can't renew its connection and may stop. Sign in again once this recording ends.",
"systemAudioSilent": {
"title": "No meeting audio detected yet",
"description": "Only your microphone has picked up sound so far. On a video call? Check that the meeting audio is playing on this computer and isn't muted. Recording in person? You can ignore this — your microphone captures the room."
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 300363df2..7f646aa34 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -179,7 +179,8 @@
"recommended": "Recomendado",
"active": "Activo",
"managedByOrg": "Gestionado por tu organización",
- "freeAccountRequired": "Cuenta gratuita requerida",
+ "signInRequired": "Inicio de sesión requerido",
+ "signIn": "Iniciar sesión",
"comingSoon": "Próximamente",
"cloud": "Nube",
"local": "Local",
@@ -2387,7 +2388,8 @@
}
}
},
- "meetingEnterpriseOnly": "Tu organización solo permite la transcripción en nube empresarial, que aún no cubre la grabación de reuniones."
+ "meetingEnterpriseOnly": "Tu organización solo permite la transcripción en nube empresarial, que aún no cubre la grabación de reuniones.",
+ "meetingCloudSignedOut": "Las grabaciones de notas no pueden iniciarse con OpenWhispr Cloud sin haber iniciado sesión. Elige otro motor arriba."
},
"intelligence": {
"gpuDevice": {
@@ -3193,6 +3195,8 @@
"unsupportedSelfHosted": "La grabación de notas aún no puede usar un servidor propio. Abre Ajustes y elige Local o un proveedor de streaming.",
"unsupportedProvider": "La grabación de notas no puede usar {{provider}} para transcripción en vivo. Abre Ajustes y elige Local o un proveedor de streaming.",
"noProviderSelected": "No hay ningún proveedor seleccionado para la grabación de notas. Abre Ajustes y elige Local o un proveedor de streaming.",
+ "signInRequired": "La grabación de notas requiere iniciar sesión. Por favor, inicia sesión.",
+ "signInExpired": "Tu sesión ha caducado, así que la grabación de notas no puede renovar su conexión y podría detenerse. Vuelve a iniciar sesión cuando termine esta grabación.",
"systemAudioSilent": {
"title": "Aún no se detecta el audio de la reunión",
"description": "Hasta ahora solo tu micrófono ha captado sonido. ¿Estás en una videollamada? Comprueba que el audio de la reunión se reproduce en este equipo y no está silenciado. ¿Estás grabando en persona? Puedes ignorar este aviso: tu micrófono capta la sala."
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index d6ae24630..03ca06299 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -179,7 +179,8 @@
"recommended": "Recommandé",
"active": "Actif",
"managedByOrg": "Géré par votre organisation",
- "freeAccountRequired": "Compte gratuit requis",
+ "signInRequired": "Connexion requise",
+ "signIn": "Se connecter",
"comingSoon": "Bientôt disponible",
"cloud": "Cloud",
"local": "Local",
@@ -2629,7 +2630,8 @@
}
}
},
- "meetingEnterpriseOnly": "Votre organisation n'autorise que la transcription cloud d'entreprise, qui ne couvre pas encore l'enregistrement des réunions."
+ "meetingEnterpriseOnly": "Votre organisation n'autorise que la transcription cloud d'entreprise, qui ne couvre pas encore l'enregistrement des réunions.",
+ "meetingCloudSignedOut": "Les enregistrements de notes ne peuvent pas démarrer avec OpenWhispr Cloud tant que vous êtes déconnecté. Choisissez un autre moteur ci-dessus."
},
"intelligence": {
"gpuDevice": {
@@ -3492,6 +3494,8 @@
"unsupportedSelfHosted": "L'enregistrement de notes ne peut pas encore utiliser un serveur auto-hébergé. Ouvrez les Réglages et choisissez Local ou un fournisseur en streaming.",
"unsupportedProvider": "L'enregistrement de notes ne peut pas utiliser {{provider}} pour la transcription en direct. Ouvrez les Réglages et choisissez Local ou un fournisseur en streaming.",
"noProviderSelected": "Aucun fournisseur n'est sélectionné pour l'enregistrement de notes. Ouvrez les Réglages et choisissez Local ou un fournisseur en streaming.",
+ "signInRequired": "L'enregistrement de notes nécessite d'être connecté. Veuillez vous connecter.",
+ "signInExpired": "Votre session a expiré : l'enregistrement de notes ne peut pas renouveler sa connexion et risque de s'arrêter. Reconnectez-vous une fois cet enregistrement terminé.",
"systemAudioSilent": {
"title": "Aucun son de réunion détecté pour le moment",
"description": "Seul votre microphone a capté du son jusqu'à présent. Vous êtes en visioconférence ? Vérifiez que le son de la réunion est diffusé sur cet ordinateur et qu'il n'est pas coupé. Vous enregistrez en présentiel ? Vous pouvez ignorer ce message : votre microphone capte la salle."
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index b98ac9bb4..7f0908043 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -179,7 +179,8 @@
"recommended": "Consigliato",
"active": "Attivo",
"managedByOrg": "Gestito dalla tua organizzazione",
- "freeAccountRequired": "Account gratuito richiesto",
+ "signInRequired": "Accesso richiesto",
+ "signIn": "Accedi",
"comingSoon": "Prossimamente",
"cloud": "Cloud",
"local": "Locale",
@@ -2334,7 +2335,8 @@
}
}
},
- "meetingEnterpriseOnly": "La tua organizzazione consente solo la trascrizione su cloud aziendale, che non copre ancora la registrazione delle riunioni."
+ "meetingEnterpriseOnly": "La tua organizzazione consente solo la trascrizione su cloud aziendale, che non copre ancora la registrazione delle riunioni.",
+ "meetingCloudSignedOut": "Le registrazioni delle note non possono avviarsi con OpenWhispr Cloud finché non hai effettuato l'accesso. Scegli un altro motore qui sopra."
},
"intelligence": {
"gpuDevice": {
@@ -3140,6 +3142,8 @@
"unsupportedSelfHosted": "La registrazione delle note non può ancora usare un endpoint self-hosted. Apri le Impostazioni e scegli Locale o un provider in streaming.",
"unsupportedProvider": "La registrazione delle note non può usare {{provider}} per la trascrizione dal vivo. Apri le Impostazioni e scegli Locale o un provider in streaming.",
"noProviderSelected": "Nessun provider selezionato per la registrazione delle note. Apri le Impostazioni e scegli Locale o un provider in streaming.",
+ "signInRequired": "La registrazione delle note richiede l'accesso. Accedi, per favore.",
+ "signInExpired": "La sessione è scaduta, quindi la registrazione delle note non può rinnovare la connessione e potrebbe interrompersi. Accedi di nuovo al termine di questa registrazione.",
"systemAudioSilent": {
"title": "Nessun audio della riunione rilevato finora",
"description": "Finora solo il tuo microfono ha captato suoni. Sei in una videochiamata? Verifica che l'audio della riunione venga riprodotto su questo computer e non sia disattivato. Stai registrando di persona? Puoi ignorare questo avviso: il tuo microfono cattura la stanza."
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 5e1e586ca..64c294241 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -179,7 +179,8 @@
"recommended": "推奨",
"active": "有効",
"managedByOrg": "組織によって管理されています",
- "freeAccountRequired": "無料アカウントが必要です",
+ "signInRequired": "サインインが必要です",
+ "signIn": "サインイン",
"comingSoon": "近日公開",
"cloud": "クラウド",
"local": "ローカル",
@@ -2334,7 +2335,8 @@
}
}
},
- "meetingEnterpriseOnly": "組織はエンタープライズクラウドの文字起こしのみを許可しており、会議の録音にはまだ対応していません。"
+ "meetingEnterpriseOnly": "組織はエンタープライズクラウドの文字起こしのみを許可しており、会議の録音にはまだ対応していません。",
+ "meetingCloudSignedOut": "サインアウト中は OpenWhispr Cloud でノート録音を開始できません。上で別のエンジンを選択してください。"
},
"intelligence": {
"gpuDevice": {
@@ -3207,6 +3209,8 @@
"unsupportedSelfHosted": "ノート録音はまだセルフホストのエンドポイントを利用できません。設定を開き、ローカルまたはストリーミング対応プロバイダーを選択してください。",
"unsupportedProvider": "ノート録音ではライブ文字起こしに {{provider}} を利用できません。設定を開き、ローカルまたはストリーミング対応プロバイダーを選択してください。",
"noProviderSelected": "ノート録音のプロバイダーが選択されていません。設定を開き、ローカルまたはストリーミング対応プロバイダーを選択してください。",
+ "signInRequired": "ノート録音にはサインインが必要です。サインインしてください。",
+ "signInExpired": "サインインの有効期限が切れたため、ノート録音の接続を更新できず、録音が停止する可能性があります。この録音が終わったら、もう一度サインインしてください。",
"systemAudioSilent": {
"title": "会議の音声がまだ検出されていません",
"description": "これまでのところ、音声を拾っているのはマイクのみです。ビデオ会議中の場合は、会議の音声がこのコンピューターで再生されており、ミュートになっていないことを確認してください。対面で録音している場合は、この通知は無視してかまいません。マイクが室内の音を拾います。"
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 89321d2d9..aed0bc910 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -158,7 +158,8 @@
"recommended": "Recomendado",
"active": "Ativo",
"managedByOrg": "Gerenciado pela sua organização",
- "freeAccountRequired": "Conta gratuita necessária",
+ "signInRequired": "Login necessário",
+ "signIn": "Entrar",
"comingSoon": "Em breve",
"cloud": "Nuvem",
"local": "Local",
@@ -2313,7 +2314,8 @@
}
}
},
- "meetingEnterpriseOnly": "A sua organização só permite transcrição em nuvem corporativa, que ainda não abrange a gravação de reuniões."
+ "meetingEnterpriseOnly": "A sua organização só permite transcrição em nuvem corporativa, que ainda não abrange a gravação de reuniões.",
+ "meetingCloudSignedOut": "As gravações de notas não podem começar no OpenWhispr Cloud enquanto você estiver desconectado. Escolha outro motor acima."
},
"intelligence": {
"gpuDevice": {
@@ -3140,6 +3142,8 @@
"unsupportedSelfHosted": "A gravação de notas ainda não pode usar um endpoint auto-hospedado. Abra as Configurações e escolha Local ou um provedor de streaming.",
"unsupportedProvider": "A gravação de notas não pode usar {{provider}} para transcrição ao vivo. Abra as Configurações e escolha Local ou um provedor de streaming.",
"noProviderSelected": "Nenhum provedor está selecionado para a gravação de notas. Abra as Configurações e escolha Local ou um provedor de streaming.",
+ "signInRequired": "A gravação de notas exige que você entre na sua conta. Entre para continuar.",
+ "signInExpired": "Sua sessão expirou, então a gravação de notas não consegue renovar a conexão e pode parar. Entre novamente quando esta gravação terminar.",
"systemAudioSilent": {
"title": "Nenhum áudio da reunião detectado até agora",
"description": "Até agora, apenas o seu microfone captou som. Está em uma videochamada? Verifique se o áudio da reunião está sendo reproduzido neste computador e não está silenciado. Está gravando presencialmente? Você pode ignorar este aviso: seu microfone capta o ambiente."
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index e6bbdf148..ca29c30e0 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -179,7 +179,8 @@
"recommended": "Рекомендуется",
"active": "Активно",
"managedByOrg": "Управляется вашей организацией",
- "freeAccountRequired": "Требуется бесплатный аккаунт",
+ "signInRequired": "Требуется вход",
+ "signIn": "Войти",
"comingSoon": "Скоро",
"cloud": "Облако",
"local": "Локально",
@@ -2340,7 +2341,8 @@
}
}
},
- "meetingEnterpriseOnly": "Ваша организация разрешает только корпоративную облачную транскрипцию, которая пока не поддерживает запись встреч."
+ "meetingEnterpriseOnly": "Ваша организация разрешает только корпоративную облачную транскрипцию, которая пока не поддерживает запись встреч.",
+ "meetingCloudSignedOut": "Пока вы не вошли в аккаунт, запись заметок через OpenWhispr Cloud не запустится. Выберите другой движок выше."
},
"intelligence": {
"gpuDevice": {
@@ -3160,6 +3162,8 @@
"unsupportedSelfHosted": "Запись заметок пока не может использовать собственный сервер. Откройте настройки и выберите локальный режим или потоковый провайдер.",
"unsupportedProvider": "Запись заметок не может использовать {{provider}} для live-расшифровки. Откройте настройки и выберите локальный режим или потоковый провайдер.",
"noProviderSelected": "Для записи заметок не выбран провайдер. Откройте настройки и выберите локальный режим или потоковый провайдер.",
+ "signInRequired": "Для записи заметок нужно войти в аккаунт. Пожалуйста, войдите.",
+ "signInExpired": "Срок действия входа истёк, поэтому запись заметок не может обновить подключение и может остановиться. Войдите снова, когда эта запись закончится.",
"systemAudioSilent": {
"title": "Звук встречи пока не обнаружен",
"description": "Пока звук поступает только с вашего микрофона. Вы на видеозвонке? Убедитесь, что звук встречи воспроизводится на этом компьютере и не отключён. Записываете встречу вживую? Это предупреждение можно игнорировать — ваш микрофон улавливает звук в помещении."
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index cd74d7741..39e29c9ac 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -179,7 +179,8 @@
"recommended": "推荐",
"active": "已激活",
"managedByOrg": "由您的组织管理",
- "freeAccountRequired": "需要免费账户",
+ "signInRequired": "需要登录",
+ "signIn": "登录",
"comingSoon": "即将推出",
"cloud": "云端",
"local": "本地",
@@ -2334,7 +2335,8 @@
}
}
},
- "meetingEnterpriseOnly": "贵组织仅允许企业云转录,暂不支持会议录音。"
+ "meetingEnterpriseOnly": "贵组织仅允许企业云转录,暂不支持会议录音。",
+ "meetingCloudSignedOut": "未登录时,无法使用 OpenWhispr Cloud 开始笔记录音。请在上方选择其他引擎。"
},
"intelligence": {
"gpuDevice": {
@@ -3140,6 +3142,8 @@
"unsupportedSelfHosted": "笔记录音暂不支持自托管端点。请打开设置,选择本地或支持流式传输的服务商。",
"unsupportedProvider": "笔记录音无法使用 {{provider}} 进行实时转录。请打开设置,选择本地或支持流式传输的服务商。",
"noProviderSelected": "尚未为笔记录音选择服务商。请打开设置,选择本地或支持流式传输的服务商。",
+ "signInRequired": "笔记录音需要登录,请先登录。",
+ "signInExpired": "登录已过期,笔记录音无法更新连接,可能会中断。请在本次录音结束后重新登录。",
"systemAudioSilent": {
"title": "尚未检测到会议音频",
"description": "到目前为止,只有您的麦克风采集到声音。正在进行视频通话?请检查会议音频是否正在此电脑上播放且未被静音。正在进行现场录音?您可以忽略此提示——您的麦克风会采集房间内的声音。"
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 300120a9e..00d5b2ab3 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -179,7 +179,8 @@
"recommended": "推薦",
"active": "使用中",
"managedByOrg": "由您的組織管理",
- "freeAccountRequired": "需要免費帳戶",
+ "signInRequired": "需要登入",
+ "signIn": "登入",
"comingSoon": "即將推出",
"cloud": "雲端",
"local": "本機",
@@ -2334,7 +2335,8 @@
}
}
},
- "meetingEnterpriseOnly": "貴組織僅允許企業雲端轉錄,尚不支援會議錄音。"
+ "meetingEnterpriseOnly": "貴組織僅允許企業雲端轉錄,尚不支援會議錄音。",
+ "meetingCloudSignedOut": "未登入時,無法使用 OpenWhispr Cloud 開始筆記錄音。請在上方選擇其他引擎。"
},
"intelligence": {
"gpuDevice": {
@@ -3140,6 +3142,8 @@
"unsupportedSelfHosted": "筆記錄音尚不支援自架端點。請開啟設定,選擇本機或支援串流的服務商。",
"unsupportedProvider": "筆記錄音無法使用 {{provider}} 進行即時轉錄。請開啟設定,選擇本機或支援串流的服務商。",
"noProviderSelected": "尚未為筆記錄音選擇服務商。請開啟設定,選擇本機或支援串流的服務商。",
+ "signInRequired": "筆記錄音需要登入,請先登入。",
+ "signInExpired": "登入已過期,筆記錄音無法更新連線,可能會中斷。請在本次錄音結束後重新登入。",
"systemAudioSilent": {
"title": "尚未偵測到會議音訊",
"description": "到目前為止,只有您的麥克風收到聲音。正在進行視訊通話?請檢查會議音訊是否正在此電腦上播放且未被靜音。正在進行現場錄音?您可以忽略此提示——您的麥克風會收錄房間內的聲音。"
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index 9997acd1a..df2e48da9 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -1010,13 +1010,17 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
if (!startResult?.success) {
logger.error(
"Meeting transcription IPC start failed",
- { error: startResult?.error },
+ { error: startResult?.error, code: startResult?.code },
"meeting"
);
- reportMeetingError(startResult?.error || "Failed to start meeting transcription", {
- isRecording: false,
- isTranscribing: false,
- });
+ const needsSignIn =
+ startResult?.code === "AUTH_EXPIRED" || startResult?.code === "AUTH_REQUIRED";
+ reportMeetingError(
+ needsSignIn
+ ? "signInRequired"
+ : startResult?.error || "Failed to start meeting transcription",
+ { isRecording: false, isTranscribing: false }
+ );
stopMediaStream(micResult);
stopMediaStream(systemCaptureResult.stream);
setupMicResult = null;
diff --git a/test/components/meetingSignInRequiredToast.test.js b/test/components/meetingSignInRequiredToast.test.js
new file mode 100644
index 000000000..7fdab23ec
--- /dev/null
+++ b/test/components/meetingSignInRequiredToast.test.js
@@ -0,0 +1,107 @@
+const { createRequire } = require("node:module");
+const requireRepo = createRequire(require("node:path").resolve(__dirname, "../../package.json"));
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = requireRepo("react");
+const { createRoot } = requireRepo("react-dom/client");
+const { createRendererServer, installBrowserGlobals, installHookDom, installMicCaptureGlobals } =
+ requireRepo("./test/lib/rendererTestHarness");
+
+// A Cloud note recording whose realtime-token request is refused used to toast
+// the server's bare "Invalid session" / "Not authenticated" (#2427).
+
+async function startWithResult(t, startResult) {
+ let root;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__signInToasts;
+ delete globalThis.__signInRequests;
+ });
+ const noop = () => () => {};
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ checkSystemAudioAccess: async () => ({
+ granted: true,
+ status: "granted",
+ mode: "native",
+ strategy: "native",
+ }),
+ meetingTranscriptionStart: async () => startResult,
+ onMeetingSystemAudioInterrupted: noop,
+ onMeetingSystemAudioResumed: noop,
+ onMeetingAutoEndRequested: noop,
+ },
+ },
+ });
+ installMicCaptureGlobals(t);
+ const container = installHookDom(t);
+ globalThis.__signInToasts = [];
+ globalThis.__signInRequests = 0;
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-meeting-sign-in-toast-",
+ mockModules: {
+ "/ui/useToast": `export const useToast = () => ({ toast: (props) => { globalThis.__signInToasts.push(props); return "1"; }, dismiss: () => {} });`,
+ "/utils/requestSignIn": `export const requestSignIn = () => { globalThis.__signInRequests += 1; };`,
+ },
+ });
+ const { default: Mount } = await vite.ssrLoadModule("/components/MeetingRecordingMount.tsx");
+ const store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Mount)));
+ await React.act(async () =>
+ store.startRecording({ noteId: null, noteTitle: null, folderId: null, autoEndEligible: false })
+ );
+ assert.equal(store.useMeetingRecordingStore.getState().isRecording, false);
+ assert.equal(globalThis.__signInToasts.length, 1);
+ return { toast: globalThis.__signInToasts[0], i18n, store };
+}
+
+for (const code of ["AUTH_EXPIRED", "AUTH_REQUIRED"]) {
+ test(`${code}: the start failure explains the sign-in and offers it`, async (t) => {
+ const { toast, i18n } = await startWithResult(t, {
+ success: false,
+ error: code === "AUTH_EXPIRED" ? "Invalid session" : "Not authenticated",
+ code,
+ });
+
+ assert.ok(i18n.exists("notes.meeting.signInRequired"));
+ assert.equal(toast.description, i18n.t("notes.meeting.signInRequired"));
+ assert.equal(toast.actions.length, 1);
+ assert.equal(toast.actions[0].label, i18n.t("common.signIn"));
+ toast.actions[0].onClick();
+ assert.equal(globalThis.__signInRequests, 1);
+ });
+}
+
+test("any other start failure keeps its message and offers no sign-in", async (t) => {
+ const { toast } = await startWithResult(t, {
+ success: false,
+ error: "Token request failed: 500",
+ status: 500,
+ });
+
+ assert.equal(toast.description, "Token request failed: 500");
+ assert.equal(toast.actions, undefined);
+});
+
+test("a session that expires mid-recording is explained without a Sign in action", async (t) => {
+ // Signing in reloads the Control Panel, which would take a running recording with it.
+ const { i18n, store } = await startWithResult(t, {
+ success: false,
+ error: "Token request failed: 500",
+ status: 500,
+ });
+ await React.act(async () =>
+ store.useMeetingRecordingStore.setState((state) => ({
+ error: "signInExpired",
+ errorNonce: state.errorNonce + 1,
+ }))
+ );
+
+ const toast = globalThis.__signInToasts[1];
+ assert.ok(i18n.exists("notes.meeting.signInExpired"));
+ assert.equal(toast.description, i18n.t("notes.meeting.signInExpired"));
+ assert.equal(toast.actions, undefined);
+});
diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.js
index 327e275bc..d7c44e023 100644
--- a/test/helpers/ipcPolicyHeaderCoverage.test.js
+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js
@@ -56,9 +56,11 @@ test("chunk pool recovery cannot abort inline multipart uploads", () => {
});
test("the shared realtime-token helper applies policy headers", () => {
+ // realtimeTokenProviders.test.js pins that createServerTokenPoster sends its
+ // request through withPolicyHeaders; this pins that main hands it the real one.
assert.match(
source,
- /const postServerToken[\s\S]{0,900}?headers:\s*withPolicyHeaders\(/,
+ /createServerTokenPoster\(\{[\s\S]{0,300}?\bwithPolicyHeaders,/,
"the shared realtime-token helper must apply policy headers"
);
});
diff --git a/test/helpers/meetingStreamingWiring.test.js b/test/helpers/meetingStreamingWiring.test.js
index 443c09908..afa0fea2e 100644
--- a/test/helpers/meetingStreamingWiring.test.js
+++ b/test/helpers/meetingStreamingWiring.test.js
@@ -101,7 +101,10 @@ test("the system-audio watchdog is armed beside the silence timer and torn down
// that reported stalls it could not recover from.
const armStart = source.indexOf("const startMeetingSystemAudioWatchdog");
assert.ok(armStart >= 0);
- const armSection = source.slice(armStart, source.indexOf("const rollbackMeetingTranscriptionStart"));
+ const armSection = source.slice(
+ armStart,
+ source.indexOf("const rollbackMeetingTranscriptionStart")
+ );
assert.match(armSection, /clearMeetingSystemAudioTicker\(\);/);
assert.doesNotMatch(armSection, /stopMeetingSystemAudioWatchdog\(\);/);
assert.doesNotMatch(armSection, /detachCapture\(\)/);
@@ -109,11 +112,7 @@ test("the system-audio watchdog is armed beside the silence timer and torn down
// Every path that clears the one-shot timer also stops the watchdog, plus the
// mic-only fallback, which strands the restart hook on a dead manager.
for (const [label, from, to] of [
- [
- "rollback",
- "const rollbackMeetingTranscriptionStart",
- "const setupDictationCallbacks",
- ],
+ ["rollback", "const rollbackMeetingTranscriptionStart", "const setupDictationCallbacks"],
["stop", "const stopMeetingTranscription", "const meetingTranscriptionLifecycle"],
["mic-only fallback", "const fallBackToMicOnly", "const startMeetingSystemAudio = async"],
]) {
@@ -164,3 +163,16 @@ test("meeting connects forward the credential mode", () => {
assert.match(block, /^\s*mode: options\.mode,$/m);
}
});
+
+test("a mid-meeting renewal refused for the session reports the sign-in sentinel", () => {
+ // The 55-minute renewal and reconnects mint new tokens; a stale session used to
+ // reach the toast as the API's bare "Invalid session" (#2427).
+ const reconnectCatch = source.slice(
+ source.indexOf('debugLogger.error("Meeting stream reconnect failed"'),
+ source.indexOf("return canRestoreOld;")
+ );
+ assert.match(
+ reconnectCatch,
+ /"meeting-transcription-error",\s*isSignInRefusal\(error\) \? "signInExpired" : error\.message/
+ );
+});
diff --git a/test/helpers/realtimeTokenProviders.test.js b/test/helpers/realtimeTokenProviders.test.js
index 55ece63ae..3489c194f 100644
--- a/test/helpers/realtimeTokenProviders.test.js
+++ b/test/helpers/realtimeTokenProviders.test.js
@@ -248,3 +248,126 @@ test('wire bodies: dictation posts the bare {"streams":1}; meetings post model+l
{ path: "/api/gemini-live-token", json: "{}" },
]);
});
+
+// A Cloud note recording whose token request is refused used to toast the API's
+// bare "Invalid session" / "Not authenticated"; these codes let it offer sign-in (#2427).
+const serverTokenPoster = async (overrides = {}) => {
+ const { createServerTokenPoster } = await load();
+ return createServerTokenPoster({
+ getApiUrl: () => "https://api.example",
+ getAuthHeader: async () => ({ Authorization: "Bearer stale" }),
+ proxyFetch: async () => jsonResponse(200, { clientSecret: "secret" }),
+ withPolicyHeaders: (headers) => headers,
+ classifyAndLog: () => ({ isNetworkError: false }),
+ ...overrides,
+ });
+};
+
+test("server tokens: a code-less 401 is AUTH_EXPIRED and keeps the server's message", async () => {
+ const post = await serverTokenPoster({
+ proxyFetch: async () => jsonResponse(401, { error: "Invalid session" }),
+ });
+ await assert.rejects(post("/api/openai-realtime-token"), {
+ message: "Invalid session",
+ code: "AUTH_EXPIRED",
+ status: 401,
+ });
+});
+
+test("server tokens: a missing credential is AUTH_REQUIRED and never reaches the API", async () => {
+ let fetched = false;
+ const post = await serverTokenPoster({
+ getAuthHeader: async () => ({}),
+ proxyFetch: async () => {
+ fetched = true;
+ return jsonResponse(200, {});
+ },
+ });
+ await assert.rejects(post("/api/openai-realtime-token"), {
+ message: "Not authenticated",
+ code: "AUTH_REQUIRED",
+ });
+ assert.equal(fetched, false);
+});
+
+test("server tokens: codes the API sends are kept, and other refusals stay untagged", async () => {
+ const refuse = async (status, body) =>
+ (await serverTokenPoster({ proxyFetch: async () => jsonResponse(status, body) }))(
+ "/api/openai-realtime-token"
+ );
+ await assert.rejects(refuse(401, { error: "Session expired", code: "SESSION_REVOKED" }), {
+ code: "SESSION_REVOKED",
+ });
+ await assert.rejects(refuse(403, { error: "Blocked", code: "POLICY_BLOCKED" }), {
+ code: "POLICY_BLOCKED",
+ });
+ await assert.rejects(refuse(500, null), (error) => {
+ assert.equal(error.message, "Token request failed: 500");
+ assert.equal(error.code, undefined);
+ return true;
+ });
+});
+
+test("server tokens: a network failure is NETWORK_ERROR, not a sign-in prompt", async () => {
+ const post = await serverTokenPoster({
+ proxyFetch: async () => {
+ throw Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" });
+ },
+ classifyAndLog: () => ({
+ isNetworkError: true,
+ code: "ENOTFOUND",
+ messageKey: "streaming.errors.cloudUnreachable.dnsBlocked",
+ }),
+ });
+ await assert.rejects(post("/api/openai-realtime-token"), {
+ code: "NETWORK_ERROR",
+ networkCode: "ENOTFOUND",
+ });
+});
+
+test("server tokens: a success posts the body with credential and policy headers", async () => {
+ const requests = [];
+ const post = await serverTokenPoster({
+ proxyFetch: async (url, init) => {
+ requests.push({ url, init });
+ return jsonResponse(200, { clientSecret: "secret" });
+ },
+ withPolicyHeaders: (headers) => ({ ...headers, "x-policy": "applied" }),
+ });
+ assert.deepEqual(await post("/api/openai-realtime-token", { streams: 1 }), {
+ clientSecret: "secret",
+ });
+ assert.equal(requests[0].url, "https://api.example/api/openai-realtime-token");
+ assert.equal(requests[0].init.headers.Authorization, "Bearer stale");
+ assert.equal(requests[0].init.headers["x-policy"], "applied");
+ assert.equal(requests[0].init.body, '{"streams":1}');
+});
+
+test("server tokens: only session refusals count as sign-in refusals", async () => {
+ const { isSignInRefusal } = await load();
+ const refusal = async (overrides) => {
+ try {
+ await (
+ await serverTokenPoster(overrides)
+ )("/api/openai-realtime-token");
+ } catch (error) {
+ return error;
+ }
+ assert.fail("expected the token request to be refused");
+ };
+ assert.equal(
+ isSignInRefusal(await refusal({ proxyFetch: async () => jsonResponse(401, {}) })),
+ true
+ );
+ assert.equal(isSignInRefusal(await refusal({ getAuthHeader: async () => ({}) })), true);
+ assert.equal(
+ isSignInRefusal(
+ await refusal({ proxyFetch: async () => jsonResponse(403, { code: "POLICY_BLOCKED" }) })
+ ),
+ false
+ );
+ assert.equal(
+ isSignInRefusal(await refusal({ proxyFetch: async () => jsonResponse(500, null) })),
+ false
+ );
+});