Skip to content

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

feat(audio): add linux portal system audio plumbing

Gabriel Stein0e284ab3a9a0
diff --git a/README.md b/README.md
index 9ca7e653b..4a841dec1 100644
--- a/README.md
+++ b/README.md
@@ -394,7 +394,7 @@ npm run build:linux # Linux
2. **Grant Permissions**:
- **Microphone Access**: Required for voice recording
- **Accessibility Permissions**: Required for automatic text pasting (macOS)
- - **Screen Recording** (optional, macOS): Required for meeting audio capture — prompted during onboarding if you want meeting features
+ - **Screen Recording / System Audio**: macOS prompts during onboarding for meeting capture. On Linux, system audio is shared through the desktop portal when recording starts
3. **Name Your Agent**: Give your AI assistant a personal name (e.g., "Assistant", "Jarvis", "Alex")
- Makes interactions feel more natural and conversational
@@ -494,6 +494,7 @@ Automatically detect and transcribe meetings with Google Calendar integration:
3. **Auto-Detection**: When a meeting starts (Zoom, Teams, FaceTime), a notification appears asking to record
4. **Live Transcription**: Meeting audio is transcribed in real-time via OpenAI Realtime API
5. **Review**: Meeting transcriptions are saved as notes for later review and AI enhancement
+6. **Linux system audio**: Uses the standard desktop portal chooser today, with runtime capability detection and fallback handling for future persistent portal support
### Processing Options
diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md
index 1d5ecdc2f..abb13af45 100644
--- a/TROUBLESHOOTING.md
+++ b/TROUBLESHOOTING.md
@@ -99,6 +99,16 @@
OpenWhispr tries clipboard methods in order: `wl-copy` (most reliable) → renderer `navigator.clipboard` → X11 fallback.
+### Linux System Audio Portal Issues
+
+**Symptoms:** The Linux share dialog keeps appearing, system audio does not stay granted, or onboarding does not show a system-audio grant step.
+
+**Fix:**
+1. Update `xdg-desktop-portal` and the matching desktop backend for your session (`xdg-desktop-portal-gnome`, `xdg-desktop-portal-kde`, `xdg-desktop-portal-wlr`, etc.)
+2. Sign out and back in after updating portal packages
+3. Re-run system audio capture and complete the chooser again
+4. Expect the chooser to appear on Linux while OpenWhispr is using the standard browser portal path; some desktops may support more persistent portal behavior later, but fallback capture should still work
+
### Meeting Transcription Issues
**Symptoms:** Meeting detection not working, no transcription, audio not captured
diff --git a/electron-builder.json b/electron-builder.json
index 4502e751f..b50a9d952 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -94,6 +94,7 @@
"resources/bin/macos-text-monitor",
"resources/bin/macos-media-remote",
"resources/bin/linux-fast-paste",
+ "resources/bin/linux-system-audio-helper",
"resources/bin/linux-text-monitor",
{
"from": "resources/bin/",
diff --git a/main.js b/main.js
index 78506dcae..81d05c3dc 100644
--- a/main.js
+++ b/main.js
@@ -207,6 +207,7 @@ const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");
const MeetingProcessDetector = require("./src/helpers/meetingProcessDetector");
const AudioActivityDetector = require("./src/helpers/audioActivityDetector");
const AudioTapManager = require("./src/helpers/audioTapManager");
+const LinuxPortalAudioManager = require("./src/helpers/linuxPortalAudioManager");
const MeetingDetectionEngine = require("./src/helpers/meetingDetectionEngine");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
const { ensureYdotool } = require("./src/helpers/ensureYdotool");
@@ -229,6 +230,7 @@ let whisperCudaManager = null;
let googleCalendarManager = null;
let meetingDetectionEngine = null;
let audioTapManager = null;
+let linuxPortalAudioManager = null;
let qdrantManager = null;
let ipcHandlers = null;
let globeKeyAlertShown = false;
@@ -307,6 +309,7 @@ function initializeCoreManagers() {
windowsKeyManager = new WindowsKeyManager();
textEditMonitor = new TextEditMonitor();
audioTapManager = new AudioTapManager();
+ linuxPortalAudioManager = new LinuxPortalAudioManager();
windowManager.textEditMonitor = textEditMonitor;
// IPC handlers must be registered before window content loads
@@ -324,6 +327,7 @@ function initializeCoreManagers() {
googleCalendarManager,
meetingDetectionEngine,
audioTapManager,
+ linuxPortalAudioManager,
getTrayManager: () => trayManager,
});
}
@@ -1077,7 +1081,7 @@ if (gotSingleInstanceLock) {
return new Promise((resolve) => setTimeout(resolve, delay));
})
.then(() => {
- if (process.platform !== "darwin") {
+ if (process.platform === "win32") {
session.defaultSession.setDisplayMediaRequestHandler((_request, callback) => {
desktopCapturer.getSources({ types: ["screen"] }).then((sources) => {
callback({ video: sources[0], audio: "loopback" });
@@ -1176,6 +1180,9 @@ if (gotSingleInstanceLock) {
if (audioTapManager) {
audioTapManager.stop().catch(() => {});
}
+ if (linuxPortalAudioManager) {
+ linuxPortalAudioManager.stop().catch(() => {});
+ }
if (ipcHandlers) {
ipcHandlers._cleanupTextEditMonitor();
}
diff --git a/package.json b/package.json
index 76f9d5927..76616e87f 100644
--- a/package.json
+++ b/package.json
@@ -14,10 +14,11 @@
"compile:text-monitor": "node scripts/build-text-monitor.js",
"compile:winpaste": "node scripts/build-windows-fast-paste.js",
"compile:linux-paste": "node scripts/build-linux-fast-paste.js",
+ "compile:linux-system-audio": "node scripts/build-linux-system-audio.js",
"compile:media-remote": "node scripts/build-media-remote.js",
"compile:mic-listener": "node scripts/build-macos-mic-listener.js",
"compile:audio-tap": "node scripts/build-macos-audio-tap.js",
- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mic-listener && npm run compile:audio-tap",
+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mic-listener && npm run compile:audio-tap",
"prestart": "npm run compile:native && npm run download:qdrant && npm run download:embedding-model",
"start": "electron .",
"predev": "npm run compile:native && npm run download:qdrant && npm run download:embedding-model",
diff --git a/resources/linux-system-audio-helper.c b/resources/linux-system-audio-helper.c
new file mode 100644
index 000000000..54c82d381
--- /dev/null
+++ b/resources/linux-system-audio-helper.c
@@ -0,0 +1,626 @@
+#define _GNU_SOURCE
+
+#include <gio/gio.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define PORTAL_BUS "org.freedesktop.portal.Desktop"
+#define PORTAL_PATH "/org/freedesktop/portal/desktop"
+#define SCREENCAST_IFACE "org.freedesktop.portal.ScreenCast"
+#define PROPERTIES_IFACE "org.freedesktop.DBus.Properties"
+#define REQUEST_IFACE "org.freedesktop.portal.Request"
+
+#define SCREENCAST_SOURCE_MONITOR 1u
+#define SCREENCAST_PERSIST_PERMANENT 2u
+
+typedef enum {
+ MODE_PROBE = 0,
+ MODE_GRANT = 1,
+ MODE_START = 2,
+} HelperMode;
+
+typedef struct {
+ GDBusConnection *conn;
+ GMainLoop *loop;
+ HelperMode mode;
+ gchar *restore_token;
+ gchar *session_handle;
+ gchar *create_token;
+ gchar *select_token;
+ gchar *start_token;
+ gchar *create_request_path;
+ gchar *select_request_path;
+ gchar *start_request_path;
+ guint signal_id;
+ guint portal_version;
+ guint available_source_types;
+ gboolean supports_persist_mode;
+ gboolean supports_restore_token;
+ gboolean supports_system_audio;
+ gboolean probe_ok;
+ gboolean requested_restore_token;
+ gboolean result_printed;
+ int exit_code;
+} Helper;
+
+static void json_print_escaped(FILE *stream, const char *value)
+{
+ const unsigned char *ptr = (const unsigned char *)value;
+
+ fputc('"', stream);
+ for (; ptr && *ptr; ptr++) {
+ switch (*ptr) {
+ case '\\':
+ fputs("\\\\", stream);
+ break;
+ case '"':
+ fputs("\\\"", stream);
+ break;
+ case '\b':
+ fputs("\\b", stream);
+ break;
+ case '\f':
+ fputs("\\f", stream);
+ break;
+ case '\n':
+ fputs("\\n", stream);
+ break;
+ case '\r':
+ fputs("\\r", stream);
+ break;
+ case '\t':
+ fputs("\\t", stream);
+ break;
+ default:
+ if (*ptr < 0x20) {
+ fprintf(stream, "\\u%04x", *ptr);
+ } else {
+ fputc(*ptr, stream);
+ }
+ break;
+ }
+ }
+ fputc('"', stream);
+}
+
+static void json_print_nullable_string(FILE *stream, const char *value)
+{
+ if (!value) {
+ fputs("null", stream);
+ return;
+ }
+
+ json_print_escaped(stream, value);
+}
+
+static void print_probe_json(const Helper *app)
+{
+ fputs("{\"ok\":", stdout);
+ fputs(app->probe_ok ? "true" : "false", stdout);
+ fprintf(stdout, ",\"portalVersion\":%u", app->portal_version);
+ fputs(",\"supportsPersistMode\":", stdout);
+ fputs(app->supports_persist_mode ? "true" : "false", stdout);
+ fputs(",\"supportsRestoreToken\":", stdout);
+ fputs(app->supports_restore_token ? "true" : "false", stdout);
+ fputs(",\"supportsSystemAudio\":", stdout);
+ fputs(app->supports_system_audio ? "true" : "false", stdout);
+ fputs(",\"supportsNativeCapture\":false", stdout);
+
+ if (!app->probe_ok) {
+ const char *message = "portal_unavailable";
+ fputs(",\"error\":", stdout);
+ json_print_escaped(stdout, message);
+ }
+
+ fputs("}\n", stdout);
+ fflush(stdout);
+}
+
+static void print_grant_json(gboolean granted, const char *restore_token, guint portal_version,
+ const char *source, const char *error)
+{
+ fputs("{\"granted\":", stdout);
+ fputs(granted ? "true" : "false", stdout);
+ fputs(",\"restoreToken\":", stdout);
+ json_print_nullable_string(stdout, restore_token);
+ fprintf(stdout, ",\"portalVersion\":%u", portal_version);
+ fputs(",\"source\":", stdout);
+ json_print_escaped(stdout, source);
+
+ if (error) {
+ fputs(",\"error\":", stdout);
+ json_print_escaped(stdout, error);
+ }
+
+ fputs("}\n", stdout);
+ fflush(stdout);
+}
+
+static void emit_event(const char *type, const char *code, const char *message,
+ const char *restore_token)
+{
+ fputs("{\"type\":", stderr);
+ json_print_escaped(stderr, type);
+
+ if (code) {
+ fputs(",\"code\":", stderr);
+ json_print_escaped(stderr, code);
+ }
+
+ if (message) {
+ fputs(",\"message\":", stderr);
+ json_print_escaped(stderr, message);
+ }
+
+ if (restore_token || strcmp(type, "start") == 0) {
+ fputs(",\"restoreToken\":", stderr);
+ json_print_nullable_string(stderr, restore_token);
+ }
+
+ fputs("}\n", stderr);
+ fflush(stderr);
+}
+
+static gchar *make_token(const char *suffix)
+{
+ return g_strdup_printf("ow_%d_%s", (int)getpid(), suffix);
+}
+
+static gchar *get_sender_path(GDBusConnection *conn)
+{
+ const char *name = g_dbus_connection_get_unique_name(conn);
+ gchar *path = g_strdup(name + 1);
+
+ for (char *ptr = path; ptr && *ptr; ptr++) {
+ if (*ptr == '.') {
+ *ptr = '_';
+ }
+ }
+
+ return path;
+}
+
+static gchar *make_request_path(GDBusConnection *conn, const char *token)
+{
+ gchar *sender_path = get_sender_path(conn);
+ gchar *request_path = g_strdup_printf(
+ "/org/freedesktop/portal/desktop/request/%s/%s", sender_path, token);
+ g_free(sender_path);
+ return request_path;
+}
+
+static guint subscribe_response(Helper *app, const char *request_path, GDBusSignalCallback callback)
+{
+ return g_dbus_connection_signal_subscribe(
+ app->conn, PORTAL_BUS, REQUEST_IFACE, "Response",
+ request_path, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, callback, app, NULL);
+}
+
+static gboolean get_portal_uint_property(GDBusConnection *conn, const char *property_name,
+ guint *value_out)
+{
+ GError *error = NULL;
+ GVariant *result = g_dbus_connection_call_sync(
+ conn, PORTAL_BUS, PORTAL_PATH, PROPERTIES_IFACE, "Get",
+ g_variant_new("(ss)", SCREENCAST_IFACE, property_name), G_VARIANT_TYPE("(v)"),
+ G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+
+ if (!result) {
+ g_clear_error(&error);
+ return FALSE;
+ }
+
+ GVariant *value = NULL;
+ g_variant_get(result, "(@v)", &value);
+
+ if (!value || !g_variant_is_of_type(value, G_VARIANT_TYPE_UINT32)) {
+ if (value) {
+ g_variant_unref(value);
+ }
+ g_variant_unref(result);
+ return FALSE;
+ }
+
+ *value_out = g_variant_get_uint32(value);
+ g_variant_unref(value);
+ g_variant_unref(result);
+ return TRUE;
+}
+
+static gboolean load_portal_capabilities(Helper *app)
+{
+ GError *error = NULL;
+ app->conn = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
+ if (!app->conn) {
+ g_clear_error(&error);
+ return FALSE;
+ }
+
+ gboolean got_version = get_portal_uint_property(app->conn, "version", &app->portal_version);
+ gboolean got_sources = get_portal_uint_property(app->conn, "AvailableSourceTypes",
+ &app->available_source_types);
+
+ app->supports_persist_mode = app->portal_version >= 4;
+ app->supports_restore_token = app->portal_version >= 4;
+ app->supports_system_audio = (app->available_source_types & SCREENCAST_SOURCE_MONITOR) != 0;
+ app->probe_ok = got_version && got_sources;
+
+ return app->probe_ok;
+}
+
+static void finish_grant(Helper *app, gboolean granted, const char *restore_token,
+ const char *error)
+{
+ if (app->result_printed) {
+ return;
+ }
+
+ app->result_printed = TRUE;
+ print_grant_json(granted, restore_token, app->portal_version, "screen-cast", error);
+ if (app->loop) {
+ g_main_loop_quit(app->loop);
+ }
+}
+
+static void finish_start(Helper *app, int exit_code)
+{
+ app->exit_code = exit_code;
+ if (app->loop) {
+ g_main_loop_quit(app->loop);
+ }
+}
+
+static void on_start_response(GDBusConnection *conn, const char *sender, const char *object_path,
+ const char *interface_name, const char *signal_name,
+ GVariant *parameters, gpointer user_data);
+
+static void on_select_sources_response(GDBusConnection *conn, const char *sender,
+ const char *object_path, const char *interface_name,
+ const char *signal_name, GVariant *parameters,
+ gpointer user_data)
+{
+ Helper *app = user_data;
+ guint32 response = 0;
+ GVariant *results = NULL;
+
+ g_variant_get(parameters, "(u@a{sv})", &response, &results);
+ g_dbus_connection_signal_unsubscribe(app->conn, app->signal_id);
+
+ if (response != 0) {
+ g_variant_unref(results);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, "permission_denied");
+ } else {
+ emit_event("error", "permission_denied", "Portal denied system audio capture", NULL);
+ finish_start(app, 2);
+ }
+ return;
+ }
+
+ g_variant_unref(results);
+
+ app->signal_id = subscribe_response(app, app->start_request_path, on_start_response);
+
+ GVariantBuilder opts;
+ g_variant_builder_init(&opts, G_VARIANT_TYPE("a{sv}"));
+ g_variant_builder_add(&opts, "{sv}", "handle_token", g_variant_new_string(app->start_token));
+
+ GError *error = NULL;
+ g_dbus_connection_call_sync(
+ app->conn, PORTAL_BUS, PORTAL_PATH, SCREENCAST_IFACE, "Start",
+ g_variant_new("(os@a{sv})", app->session_handle, "", g_variant_builder_end(&opts)),
+ NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+
+ if (error) {
+ g_dbus_connection_signal_unsubscribe(app->conn, app->signal_id);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, error->message);
+ } else {
+ emit_event("error", "portal_error", error->message, NULL);
+ finish_start(app, 2);
+ }
+ g_error_free(error);
+ }
+}
+
+static void on_create_session_response(GDBusConnection *conn, const char *sender,
+ const char *object_path, const char *interface_name,
+ const char *signal_name, GVariant *parameters,
+ gpointer user_data)
+{
+ Helper *app = user_data;
+ guint32 response = 0;
+ GVariant *results = NULL;
+
+ g_variant_get(parameters, "(u@a{sv})", &response, &results);
+ g_dbus_connection_signal_unsubscribe(app->conn, app->signal_id);
+
+ if (response != 0) {
+ g_variant_unref(results);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, "permission_denied");
+ } else {
+ emit_event("error", "permission_denied", "Portal denied system audio capture", NULL);
+ finish_start(app, 2);
+ }
+ return;
+ }
+
+ GVariant *handle_value = g_variant_lookup_value(results, "session_handle", G_VARIANT_TYPE_STRING);
+ if (!handle_value) {
+ g_variant_unref(results);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, "portal_error");
+ } else {
+ emit_event("error", "portal_error", "Missing session handle in portal response", NULL);
+ finish_start(app, 2);
+ }
+ return;
+ }
+
+ g_free(app->session_handle);
+ app->session_handle = g_variant_dup_string(handle_value, NULL);
+ g_variant_unref(handle_value);
+ g_variant_unref(results);
+
+ app->select_request_path = make_request_path(app->conn, app->select_token);
+ app->signal_id = subscribe_response(app, app->select_request_path, on_select_sources_response);
+
+ GVariantBuilder opts;
+ g_variant_builder_init(&opts, G_VARIANT_TYPE("a{sv}"));
+ g_variant_builder_add(&opts, "{sv}", "handle_token", g_variant_new_string(app->select_token));
+ g_variant_builder_add(&opts, "{sv}", "types",
+ g_variant_new_uint32(SCREENCAST_SOURCE_MONITOR));
+
+ if (app->supports_persist_mode) {
+ g_variant_builder_add(&opts, "{sv}", "persist_mode",
+ g_variant_new_uint32(SCREENCAST_PERSIST_PERMANENT));
+ }
+
+ if (app->supports_restore_token && app->restore_token) {
+ g_variant_builder_add(&opts, "{sv}", "restore_token",
+ g_variant_new_string(app->restore_token));
+ }
+
+ GError *error = NULL;
+ g_dbus_connection_call_sync(
+ app->conn, PORTAL_BUS, PORTAL_PATH, SCREENCAST_IFACE, "SelectSources",
+ g_variant_new("(o@a{sv})", app->session_handle, g_variant_builder_end(&opts)),
+ NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+
+ if (error) {
+ g_dbus_connection_signal_unsubscribe(app->conn, app->signal_id);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, error->message);
+ } else {
+ emit_event("error", "portal_error", error->message, NULL);
+ finish_start(app, 2);
+ }
+ g_error_free(error);
+ }
+}
+
+static void on_start_response(GDBusConnection *conn, const char *sender, const char *object_path,
+ const char *interface_name, const char *signal_name,
+ GVariant *parameters, gpointer user_data)
+{
+ Helper *app = user_data;
+ guint32 response = 0;
+ GVariant *results = NULL;
+
+ g_variant_get(parameters, "(u@a{sv})", &response, &results);
+ g_dbus_connection_signal_unsubscribe(app->conn, app->signal_id);
+
+ if (response != 0) {
+ g_variant_unref(results);
+ if (app->mode == MODE_GRANT) {
+ finish_grant(app, FALSE, NULL, "permission_denied");
+ } else {
+ emit_event("error", "permission_denied", "Portal denied system audio capture", NULL);
+ finish_start(app, 2);
+ }
+ return;
+ }
+
+ const gchar *restore_token = NULL;
+ GVariant *restore_value = g_variant_lookup_value(results, "restore_token", G_VARIANT_TYPE_STRING);
+ if (restore_value) {
+ restore_token = g_variant_get_string(restore_value, NULL);
+ }
+
+ if (app->mode == MODE_GRANT) {
+ gchar *restore_copy = restore_token ? g_strdup(restore_token) : NULL;
+ if (restore_value) {
+ g_variant_unref(restore_value);
+ }
+ g_variant_unref(results);
+ finish_grant(app, TRUE, restore_copy, NULL);
+ g_free(restore_copy);
+ return;
+ }
+
+ emit_event("start", NULL, NULL, restore_token);
+
+ if (app->requested_restore_token && !restore_token) {
+ emit_event("warning", "restore_failed",
+ "Restore token was supplied but the portal did not return a replacement token",
+ NULL);
+ }
+
+ emit_event("warning", "capture_unimplemented",
+ "Native PipeWire PCM capture is not implemented in this helper yet", NULL);
+
+ if (restore_value) {
+ g_variant_unref(restore_value);
+ }
+ g_variant_unref(results);
+ finish_start(app, 2);
+}
+
+static gboolean run_probe(void)
+{
+ Helper app = {0};
+ app.mode = MODE_PROBE;
+ app.probe_ok = load_portal_capabilities(&app);
+ print_probe_json(&app);
+ g_clear_object(&app.conn);
+ return TRUE;
+}
+
+static gboolean run_grant(void)
+{
+ Helper app = {0};
+ app.mode = MODE_GRANT;
+ app.loop = g_main_loop_new(NULL, FALSE);
+
+ if (!load_portal_capabilities(&app) || !app.supports_system_audio) {
+ print_grant_json(FALSE, NULL, app.portal_version, "screen-cast",
+ app.probe_ok ? "unsupported" : "portal_unavailable");
+ g_clear_object(&app.conn);
+ g_main_loop_unref(app.loop);
+ return TRUE;
+ }
+
+ app.create_token = make_token("create");
+ app.select_token = make_token("select");
+ app.start_token = make_token("start");
+ app.create_request_path = make_request_path(app.conn, app.create_token);
+ app.select_request_path = make_request_path(app.conn, app.select_token);
+ app.start_request_path = make_request_path(app.conn, app.start_token);
+
+ app.signal_id = subscribe_response(&app, app.create_request_path, on_create_session_response);
+
+ GVariantBuilder opts;
+ g_variant_builder_init(&opts, G_VARIANT_TYPE("a{sv}"));
+ g_variant_builder_add(&opts, "{sv}", "handle_token", g_variant_new_string(app.create_token));
+ g_variant_builder_add(&opts, "{sv}", "session_handle_token",
+ g_variant_new_string(app.create_token));
+
+ GError *error = NULL;
+ g_dbus_connection_call_sync(
+ app.conn, PORTAL_BUS, PORTAL_PATH, SCREENCAST_IFACE, "CreateSession",
+ g_variant_new("(a{sv})", g_variant_builder_end(&opts)),
+ NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+
+ if (error) {
+ g_dbus_connection_signal_unsubscribe(app.conn, app.signal_id);
+ print_grant_json(FALSE, NULL, app.portal_version, "screen-cast", error->message);
+ g_error_free(error);
+ } else {
+ g_main_loop_run(app.loop);
+ }
+
+ g_clear_object(&app.conn);
+ g_main_loop_unref(app.loop);
+ g_free(app.restore_token);
+ g_free(app.session_handle);
+ g_free(app.create_token);
+ g_free(app.select_token);
+ g_free(app.start_token);
+ g_free(app.create_request_path);
+ g_free(app.select_request_path);
+ g_free(app.start_request_path);
+ return TRUE;
+}
+
+static gboolean run_start(const char *restore_token)
+{
+ Helper app = {0};
+ app.mode = MODE_START;
+ app.loop = g_main_loop_new(NULL, FALSE);
+ app.restore_token = restore_token ? g_strdup(restore_token) : NULL;
+ app.requested_restore_token = restore_token != NULL;
+
+ if (!load_portal_capabilities(&app) || !app.supports_system_audio) {
+ emit_event("error", "unsupported",
+ "Linux portal system audio capture is not available on this desktop", NULL);
+ g_clear_object(&app.conn);
+ g_main_loop_unref(app.loop);
+ g_free(app.restore_token);
+ return FALSE;
+ }
+
+ app.create_token = make_token("create");
+ app.select_token = make_token("select");
+ app.start_token = make_token("start");
+ app.create_request_path = make_request_path(app.conn, app.create_token);
+ app.select_request_path = make_request_path(app.conn, app.select_token);
+ app.start_request_path = make_request_path(app.conn, app.start_token);
+
+ app.signal_id = subscribe_response(&app, app.create_request_path, on_create_session_response);
+
+ GVariantBuilder opts;
+ g_variant_builder_init(&opts, G_VARIANT_TYPE("a{sv}"));
+ g_variant_builder_add(&opts, "{sv}", "handle_token", g_variant_new_string(app.create_token));
+ g_variant_builder_add(&opts, "{sv}", "session_handle_token",
+ g_variant_new_string(app.create_token));
+
+ GError *error = NULL;
+ g_dbus_connection_call_sync(
+ app.conn, PORTAL_BUS, PORTAL_PATH, SCREENCAST_IFACE, "CreateSession",
+ g_variant_new("(a{sv})", g_variant_builder_end(&opts)),
+ NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+
+ if (error) {
+ g_dbus_connection_signal_unsubscribe(app.conn, app.signal_id);
+ emit_event("error", "portal_error", error->message, NULL);
+ g_error_free(error);
+ app.exit_code = 2;
+ } else {
+ g_main_loop_run(app.loop);
+ }
+
+ g_clear_object(&app.conn);
+ g_main_loop_unref(app.loop);
+ g_free(app.restore_token);
+ g_free(app.session_handle);
+ g_free(app.create_token);
+ g_free(app.select_token);
+ g_free(app.start_token);
+ g_free(app.create_request_path);
+ g_free(app.select_request_path);
+ g_free(app.start_request_path);
+ return app.exit_code == 0;
+}
+
+static void print_usage(void)
+{
+ fprintf(stderr, "Usage: linux-system-audio-helper <probe|grant|start> [--restore-token TOKEN]\n");
+}
+
+int main(int argc, char *argv[])
+{
+ if (argc < 2) {
+ print_usage();
+ return 1;
+ }
+
+ if (strcmp(argv[1], "probe") == 0) {
+ run_probe();
+ return 0;
+ }
+
+ if (strcmp(argv[1], "grant") == 0) {
+ run_grant();
+ return 0;
+ }
+
+ if (strcmp(argv[1], "start") == 0) {
+ const char *restore_token = NULL;
+ for (int i = 2; i < argc; i++) {
+ if (strcmp(argv[i], "--restore-token") == 0 && i + 1 < argc) {
+ restore_token = argv[++i];
+ continue;
+ }
+ print_usage();
+ return 1;
+ }
+
+ return run_start(restore_token) ? 0 : 2;
+ }
+
+ print_usage();
+ return 1;
+}
diff --git a/scripts/build-linux-system-audio.js b/scripts/build-linux-system-audio.js
new file mode 100644
index 000000000..48635e758
--- /dev/null
+++ b/scripts/build-linux-system-audio.js
@@ -0,0 +1,157 @@
+#!/usr/bin/env node
+
+const { spawnSync } = require("child_process");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+
+if (process.platform !== "linux") {
+ process.exit(0);
+}
+
+const projectRoot = path.resolve(__dirname, "..");
+const cSource = path.join(projectRoot, "resources", "linux-system-audio-helper.c");
+const outputDir = path.join(projectRoot, "resources", "bin");
+const outputBinary = path.join(outputDir, "linux-system-audio-helper");
+const hashFile = path.join(outputDir, ".linux-system-audio-helper.hash");
+
+function log(message) {
+ console.log(`[linux-system-audio-helper] ${message}`);
+}
+
+function ensureDir(dirPath) {
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+}
+
+function getGioFlags() {
+ try {
+ const result = spawnSync("pkg-config", ["--cflags", "--libs", "gio-2.0"], {
+ stdio: "pipe",
+ env: process.env,
+ });
+ if (result.status !== 0) {
+ return null;
+ }
+
+ return result.stdout.toString().trim().split(/\s+/).filter(Boolean);
+ } catch {
+ return null;
+ }
+}
+
+function isBinaryUpToDate() {
+ if (!fs.existsSync(outputBinary)) {
+ return false;
+ }
+
+ if (!fs.existsSync(cSource)) {
+ return true;
+ }
+
+ try {
+ const binaryStat = fs.statSync(outputBinary);
+ const sourceStat = fs.statSync(cSource);
+ if (binaryStat.mtimeMs < sourceStat.mtimeMs) {
+ return false;
+ }
+ } catch {
+ return false;
+ }
+
+ try {
+ const flags = getGioFlags();
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const currentHash = crypto
+ .createHash("sha256")
+ .update(sourceContent + (flags ? flags.join(" ") : "no-gio"))
+ .digest("hex");
+
+ if (fs.existsSync(hashFile)) {
+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();
+ if (savedHash !== currentHash) {
+ log("Source or build flags changed, rebuild needed");
+ return false;
+ }
+ } else {
+ fs.writeFileSync(hashFile, currentHash);
+ }
+ } catch (error) {
+ log(`Hash check failed: ${error.message}, forcing rebuild`);
+ return false;
+ }
+
+ return true;
+}
+
+function attemptCompile(command, args) {
+ log(`Compiling with ${[command, ...args].join(" ")}`);
+ return spawnSync(command, args, {
+ stdio: "inherit",
+ env: process.env,
+ });
+}
+
+function tryCompile() {
+ if (!fs.existsSync(cSource)) {
+ console.error(`[linux-system-audio-helper] C source not found at ${cSource}`);
+ return false;
+ }
+
+ const gioFlags = getGioFlags();
+ if (!gioFlags) {
+ log("gio-2.0 not found, skipping native helper build");
+ return false;
+ }
+
+ log("gio-2.0 found, building native portal helper");
+
+ const compileArgs = ["-O2", cSource, "-o", outputBinary, ...gioFlags];
+
+ let result = attemptCompile("gcc", compileArgs);
+ if (result.status !== 0) {
+ result = attemptCompile("cc", compileArgs);
+ }
+
+ if (result.status !== 0) {
+ return false;
+ }
+
+ try {
+ fs.chmodSync(outputBinary, 0o755);
+ } catch (error) {
+ console.warn(`[linux-system-audio-helper] Unable to set executable permissions: ${error.message}`);
+ }
+
+ try {
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const hash = crypto
+ .createHash("sha256")
+ .update(sourceContent + gioFlags.join(" "))
+ .digest("hex");
+ fs.writeFileSync(hashFile, hash);
+ } catch (error) {
+ log(`Warning: Could not save source hash: ${error.message}`);
+ }
+
+ log("Successfully built Linux system audio helper binary");
+ return true;
+}
+
+function main() {
+ ensureDir(outputDir);
+
+ if (isBinaryUpToDate()) {
+ log("Binary is up to date, skipping build");
+ return;
+ }
+
+ if (!tryCompile()) {
+ console.warn(
+ "[linux-system-audio-helper] Native Linux portal helper is unavailable. Linux system audio will stay on the current fallback path."
+ );
+ }
+}
+
+main();
diff --git a/src/components/IntegrationsView.tsx b/src/components/IntegrationsView.tsx
index 0851a6586..d4233a573 100644
--- a/src/components/IntegrationsView.tsx
+++ b/src/components/IntegrationsView.tsx
@@ -18,6 +18,10 @@ export default function IntegrationsView() {
const [showPermissionDialog, setShowPermissionDialog] = useState(false);
const systemAudio = useSystemAudioPermission();
const hasAccounts = gcalAccounts.length > 0;
+ const needsSystemAudioGrant =
+ !systemAudio.granted &&
+ (systemAudio.mode === "native" ||
+ (systemAudio.mode === "portal" && systemAudio.supportsOnboardingGrant));
const startOAuth = useCallback(async () => {
setIsConnecting(true);
@@ -36,7 +40,7 @@ export default function IntegrationsView() {
}, [setGcalAccounts]);
const handleConnect = useCallback(async () => {
- if (systemAudio.mode === "native" && !systemAudio.granted) {
+ if (needsSystemAudioGrant) {
const granted = await systemAudio.request();
if (!granted) {
setShowPermissionDialog(true);
@@ -44,7 +48,7 @@ export default function IntegrationsView() {
}
}
await startOAuth();
- }, [systemAudio.mode, systemAudio.granted, systemAudio.request, startOAuth]);
+ }, [needsSystemAudioGrant, startOAuth, systemAudio]);
const handleDisconnect = useCallback(
async (email: string) => {
@@ -218,8 +222,12 @@ export default function IntegrationsView() {
onOpenChange={setShowPermissionDialog}
title={t("integrations.googleCalendar.systemAudioRequired")}
description={t("integrations.googleCalendar.systemAudioDescription")}
- confirmText={t("integrations.googleCalendar.openSettings")}
- onConfirm={systemAudio.openSettings}
+ confirmText={
+ systemAudio.mode === "native"
+ ? t("integrations.googleCalendar.openSettings")
+ : t("onboarding.permissions.grantAccess")
+ }
+ onConfirm={systemAudio.mode === "native" ? systemAudio.openSettings : systemAudio.request}
/>
</div>
);
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index e456bac8f..003419997 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -2777,7 +2777,7 @@ EOF`,
desc: t("settingsPage.general.waylandPaste.xclipDesc", {
defaultValue: "Clipboard tool for KDE Wayland paste (xclip or xsel)",
}),
- guide: [
+ steps: [
{
title: t("settingsPage.general.waylandPaste.guide.xclip.step1Title", {
defaultValue: "Install xclip",
@@ -3498,17 +3498,21 @@ EOF`,
buttonText={t("settingsPage.permissions.grantAccess")}
/>
- {platform === "darwin" && (
+ {(platform === "darwin" ||
+ (platform === "linux" && systemAudio.supportsOnboardingGrant)) && (
<>
- <PermissionCard
- icon={Shield}
- title={t("settingsPage.permissions.accessibilityTitle")}
- description={t("settingsPage.permissions.accessibilityDescription")}
- granted={permissionsHook.accessibilityPermissionGranted}
- onRequest={permissionsHook.requestAccessibilityPermission}
- buttonText={t("settingsPage.permissions.grantAccess")}
- />
- {systemAudio.mode === "native" && (
+ {platform === "darwin" && (
+ <PermissionCard
+ icon={Shield}
+ title={t("settingsPage.permissions.accessibilityTitle")}
+ description={t("settingsPage.permissions.accessibilityDescription")}
+ granted={permissionsHook.accessibilityPermissionGranted}
+ onRequest={permissionsHook.requestAccessibilityPermission}
+ buttonText={t("settingsPage.permissions.grantAccess")}
+ />
+ )}
+ {(systemAudio.mode === "native" ||
+ (systemAudio.mode === "portal" && systemAudio.supportsOnboardingGrant)) && (
<PermissionCard
icon={Monitor}
title={t("settingsPage.permissions.systemAudioTitle")}
diff --git a/src/components/UpcomingMeetings.tsx b/src/components/UpcomingMeetings.tsx
index 36b2866b3..77f4c1004 100644
--- a/src/components/UpcomingMeetings.tsx
+++ b/src/components/UpcomingMeetings.tsx
@@ -41,6 +41,10 @@ export default function UpcomingMeetings({ events, isLoading }: UpcomingMeetings
const [hoveredEventId, setHoveredEventId] = useState<string | null>(null);
const systemAudio = useSystemAudioPermission();
const isSignedIn = useSettingsStore((s) => s.isSignedIn);
+ const needsSystemAudioGrant =
+ !systemAudio.granted &&
+ (systemAudio.mode === "native" ||
+ (systemAudio.mode === "portal" && systemAudio.supportsOnboardingGrant));
const now = useMemo(() => new Date(), []);
@@ -104,7 +108,7 @@ export default function UpcomingMeetings({ events, isLoading }: UpcomingMeetings
{/* Empty state */}
{!isLoading && events.length === 0 && (
<div className="flex flex-col items-center justify-center py-8 px-3">
- {systemAudio.mode === "native" && !systemAudio.granted ? (
+ {needsSystemAudioGrant ? (
<>
<Monitor size={24} className="text-muted-foreground/30 mb-2.5" />
<p className="text-xs text-muted-foreground/60 text-center mb-3">
@@ -116,7 +120,9 @@ export default function UpcomingMeetings({ events, isLoading }: UpcomingMeetings
onClick={() => systemAudio.request()}
className="text-xs h-7"
>
- {t("upcoming.openSettings")}
+ {systemAudio.mode === "native"
+ ? t("upcoming.openSettings")
+ : t("onboarding.permissions.grantAccess")}
</Button>
</>
) : !isSignedIn ? (
diff --git a/src/components/notes/NotesOnboarding.tsx b/src/components/notes/NotesOnboarding.tsx
index 5754b8c78..5fbdfeaee 100644
--- a/src/components/notes/NotesOnboarding.tsx
+++ b/src/components/notes/NotesOnboarding.tsx
@@ -54,9 +54,13 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
const {
granted: systemAudioGranted,
mode: systemAudioMode,
+ supportsOnboardingGrant: systemAudioSupportsOnboardingGrant,
request: requestSystemAudio,
} = useSystemAudioPermission();
const [isRequestingSystemAudio, setIsRequestingSystemAudio] = useState(false);
+ const shouldShowSystemAudioPermission =
+ systemAudioMode === "native" ||
+ (systemAudioMode === "portal" && systemAudioSupportsOnboardingGrant);
const handleGrantSystemAudio = useCallback(async () => {
setIsRequestingSystemAudio(true);
@@ -185,7 +189,7 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
)}
{/* System Audio Permission */}
- {systemAudioMode !== "unsupported" && (
+ {shouldShowSystemAudioPermission && (
<div
className={cn(
"rounded-lg border transition-colors duration-200",
@@ -210,10 +214,10 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
</div>
</div>
{systemAudioGranted ? (
- <span className="text-xs text-success/60 font-medium shrink-0">
+ <span className="text-xs font-medium text-success/60 shrink-0">
{t("notes.onboarding.systemAudio.enabled")}
</span>
- ) : systemAudioMode === "native" ? (
+ ) : (
<Button
variant="outline"
size="sm"
@@ -227,7 +231,7 @@ export default function NotesOnboarding({ onComplete }: NotesOnboardingProps) {
t("notes.onboarding.systemAudio.grant")
)}
</Button>
- ) : null}
+ )}
</div>
</div>
)}
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index a0649d690..993ecb02f 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -170,7 +170,7 @@ export default function PersonalNotesView({
const startRecording = useCallback(async () => {
isMeetingModeRef.current = false;
- await startTranscription();
+ await startTranscription({ allowSystemAudio: true });
}, [startTranscription]);
const stopRecording = useCallback(async () => {
@@ -460,7 +460,7 @@ export default function PersonalNotesView({
if (!meetingRecordingRequest || activeNoteId !== meetingRecordingRequest.noteId) return;
meetingNoteIdRef.current = meetingRecordingRequest.noteId;
isMeetingModeRef.current = true;
- startTranscription();
+ startTranscription({ allowSystemAudio: false });
onMeetingRecordingRequestHandled?.();
}, [meetingRecordingRequest, activeNoteId, startTranscription, onMeetingRecordingRequestHandled]);
diff --git a/src/components/ui/PermissionsSection.tsx b/src/components/ui/PermissionsSection.tsx
index 9f4df7434..f899d672d 100644
--- a/src/components/ui/PermissionsSection.tsx
+++ b/src/components/ui/PermissionsSection.tsx
@@ -4,12 +4,11 @@ import PermissionCard from "./PermissionCard";
import MicPermissionWarning from "./MicPermissionWarning";
import PasteToolsInfo from "./PasteToolsInfo";
import type { UsePermissionsReturn } from "../../hooks/usePermissions";
+import type { SystemAudioAccessResult } from "../../types/electron";
interface PermissionsSectionProps {
permissions: UsePermissionsReturn;
- systemAudio: {
- granted: boolean;
- mode: "native" | "unsupported";
+ systemAudio: Pick<SystemAudioAccessResult, "granted" | "mode" | "supportsOnboardingGrant"> & {
request: () => Promise<boolean>;
};
}
@@ -18,6 +17,9 @@ export default function PermissionsSection({ permissions, systemAudio }: Permiss
const { t } = useTranslation();
const platform = permissions.pasteToolsInfo?.platform;
const isMacOS = platform === "darwin";
+ const shouldShowSystemAudioPermission =
+ systemAudio.mode === "native" ||
+ (systemAudio.mode === "portal" && systemAudio.supportsOnboardingGrant);
return (
<>
@@ -32,33 +34,32 @@ export default function PermissionsSection({ permissions, systemAudio }: Permiss
/>
{isMacOS && (
- <>
- <PermissionCard
- icon={Shield}
- title={t("onboarding.permissions.accessibilityTitle")}
- description={t("onboarding.permissions.accessibilityDescription")}
- granted={permissions.accessibilityPermissionGranted}
- onRequest={permissions.requestAccessibilityPermission}
- buttonText={t("onboarding.permissions.grantAccess")}
- badge={t("onboarding.permissions.recommended")}
- hint={
- permissions.accessibilityTroubleshooting
- ? t("onboarding.permissions.accessibilityTroubleshooting")
- : undefined
- }
- />
- {systemAudio.mode === "native" && (
- <PermissionCard
- icon={Monitor}
- title={t("onboarding.permissions.systemAudioTitle")}
- description={t("onboarding.permissions.systemAudioDescription")}
- granted={systemAudio.granted}
- onRequest={systemAudio.request}
- buttonText={t("onboarding.permissions.grantAccess")}
- badge={t("onboarding.permissions.optional")}
- />
- )}
- </>
+ <PermissionCard
+ icon={Shield}
+ title={t("onboarding.permissions.accessibilityTitle")}
+ description={t("onboarding.permissions.accessibilityDescription")}
+ granted={permissions.accessibilityPermissionGranted}
+ onRequest={permissions.requestAccessibilityPermission}
+ buttonText={t("onboarding.permissions.grantAccess")}
+ badge={t("onboarding.permissions.recommended")}
+ hint={
+ permissions.accessibilityTroubleshooting
+ ? t("onboarding.permissions.accessibilityTroubleshooting")
+ : undefined
+ }
+ />
+ )}
+
+ {shouldShowSystemAudioPermission && (
+ <PermissionCard
+ icon={Monitor}
+ title={t("onboarding.permissions.systemAudioTitle")}
+ description={t("onboarding.permissions.systemAudioDescription")}
+ granted={systemAudio.granted}
+ onRequest={systemAudio.request}
+ buttonText={t("onboarding.permissions.grantAccess")}
+ badge={t("onboarding.permissions.optional")}
+ />
)}
</div>
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 1ab7af5b9..ee2efdf97 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -104,6 +104,7 @@ class IPCHandlers {
this.googleCalendarManager = managers.googleCalendarManager;
this.meetingDetectionEngine = managers.meetingDetectionEngine;
this.audioTapManager = managers.audioTapManager;
+ this.linuxPortalAudioManager = managers.linuxPortalAudioManager;
this.sessionId = crypto.randomUUID();
this.assemblyAiStreaming = null;
this.deepgramStreaming = null;
@@ -2431,33 +2432,125 @@ class IPCHandlers {
return { granted: status === "granted", status };
});
- ipcMain.handle("check-system-audio-access", async () => {
- if (process.platform !== "darwin") {
- return { granted: true, status: "granted", mode: "loopback" };
+ const buildSystemAudioAccess = (partial = {}) => ({
+ granted: false,
+ status: "unsupported",
+ mode: "unsupported",
+ supportsPersistentGrant: false,
+ supportsOnboardingGrant: false,
+ requiresRuntimeSharePrompt: false,
+ strategy: "unsupported",
+ restoreTokenAvailable: false,
+ portalVersion: null,
+ ...partial,
+ });
+
+ const getLinuxSystemAudioAccess = async () => {
+ const capability = await this.linuxPortalAudioManager?.getCapability().catch((error) => ({
+ available: false,
+ supportsPersistentGrant: false,
+ portalVersion: null,
+ error: error.message,
+ }));
+ const supportsPersistentGrant = !!capability?.supportsPersistentGrant;
+ const restoreTokenAvailable =
+ supportsPersistentGrant && !!this.linuxPortalAudioManager?.hasStoredRestoreToken();
+ const helperError =
+ typeof capability?.error === "string" &&
+ !capability.error.includes("helper binary not found")
+ ? capability.error
+ : undefined;
+
+ return buildSystemAudioAccess({
+ granted: restoreTokenAvailable,
+ status: supportsPersistentGrant
+ ? restoreTokenAvailable
+ ? "granted"
+ : "not-determined"
+ : "unknown",
+ mode: "portal",
+ supportsPersistentGrant,
+ supportsOnboardingGrant: supportsPersistentGrant,
+ requiresRuntimeSharePrompt: !restoreTokenAvailable,
+ strategy: supportsPersistentGrant ? "portal-helper" : "browser-portal",
+ restoreTokenAvailable,
+ portalVersion: capability?.portalVersion ?? null,
+ error: helperError,
+ });
+ };
+
+ const getSystemAudioAccess = async () => {
+ if (process.platform === "win32") {
+ return buildSystemAudioAccess({
+ granted: true,
+ status: "granted",
+ mode: "loopback",
+ strategy: "loopback",
+ });
+ }
+
+ if (process.platform === "linux") {
+ return getLinuxSystemAudioAccess();
}
if (!this.audioTapManager?.isSupported()) {
- return { granted: false, status: "unsupported", mode: "unsupported" };
+ return buildSystemAudioAccess();
}
const result = await this.audioTapManager.verifyAccess();
- return { granted: result.granted, status: result.status, mode: "native" };
- });
+ return buildSystemAudioAccess({
+ granted: result.granted,
+ status: result.status,
+ mode: "native",
+ strategy: "native",
+ });
+ };
+
+ ipcMain.handle("check-system-audio-access", () => getSystemAudioAccess());
ipcMain.handle("request-system-audio-access", async () => {
- if (process.platform !== "darwin") {
- return { granted: true, status: "granted", mode: "loopback" };
+ if (process.platform === "win32") {
+ return buildSystemAudioAccess({
+ granted: true,
+ status: "granted",
+ mode: "loopback",
+ strategy: "loopback",
+ });
+ }
+
+ if (process.platform === "linux") {
+ const currentAccess = await getLinuxSystemAudioAccess();
+ if (!currentAccess.supportsOnboardingGrant) {
+ return currentAccess;
+ }
+
+ try {
+ await this.linuxPortalAudioManager?.requestAccess();
+ } catch (error) {
+ debugLogger.warn(
+ "Linux system audio persistent grant failed",
+ { error: error.message },
+ "meeting"
+ );
+ }
+
+ return getLinuxSystemAudioAccess();
}
if (!this.audioTapManager?.isSupported()) {
- return { granted: false, status: "unsupported", mode: "unsupported" };
+ return buildSystemAudioAccess();
}
// Probe the binary — AudioHardwareCreateProcessTap triggers the native consent dialog.
try {
const result = await this.audioTapManager.requestAccess();
if (result.granted) {
- return { granted: true, status: "granted", mode: "native" };
+ return buildSystemAudioAccess({
+ granted: true,
+ status: "granted",
+ mode: "native",
+ strategy: "native",
+ });
}
} catch {
// Falls through to opening System Settings
@@ -2466,7 +2559,12 @@ class IPCHandlers {
// Fallback for older macOS or if the native prompt was denied
await openSystemSettings("systemAudio");
const status = this.audioTapManager.getPermissionStatus();
- return { granted: false, status, mode: "native" };
+ return buildSystemAudioAccess({
+ granted: false,
+ status,
+ mode: "native",
+ strategy: "native",
+ });
});
// Auth: clear all session cookies for sign-out.
@@ -2877,17 +2975,45 @@ class IPCHandlers {
return data.clientSecret;
};
- const getMeetingSystemAudioMode = () => {
+ const getMeetingSystemAudioCapabilityMode = () => {
if (this.audioTapManager?.isSupported()) return "native";
- if (process.platform !== "darwin") return "loopback";
+ if (process.platform === "win32") return "loopback";
+ if (process.platform === "linux") return "portal";
return "unsupported";
};
- const hasMeetingSystemAudio = () => getMeetingSystemAudioMode() !== "unsupported";
+ const getMeetingSystemAudioMode = (options = {}) => {
+ const mode = getMeetingSystemAudioCapabilityMode();
+ if (options.allowSystemAudio === false) {
+ return "unsupported";
+ }
+ return mode;
+ };
+
+ const getMeetingSystemAudioPlan = async (options = {}) => {
+ const mode = getMeetingSystemAudioMode(options);
+ if (mode === "unsupported") {
+ return { mode, strategy: "unsupported" };
+ }
+
+ if (mode === "native") {
+ return { mode, strategy: "native" };
+ }
+
+ if (mode === "loopback") {
+ return { mode, strategy: "loopback" };
+ }
+
+ const linuxAccess = await getLinuxSystemAudioAccess();
+ return {
+ mode,
+ strategy: linuxAccess.strategy === "portal-helper" ? "portal-helper" : "browser-portal",
+ };
+ };
- const isMeetingStreamingConnected = () =>
+ const isMeetingStreamingConnected = (systemAudioMode) =>
!!this._meetingMicStreaming?.isConnected &&
- (!hasMeetingSystemAudio() || !!this._meetingSystemStreaming?.isConnected);
+ (systemAudioMode === "unsupported" || !!this._meetingSystemStreaming?.isConnected);
const connectRealtimeStreaming = async (event, options) => {
if (this._meetingMicStreaming?.isConnected) {
@@ -2905,8 +3031,9 @@ class IPCHandlers {
language: options.language,
preconfigured: options.mode !== "byok",
};
+ const { mode: systemAudioMode } = await getMeetingSystemAudioPlan(options);
let pairs;
- if (hasMeetingSystemAudio()) {
+ if (systemAudioMode !== "unsupported") {
const secrets = await fetchRealtimeToken(event, options, { streams: 2 });
pairs = [
{ ref: "_meetingMicStreaming", secret: secrets[0], source: "mic" },
@@ -3088,6 +3215,9 @@ class IPCHandlers {
if (this.audioTapManager) {
await this.audioTapManager.stop().catch(() => {});
}
+ if (this.linuxPortalAudioManager) {
+ await this.linuxPortalAudioManager.stop().catch(() => {});
+ }
resetMeetingLocalState();
await disconnectMeetingStreaming().catch(() => {});
};
@@ -3125,7 +3255,9 @@ class IPCHandlers {
return { success: false, error: "Operation in progress" };
}
- if (isMeetingStreamingConnected()) {
+ const { mode: systemAudioMode } = await getMeetingSystemAudioPlan(options);
+
+ if (isMeetingStreamingConnected(systemAudioMode)) {
debugLogger.debug("Meeting transcription already prepared (warm connections)");
return { success: true, alreadyPrepared: true };
}
@@ -3170,18 +3302,36 @@ class IPCHandlers {
meetingTranscriptionStartInProgress = true;
try {
- const systemAudioMode = getMeetingSystemAudioMode();
+ const systemAudioPlan = await getMeetingSystemAudioPlan(options);
+ let { mode: systemAudioMode, strategy: systemAudioStrategy } = systemAudioPlan;
+
+ if (systemAudioMode === "unsupported" && this._meetingSystemStreaming?.isConnected) {
+ await this._meetingSystemStreaming.disconnect().catch(() => ({ text: "" }));
+ this._meetingSystemStreaming = null;
+ }
// If already prepared (warm connections from prepare), just re-attach handlers
- if (!meetingLocalMode && isMeetingStreamingConnected()) {
+ if (!meetingLocalMode && isMeetingStreamingConnected(systemAudioMode)) {
debugLogger.debug("Meeting transcription start: reusing warm connections");
const win = BrowserWindow.fromWebContents(event.sender);
attachMeetingStreamingHandlers(this._meetingMicStreaming, win, "mic");
if (systemAudioMode === "native") {
attachMeetingStreamingHandlers(this._meetingSystemStreaming, win, "system");
await startNativeMeetingSystemAudio(event);
+ } else if (systemAudioStrategy === "portal-helper") {
+ attachMeetingStreamingHandlers(this._meetingSystemStreaming, win, "system");
+ try {
+ await startLinuxMeetingSystemAudio(event);
+ } catch (error) {
+ debugLogger.warn(
+ "Linux portal helper failed during warm-start reuse, falling back to browser portal",
+ { error: error.message },
+ "meeting"
+ );
+ systemAudioStrategy = "browser-portal";
+ }
}
- return { success: true, systemAudioMode };
+ return { success: true, systemAudioMode, systemAudioStrategy };
}
if (options.provider === "local") {
@@ -3198,14 +3348,26 @@ class IPCHandlers {
if (systemAudioMode === "native") {
await startNativeMeetingSystemAudio(event);
+ } else if (systemAudioStrategy === "portal-helper") {
+ try {
+ await startLinuxMeetingSystemAudio(event);
+ } catch (error) {
+ debugLogger.warn(
+ "Linux portal helper failed in local meeting mode, falling back to browser portal",
+ { error: error.message },
+ "meeting"
+ );
+ systemAudioStrategy = "browser-portal";
+ }
}
debugLogger.debug("Meeting transcription started in local mode", {
provider: meetingLocalProvider,
systemAudioMode,
+ systemAudioStrategy,
});
- return { success: true, systemAudioMode };
+ return { success: true, systemAudioMode, systemAudioStrategy };
}
if (options.provider !== "openai-realtime") {
@@ -3215,8 +3377,19 @@ class IPCHandlers {
await connectRealtimeStreaming(event, options);
if (systemAudioMode === "native") {
await startNativeMeetingSystemAudio(event);
+ } else if (systemAudioStrategy === "portal-helper") {
+ try {
+ await startLinuxMeetingSystemAudio(event);
+ } catch (error) {
+ debugLogger.warn(
+ "Linux portal helper failed in realtime mode, falling back to browser portal",
+ { error: error.message },
+ "meeting"
+ );
+ systemAudioStrategy = "browser-portal";
+ }
}
- return { success: true, systemAudioMode };
+ return { success: true, systemAudioMode, systemAudioStrategy };
} catch (error) {
await rollbackMeetingTranscriptionStart();
debugLogger.error("Meeting transcription start error", { error: error.message });
@@ -3269,6 +3442,27 @@ class IPCHandlers {
});
};
+ const startLinuxMeetingSystemAudio = async (event) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ await this.linuxPortalAudioManager.start({
+ onChunk: (chunk) => {
+ sendMeetingAudio(chunk, "system");
+ },
+ onError: (error) => {
+ if (win && !win.isDestroyed()) {
+ win.webContents.send("meeting-transcription-error", error.message);
+ }
+ },
+ onWarning: (warning) => {
+ debugLogger.warn(
+ "Linux portal system audio warning",
+ { code: warning.code, message: warning.message },
+ "meeting"
+ );
+ },
+ });
+ };
+
ipcMain.on("meeting-transcription-send", (_event, audioBuffer, source) => {
sendMeetingAudio(audioBuffer, source);
});
@@ -3278,6 +3472,9 @@ class IPCHandlers {
if (this.audioTapManager) {
await this.audioTapManager.stop();
}
+ if (this.linuxPortalAudioManager) {
+ await this.linuxPortalAudioManager.stop();
+ }
if (meetingLocalMode) {
if (meetingLocalTimer) {
diff --git a/src/helpers/linuxPortalAudioManager.js b/src/helpers/linuxPortalAudioManager.js
new file mode 100644
index 000000000..27bec0ff0
--- /dev/null
+++ b/src/helpers/linuxPortalAudioManager.js
@@ -0,0 +1,494 @@
+const { app } = require("electron");
+const { spawn } = require("child_process");
+const fs = require("fs");
+const path = require("path");
+const debugLogger = require("./debugLogger");
+
+const REQUEST_TIMEOUT_MS = 90000;
+const START_TIMEOUT_MS = 15000;
+const STOP_TIMEOUT_MS = 5000;
+const TOKEN_FILE_NAME = ".linux-system-audio-restore-token.json";
+
+class LinuxPortalAudioManager {
+ constructor() {
+ this.process = null;
+ this.stderrBuffer = "";
+ this.onChunk = null;
+ this.onError = null;
+ this.onWarning = null;
+ this.isStopping = false;
+ this.cachedCapability = null;
+ this.capabilityPromise = null;
+ }
+
+ isSupported() {
+ return process.platform === "linux";
+ }
+
+ isAvailable() {
+ return !!this.resolveBinary();
+ }
+
+ resolveBinary() {
+ const candidates = new Set([
+ path.join(__dirname, "..", "..", "resources", "bin", "linux-system-audio-helper"),
+ path.join(__dirname, "..", "..", "resources", "linux-system-audio-helper"),
+ ]);
+
+ if (process.resourcesPath) {
+ candidates.add(path.join(process.resourcesPath, "linux-system-audio-helper"));
+ candidates.add(path.join(process.resourcesPath, "bin", "linux-system-audio-helper"));
+ candidates.add(path.join(process.resourcesPath, "resources", "bin", "linux-system-audio-helper"));
+ candidates.add(
+ path.join(
+ process.resourcesPath,
+ "app.asar.unpacked",
+ "resources",
+ "bin",
+ "linux-system-audio-helper"
+ )
+ );
+ }
+
+ for (const candidate of candidates) {
+ if (fs.existsSync(candidate)) {
+ return candidate;
+ }
+ }
+
+ return null;
+ }
+
+ async getCapability({ force = false } = {}) {
+ if (!this.isSupported()) {
+ return this._buildCapability({ available: false, error: "Not running on Linux." });
+ }
+
+ if (!force && this.cachedCapability) {
+ return this.cachedCapability;
+ }
+
+ if (!force && this.capabilityPromise) {
+ return this.capabilityPromise;
+ }
+
+ const promise = this._probeCapability()
+ .catch((error) => {
+ debugLogger.warn(
+ "[LinuxPortalAudioManager] Capability probe failed",
+ { error: error.message },
+ "meeting"
+ );
+ return this._buildCapability({ available: false, error: error.message });
+ })
+ .then((capability) => {
+ this.cachedCapability = capability;
+ return capability;
+ })
+ .finally(() => {
+ this.capabilityPromise = null;
+ });
+
+ this.capabilityPromise = promise;
+ return promise;
+ }
+
+ hasStoredRestoreToken() {
+ return !!this.getStoredRestoreToken();
+ }
+
+ getStoredRestoreToken() {
+ try {
+ const raw = fs.readFileSync(this._tokenFilePath(), "utf8");
+ const parsed = JSON.parse(raw);
+ return typeof parsed?.restoreToken === "string" && parsed.restoreToken.trim()
+ ? parsed.restoreToken.trim()
+ : null;
+ } catch {
+ return null;
+ }
+ }
+
+ async requestAccess() {
+ const capability = await this.getCapability();
+ if (!capability.available || !capability.supportsPersistentGrant) {
+ return {
+ granted: false,
+ status: "unknown",
+ restoreTokenAvailable: false,
+ portalVersion: capability.portalVersion,
+ error: capability.error,
+ };
+ }
+
+ const result = await this._runJsonCommand(["grant"], REQUEST_TIMEOUT_MS);
+ const restoreToken =
+ typeof result?.restoreToken === "string" && result.restoreToken.trim()
+ ? result.restoreToken.trim()
+ : null;
+
+ if (restoreToken) {
+ this._writeTokenRecord({ restoreToken, portalVersion: capability.portalVersion });
+ }
+
+ return {
+ granted: !!result?.granted && !!restoreToken,
+ status: result?.granted && restoreToken ? "granted" : "unknown",
+ restoreTokenAvailable: !!restoreToken,
+ portalVersion: capability.portalVersion,
+ error: result?.error,
+ };
+ }
+
+ async start({ onChunk, onError, onWarning } = {}) {
+ const capability = await this.getCapability();
+ if (!capability.available || !capability.supportsSystemAudio) {
+ throw new Error(capability.error || "Linux portal system audio helper is unavailable.");
+ }
+
+ if (this.process) {
+ this.onChunk = onChunk || null;
+ this.onError = onError || null;
+ this.onWarning = onWarning || null;
+ return;
+ }
+
+ const binaryPath = this._prepareBinary();
+ const restoreToken = this.getStoredRestoreToken();
+ const args = ["start"];
+ if (restoreToken) {
+ args.push("--restore-token", restoreToken);
+ }
+
+ const child = spawn(binaryPath, args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+
+ this.process = child;
+ this.onChunk = onChunk || null;
+ this.onError = onError || null;
+ this.onWarning = onWarning || null;
+ this.isStopping = false;
+ this.stderrBuffer = "";
+
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const timeout = setTimeout(() => {
+ finish(
+ reject,
+ new Error("Timed out starting Linux portal system audio capture."),
+ true
+ );
+ }, START_TIMEOUT_MS);
+
+ const finish = (callback, value, shouldStop = false) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ if (shouldStop) {
+ void this.stop();
+ }
+ callback(value);
+ };
+
+ child.stdout.on("data", (chunk) => {
+ if (this.process !== child) return;
+ this.onChunk?.(chunk);
+ });
+
+ child.stderr.on("data", (chunk) => {
+ this._consumeStderr(chunk, (message) => {
+ if (message.type === "start") {
+ if (typeof message.restoreToken === "string" && message.restoreToken.trim()) {
+ this._writeTokenRecord({
+ restoreToken: message.restoreToken.trim(),
+ portalVersion: capability.portalVersion,
+ });
+ }
+ finish(resolve);
+ return;
+ }
+
+ if (message.type === "warning") {
+ if (message.code === "restore_failed") {
+ this.clearStoredRestoreToken();
+ }
+ this.onWarning?.(message);
+ return;
+ }
+
+ if (message.type === "error") {
+ if (
+ message.code === "restore_failed" ||
+ message.code === "permission_denied" ||
+ message.code === "portal_denied"
+ ) {
+ this.clearStoredRestoreToken();
+ }
+ const error = this._buildProcessError(message);
+ if (!settled) {
+ finish(reject, error, true);
+ } else {
+ this.onError?.(error);
+ }
+ }
+ });
+ });
+
+ child.on("error", (error) => {
+ if (this.process === child) {
+ this.process = null;
+ }
+ finish(reject, error);
+ });
+
+ child.on("exit", (code, signal) => {
+ const wasStopping = this.isStopping;
+ if (this.process === child) {
+ this.process = null;
+ }
+
+ if (!settled) {
+ finish(
+ reject,
+ new Error(
+ `Linux portal audio helper exited before start (code ${code ?? "null"}, signal ${signal ?? "null"}).`
+ )
+ );
+ return;
+ }
+
+ if (!wasStopping) {
+ this.onError?.(
+ new Error(
+ `Linux portal audio helper exited unexpectedly (code ${code ?? "null"}, signal ${signal ?? "null"}).`
+ )
+ );
+ }
+ });
+ });
+ }
+
+ async stop() {
+ if (!this.process) {
+ return;
+ }
+
+ const child = this.process;
+ this.isStopping = true;
+
+ await new Promise((resolve) => {
+ const timeout = setTimeout(() => {
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ resolve();
+ }
+ }, STOP_TIMEOUT_MS);
+
+ child.once("exit", () => {
+ clearTimeout(timeout);
+ resolve();
+ });
+
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ clearTimeout(timeout);
+ resolve();
+ }
+ });
+
+ if (this.process === child) {
+ this.process = null;
+ }
+ this.stderrBuffer = "";
+ this.onChunk = null;
+ this.onError = null;
+ this.onWarning = null;
+ this.isStopping = false;
+ }
+
+ clearStoredRestoreToken() {
+ try {
+ fs.unlinkSync(this._tokenFilePath());
+ } catch {}
+ }
+
+ _prepareBinary() {
+ const binaryPath = this.resolveBinary();
+ if (!binaryPath) {
+ throw new Error(
+ "Linux portal system audio helper not found. Run `npm run compile:linux-system-audio` before packaging."
+ );
+ }
+
+ try {
+ fs.accessSync(binaryPath, fs.constants.X_OK);
+ } catch {
+ fs.chmodSync(binaryPath, 0o755);
+ }
+
+ return binaryPath;
+ }
+
+ async _probeCapability() {
+ if (!this.resolveBinary()) {
+ return this._buildCapability({
+ available: false,
+ error: "Linux portal system audio helper binary not found.",
+ });
+ }
+
+ const result = await this._runJsonCommand(["probe"], REQUEST_TIMEOUT_MS);
+ return this._buildCapability(result);
+ }
+
+ _buildCapability(result = {}) {
+ const portalVersion = Number.isFinite(result?.portalVersion) ? result.portalVersion : null;
+ const supportsPersistMode = !!result?.supportsPersistMode;
+ const supportsRestoreToken = !!result?.supportsRestoreToken;
+ const supportsSystemAudio = !!result?.supportsSystemAudio;
+ const supportsNativeCapture = !!result?.supportsNativeCapture;
+ const available = !!result?.ok;
+ const supportsPersistentGrant =
+ available &&
+ supportsPersistMode &&
+ supportsRestoreToken &&
+ supportsSystemAudio &&
+ supportsNativeCapture;
+
+ return {
+ available,
+ portalVersion,
+ supportsPersistMode,
+ supportsRestoreToken,
+ supportsNativeCapture,
+ supportsPersistentGrant,
+ supportsSystemAudio,
+ error: typeof result?.error === "string" ? result.error : null,
+ source: typeof result?.source === "string" ? result.source : null,
+ };
+ }
+
+ _runJsonCommand(args, timeoutMs) {
+ const binaryPath = this._prepareBinary();
+ const child = spawn(binaryPath, args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+
+ let stdout = "";
+ let stderr = "";
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const timeout = setTimeout(() => {
+ finish(reject, new Error(`Linux portal helper timed out running ${args[0]}.`), true);
+ }, timeoutMs);
+
+ const finish = (callback, value, shouldStop = false) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ if (shouldStop) {
+ try {
+ child.kill("SIGKILL");
+ } catch {}
+ }
+ callback(value);
+ };
+
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk.toString();
+ });
+
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk.toString();
+ });
+
+ child.on("error", (error) => {
+ finish(reject, error);
+ });
+
+ child.on("exit", (code) => {
+ if (settled) return;
+
+ if (code !== 0) {
+ const message = stderr.trim() || stdout.trim() || `exit code ${code}`;
+ finish(reject, new Error(message));
+ return;
+ }
+
+ try {
+ finish(resolve, JSON.parse(stdout.trim() || "{}"));
+ } catch (error) {
+ finish(
+ reject,
+ new Error(
+ `Linux portal helper returned invalid JSON for ${args[0]}: ${stdout.trim().slice(0, 200)}`
+ )
+ );
+ }
+ });
+ });
+ }
+
+ _consumeStderr(chunk, onMessage) {
+ this.stderrBuffer += chunk.toString();
+ let newlineIndex = this.stderrBuffer.indexOf("\n");
+
+ while (newlineIndex !== -1) {
+ const line = this.stderrBuffer.slice(0, newlineIndex).trim();
+ this.stderrBuffer = this.stderrBuffer.slice(newlineIndex + 1);
+
+ if (line) {
+ try {
+ onMessage(JSON.parse(line));
+ } catch {
+ debugLogger.warn("[LinuxPortalAudioManager] Non-JSON stderr output", { line }, "meeting");
+ }
+ }
+
+ newlineIndex = this.stderrBuffer.indexOf("\n");
+ }
+ }
+
+ _buildProcessError(message) {
+ const error = new Error(message.message || "Linux portal system audio capture failed");
+ error.code = message.code;
+ error.status = message.status;
+ error.operation = message.operation;
+ return error;
+ }
+
+ _tokenFilePath() {
+ return path.join(app.getPath("userData"), TOKEN_FILE_NAME);
+ }
+
+ _writeTokenRecord({ restoreToken, portalVersion }) {
+ if (!restoreToken) return;
+
+ try {
+ fs.writeFileSync(
+ this._tokenFilePath(),
+ JSON.stringify(
+ {
+ restoreToken,
+ portalVersion: portalVersion ?? null,
+ updatedAt: new Date().toISOString(),
+ },
+ null,
+ 2
+ )
+ );
+ } catch (error) {
+ debugLogger.warn(
+ "[LinuxPortalAudioManager] Failed to persist restore token",
+ { error: error.message },
+ "meeting"
+ );
+ }
+ }
+}
+
+module.exports = LinuxPortalAudioManager;
diff --git a/src/hooks/useMeetingTranscription.ts b/src/hooks/useMeetingTranscription.ts
index 36d73f074..508014ac7 100644
--- a/src/hooks/useMeetingTranscription.ts
+++ b/src/hooks/useMeetingTranscription.ts
@@ -1,6 +1,8 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { getSettings } from "../stores/settingsStore";
import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";
+import { getCachedPlatform } from "../utils/platform";
+import type { SystemAudioAccessResult, SystemAudioStrategy } from "../types/electron";
import logger from "../utils/logger";
export interface TranscriptSegment {
@@ -19,7 +21,7 @@ interface UseMeetingTranscriptionReturn {
systemPartial: string;
error: string | null;
prepareTranscription: () => Promise<void>;
- startTranscription: () => Promise<void>;
+ startTranscription: (options?: { allowSystemAudio?: boolean }) => Promise<void>;
stopTranscription: () => Promise<void>;
}
@@ -27,6 +29,17 @@ const MEETING_AUDIO_BUFFER_SIZE = 800;
const MEETING_STOP_FLUSH_TIMEOUT_MS = 50;
const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);
+const DEFAULT_SYSTEM_AUDIO_ACCESS: SystemAudioAccessResult = {
+ granted: false,
+ status: "unsupported",
+ mode: "unsupported",
+ supportsPersistentGrant: false,
+ supportsOnboardingGrant: false,
+ requiresRuntimeSharePrompt: false,
+ strategy: "unsupported",
+ restoreTokenAvailable: false,
+ portalVersion: null,
+};
const getMeetingTranscriptionOptions = () => {
const {
@@ -57,6 +70,81 @@ const getMeetingTranscriptionOptions = () => {
return { provider: "openai-realtime" as const, model, mode };
};
+const getFallbackSystemAudioAccess = (): SystemAudioAccessResult => {
+ const platform = getCachedPlatform();
+
+ if (platform === "win32") {
+ return {
+ ...DEFAULT_SYSTEM_AUDIO_ACCESS,
+ granted: true,
+ status: "granted",
+ mode: "loopback",
+ strategy: "loopback",
+ };
+ }
+
+ if (platform === "linux") {
+ return {
+ ...DEFAULT_SYSTEM_AUDIO_ACCESS,
+ status: "unknown",
+ mode: "portal",
+ requiresRuntimeSharePrompt: true,
+ strategy: "browser-portal",
+ };
+ }
+
+ return DEFAULT_SYSTEM_AUDIO_ACCESS;
+};
+
+const isRendererSystemAudioStrategy = (
+ strategy: SystemAudioStrategy | undefined | null
+): strategy is "loopback" | "browser-portal" =>
+ strategy === "loopback" || strategy === "browser-portal";
+
+const getDisplayCaptureModeForStrategy = (strategy: "loopback" | "browser-portal") =>
+ strategy === "loopback" ? "loopback" : "portal";
+
+const stopMediaStream = (stream: MediaStream | null) => {
+ try {
+ stream?.getTracks().forEach((track) => track.stop());
+ } catch {}
+};
+
+const getDisplayCaptureOptions = (mode: "loopback" | "portal") => {
+ if (mode === "loopback") {
+ return { video: true, audio: true };
+ }
+
+ return {
+ video: true,
+ audio: true,
+ systemAudio: "include",
+ windowAudio: "system",
+ selfBrowserSurface: "exclude",
+ } as DisplayMediaStreamOptions & {
+ systemAudio?: "include";
+ windowAudio?: "system";
+ selfBrowserSurface?: "exclude";
+ };
+};
+
+const requestSystemAudioDisplayStream = async (mode: "loopback" | "portal") => {
+ try {
+ const stream = await navigator.mediaDevices.getDisplayMedia(getDisplayCaptureOptions(mode));
+ const audioTrack = stream.getAudioTracks()[0];
+
+ if (!audioTrack) {
+ stopMediaStream(stream);
+ return { stream: null, error: new Error("No system-audio track was returned.") };
+ }
+
+ stream.getVideoTracks().forEach((track) => track.stop());
+ return { stream, error: null };
+ } catch (error) {
+ return { stream: null, error: error as Error };
+ }
+};
+
const getMeetingWorkletBlobUrl = (() => {
let blobUrl: string | null = null;
@@ -361,9 +449,21 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
await promise;
}, []);
- const startTranscription = useCallback(async () => {
+ const startTranscription = useCallback(async (options?: { allowSystemAudio?: boolean }) => {
if (isRecordingRef.current || isStartingRef.current) return;
isStartingRef.current = true;
+ const allowSystemAudio = options?.allowSystemAudio ?? true;
+ const systemAudioAccessPromise = allowSystemAudio
+ ? window.electronAPI?.checkSystemAudioAccess?.()
+ : Promise.resolve(DEFAULT_SYSTEM_AUDIO_ACCESS);
+
+ if (!allowSystemAudio && getCachedPlatform() === "linux") {
+ logger.info(
+ "Linux system audio skipped for non-user-initiated start, continuing with mic only",
+ {},
+ "meeting"
+ );
+ }
logger.info("Meeting transcription starting...", {}, "meeting");
setTranscript("");
@@ -385,9 +485,25 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
try {
const startTime = performance.now();
-
- const [startResult, micResult] = await Promise.all([
- window.electronAPI?.meetingTranscriptionStart?.(getMeetingTranscriptionOptions()),
+ const initialSystemAudioAccess =
+ (await systemAudioAccessPromise) ?? getFallbackSystemAudioAccess();
+ const initialSystemAudioStrategy = initialSystemAudioAccess.strategy ?? "unsupported";
+ const initialDisplayCaptureStrategy = isRendererSystemAudioStrategy(
+ initialSystemAudioStrategy
+ )
+ ? initialSystemAudioStrategy
+ : null;
+ const systemCapturePromise = initialDisplayCaptureStrategy
+ ? requestSystemAudioDisplayStream(
+ getDisplayCaptureModeForStrategy(initialDisplayCaptureStrategy)
+ )
+ : Promise.resolve({ stream: null, error: null });
+
+ const [startResult, micResult, initialSystemCaptureResult] = await Promise.all([
+ window.electronAPI?.meetingTranscriptionStart?.({
+ ...getMeetingTranscriptionOptions(),
+ allowSystemAudio,
+ }),
getMeetingMicConstraints().then((constraints) =>
navigator.mediaDevices.getUserMedia(constraints).catch((err) => {
logger.error(
@@ -398,13 +514,16 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
return null;
})
),
+ systemCapturePromise,
]);
+ let systemCaptureResult = initialSystemCaptureResult;
const streamsMs = performance.now() - startTime;
// Abort if stop was called during setup
if (!isRecordingRef.current) {
logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");
- micResult?.getTracks().forEach((t) => t.stop());
+ stopMediaStream(micResult);
+ stopMediaStream(systemCaptureResult.stream);
isStartingRef.current = false;
return;
}
@@ -416,19 +535,41 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
"meeting"
);
setError(startResult?.error || "Failed to start meeting transcription");
- micResult?.getTracks().forEach((track) => track.stop());
+ stopMediaStream(micResult);
+ stopMediaStream(systemCaptureResult.stream);
isRecordingRef.current = false;
isStartingRef.current = false;
setIsRecording(false);
return;
}
- const systemAudioMode = startResult.systemAudioMode || "unsupported";
+ const systemAudioMode = startResult.systemAudioMode || initialSystemAudioAccess.mode;
+ let systemAudioStrategy = startResult.systemAudioStrategy || initialSystemAudioStrategy;
+
+ if (
+ allowSystemAudio &&
+ !systemCaptureResult.stream &&
+ !systemCaptureResult.error &&
+ isRendererSystemAudioStrategy(systemAudioStrategy) &&
+ !initialDisplayCaptureStrategy
+ ) {
+ systemCaptureResult = await requestSystemAudioDisplayStream(
+ getDisplayCaptureModeForStrategy(systemAudioStrategy)
+ );
+ }
- if (!micResult && systemAudioMode === "unsupported") {
+ const systemAudioHandledInMain =
+ systemAudioMode !== "unsupported" && !isRendererSystemAudioStrategy(systemAudioStrategy);
+ const systemCaptureError =
+ systemAudioHandledInMain ? null : systemCaptureResult.error;
+
+ if (!micResult && !systemCaptureResult.stream && !systemAudioHandledInMain) {
logger.error("Meeting transcription has no available audio source", {}, "meeting");
setError(
- "No microphone is available and system audio capture is unsupported on this device."
+ systemAudioMode === "unsupported"
+ ? "No microphone is available and system audio capture is unsupported on this device."
+ : systemCaptureError?.message ||
+ "No microphone is available and system audio capture could not be started."
);
await window.electronAPI?.meetingTranscriptionStop?.();
isRecordingRef.current = false;
@@ -491,6 +632,7 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
if (errorCleanup) ipcCleanupsRef.current.push(errorCleanup);
const pendingMicChunks: ArrayBuffer[] = [];
+ const pendingSystemChunks: ArrayBuffer[] = [];
let socketReady = false;
let micPipelinePromise: Promise<void> | null = null;
@@ -532,35 +674,41 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
await micPipelinePromise;
}
- if (systemAudioMode === "loopback") {
- try {
- const displayStream = await navigator.mediaDevices.getDisplayMedia({
- video: true,
- audio: true,
- });
- displayStream.getVideoTracks().forEach((t) => t.stop());
-
- const systemContext = new AudioContext({ sampleRate: 24000 });
- await detachFromOutputDevice(systemContext);
- systemContextRef.current = systemContext;
- systemStreamRef.current = displayStream;
-
- await createAudioPipeline({
- stream: displayStream,
- context: systemContext,
- label: "Meeting system",
- onChunk: (chunk) => {
- if (!isRecordingRef.current) return;
+ if (systemCaptureResult.stream) {
+ const systemStream = systemCaptureResult.stream;
+ systemStreamRef.current = systemStream;
+
+ const systemContext = new AudioContext({ sampleRate: 24000 });
+ await detachFromOutputDevice(systemContext);
+ systemContextRef.current = systemContext;
+
+ await createAudioPipeline({
+ stream: systemStream,
+ context: systemContext,
+ label: "Meeting system",
+ onChunk: (chunk) => {
+ if (!isRecordingRef.current) return;
+ if (socketReady) {
window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");
- },
- }).then(({ source, processor }) => {
- systemSourceRef.current = source;
- systemProcessorRef.current = processor;
- });
- } catch (err) {
+ return;
+ }
+ pendingSystemChunks.push(chunk.slice(0));
+ },
+ }).then(({ source, processor }) => {
+ systemSourceRef.current = source;
+ systemProcessorRef.current = processor;
+ });
+ } else if (systemCaptureError) {
+ if (systemAudioStrategy === "browser-portal") {
+ logger.warn(
+ "Linux system audio capture failed, continuing with mic only",
+ { error: systemCaptureError.message },
+ "meeting"
+ );
+ } else if (systemAudioStrategy === "loopback") {
logger.warn(
"System audio loopback failed, continuing with mic only",
- { error: (err as Error).message },
+ { error: systemCaptureError.message },
"meeting"
);
}
@@ -584,13 +732,18 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {
for (const chunk of pendingMicChunks) {
window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");
}
+ for (const chunk of pendingSystemChunks) {
+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "system");
+ }
const totalMs = performance.now() - startTime;
logger.info(
"Meeting transcription started successfully",
{
systemAudioMode,
+ systemAudioStrategy,
bufferedChunks: pendingMicChunks.length,
+ bufferedSystemChunks: pendingSystemChunks.length,
streamsMs: Math.round(streamsMs),
totalMs: Math.round(totalMs),
wasPrepared: isPreparedRef.current,
diff --git a/src/hooks/useSystemAudioPermission.ts b/src/hooks/useSystemAudioPermission.ts
index 283fd3de2..05dc06460 100644
--- a/src/hooks/useSystemAudioPermission.ts
+++ b/src/hooks/useSystemAudioPermission.ts
@@ -6,6 +6,12 @@ const DEFAULT_ACCESS: SystemAudioAccessResult = {
granted: false,
status: "unsupported",
mode: "unsupported",
+ supportsPersistentGrant: false,
+ supportsOnboardingGrant: false,
+ requiresRuntimeSharePrompt: false,
+ strategy: "unsupported",
+ restoreTokenAvailable: false,
+ portalVersion: null,
};
export function useSystemAudioPermission() {
@@ -43,14 +49,20 @@ export function useSystemAudioPermission() {
}, []);
const request = useCallback(async (): Promise<boolean> => {
- const currentAccess = access ?? (await window.electronAPI?.checkSystemAudioAccess?.()) ?? DEFAULT_ACCESS;
+ const currentAccess =
+ access ?? (await window.electronAPI?.checkSystemAudioAccess?.()) ?? DEFAULT_ACCESS;
if (currentAccess.mode === "loopback") {
setAccess(currentAccess);
return currentAccess.granted;
}
- if (currentAccess.mode !== "native") {
+ if (currentAccess.mode === "portal") {
+ if (!currentAccess.supportsOnboardingGrant) {
+ setAccess(currentAccess);
+ return currentAccess.granted;
+ }
+ } else if (currentAccess.mode !== "native") {
setAccess(currentAccess);
return false;
}
@@ -71,6 +83,27 @@ export function useSystemAudioPermission() {
const granted = access?.granted ?? false;
const status = access?.status ?? "unknown";
const mode = access?.mode ?? "unsupported";
+ const supportsPersistentGrant = access?.supportsPersistentGrant ?? false;
+ const supportsOnboardingGrant = access?.supportsOnboardingGrant ?? false;
+ const requiresRuntimeSharePrompt = access?.requiresRuntimeSharePrompt ?? false;
+ const strategy = access?.strategy ?? "unsupported";
+ const restoreTokenAvailable = access?.restoreTokenAvailable ?? false;
+ const portalVersion = access?.portalVersion ?? null;
- return { granted, status, mode, isChecking, request, openSettings, check, isMacOS };
+ return {
+ granted,
+ status,
+ mode,
+ supportsPersistentGrant,
+ supportsOnboardingGrant,
+ requiresRuntimeSharePrompt,
+ strategy,
+ restoreTokenAvailable,
+ portalVersion,
+ isChecking,
+ request,
+ openSettings,
+ check,
+ isMacOS,
+ };
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 59523c5f1..5f5c369ce 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -122,10 +122,24 @@ export interface AudioDiagnosticsResult {
models: string[];
}
+export type SystemAudioMode = "native" | "loopback" | "portal" | "unsupported";
+export type SystemAudioStrategy =
+ | "native"
+ | "loopback"
+ | "browser-portal"
+ | "portal-helper"
+ | "unsupported";
+
export interface SystemAudioAccessResult {
granted: boolean;
status: "granted" | "denied" | "not-determined" | "restricted" | "unknown" | "unsupported";
- mode: "native" | "loopback" | "unsupported";
+ mode: SystemAudioMode;
+ supportsPersistentGrant?: boolean;
+ supportsOnboardingGrant?: boolean;
+ requiresRuntimeSharePrompt?: boolean;
+ strategy?: SystemAudioStrategy;
+ restoreTokenAvailable?: boolean;
+ portalVersion?: number | null;
error?: string;
}
@@ -1287,15 +1301,18 @@ declare global {
provider?: string;
model?: string;
language?: string;
+ allowSystemAudio?: boolean;
}) => Promise<{ success: boolean; alreadyPrepared?: boolean; error?: string }>;
meetingTranscriptionStart?: (options: {
provider?: string;
model?: string;
language?: string;
+ allowSystemAudio?: boolean;
}) => Promise<{
success: boolean;
error?: string;
- systemAudioMode?: "native" | "loopback" | "unsupported";
+ systemAudioMode?: SystemAudioMode;
+ systemAudioStrategy?: SystemAudioStrategy;
}>;
meetingTranscriptionSend?: (buffer: ArrayBuffer, source: "mic" | "system") => void;
meetingTranscriptionStop?: () => Promise<{