Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

meeting: fix recording stop button and add push-driven status stream (#3136)

Divanshudd8f3e0a97dd
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index 31f65bd9c..64a2577f2 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -49,9 +49,9 @@ import { useTeam } from "@/lib/hooks/use-team";
import { useEnterprisePolicy } from "@/lib/hooks/use-enterprise-policy";
import { EnterpriseLicensePrompt } from "@/components/enterprise-license-prompt";
import { open as openUrl } from "@tauri-apps/plugin-shell";
-import { computeMeetingActive, type MeetingRow } from "@/lib/utils/meeting-state";
+import { computeMeetingActive, type MeetingStatusResponse } from "@/lib/utils/meeting-state";
import { useRouter } from "next/navigation";
-import { localFetch } from "@/lib/api";
+import { appendAuthToken, ensureApiReady, getApiBaseUrl, localFetch } from "@/lib/api";
import {
Tooltip,
TooltipContent,
@@ -260,11 +260,17 @@ function HomeContent() {
}, [settings.monitorIds, settings.useAllMonitors]);
// Active meeting state — lights up the phone icon for ANY active meeting
- // (manual OR auto-detected: Teams, Zoom, etc.). manualActive is true only
- // when the user can stop it via the icon click.
- const [meetingState, setMeetingState] = useState<{ active: boolean; manualActive: boolean }>(
- { active: false, manualActive: false },
- );
+ // (manual OR auto-detected: Teams, Zoom, etc.).
+ const [meetingState, setMeetingState] = useState<MeetingStatusResponse & {
+ manualActive: boolean;
+ }>({
+ active: false,
+ manualActive: false,
+ activeMeetingId: null,
+ stoppableMeetingId: null,
+ meetingApp: null,
+ detectionSource: null,
+ });
const [meetingLoading, setMeetingLoading] = useState(false);
// Timestamp when user clicked start, used for a 10s grace period so a
@@ -272,34 +278,79 @@ function HomeContent() {
const manualMeetingStartedAt = useRef<number>(0);
useEffect(() => {
let cancelled = false;
- const check = () => {
- localFetch("/meetings?limit=5")
- .then((r) => r.ok ? r.json() : [])
- .then((meetings: MeetingRow[]) => {
+ let ws: WebSocket | null = null;
+ let retry: ReturnType<typeof setTimeout> | null = null;
+ let backoffMs = 1000;
+
+ const connect = () => {
+ void (async () => {
+ try {
+ await ensureApiReady();
if (cancelled) return;
- setMeetingState(
- computeMeetingActive(meetings, manualMeetingStartedAt.current),
- );
- })
- .catch(() => {});
+ const wsBase = getApiBaseUrl().replace("http://", "ws://");
+ ws = new WebSocket(appendAuthToken(`${wsBase}/ws/meeting-status`));
+ ws.onopen = () => {
+ backoffMs = 1000;
+ };
+ ws.onmessage = (event) => {
+ try {
+ const parsed = JSON.parse(event.data) as MeetingStatusResponse;
+ if (cancelled) return;
+ setMeetingState(
+ computeMeetingActive(parsed, manualMeetingStartedAt.current),
+ );
+ } catch {
+ // ignore malformed event payloads
+ }
+ };
+ ws.onclose = (event) => {
+ if (cancelled || event.code === 1000) return;
+ retry = setTimeout(connect, backoffMs);
+ backoffMs = Math.min(backoffMs * 2, 10000);
+ };
+ ws.onerror = () => {
+ ws?.close();
+ };
+ } catch {
+ if (cancelled) return;
+ retry = setTimeout(connect, backoffMs);
+ backoffMs = Math.min(backoffMs * 2, 10000);
+ }
+ })();
+ };
+
+ connect();
+ return () => {
+ cancelled = true;
+ if (retry) clearTimeout(retry);
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
+ ws.close(1000, "unmount");
+ }
};
- check();
- const interval = setInterval(check, 5000);
- return () => { cancelled = true; clearInterval(interval); };
}, []);
const toggleMeeting = useCallback(async () => {
setMeetingLoading(true);
try {
- if (meetingState.manualActive) {
- // Stop the manual meeting we previously started
- await localFetch("/meetings/stop", { method: "POST" });
- manualMeetingStartedAt.current = 0;
- setMeetingState({ active: false, manualActive: false });
- } else if (meetingState.active) {
- // Auto-detected meeting in progress — icon is a passive indicator,
- // user can't stop someone else's Teams/Zoom call from here
- return;
+ if (meetingState.active) {
+ // Stop the currently active meeting, whether manual or auto-detected.
+ const targetId = meetingState.stoppableMeetingId;
+ const res = await localFetch("/meetings/stop", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ id: targetId }),
+ });
+ if (res.ok) {
+ manualMeetingStartedAt.current = 0;
+ setMeetingState({
+ active: false,
+ manualActive: false,
+ activeMeetingId: null,
+ stoppableMeetingId: null,
+ meetingApp: null,
+ detectionSource: null,
+ });
+ }
} else {
// No meeting active — start a manual one
const res = await localFetch("/meetings/start", {
@@ -309,7 +360,14 @@ function HomeContent() {
});
if (res.ok) {
manualMeetingStartedAt.current = Date.now();
- setMeetingState({ active: true, manualActive: true });
+ setMeetingState({
+ active: true,
+ manualActive: true,
+ activeMeetingId: null,
+ stoppableMeetingId: null,
+ meetingApp: "manual",
+ detectionSource: "manual",
+ });
}
}
} catch (e) {
@@ -319,14 +377,41 @@ function HomeContent() {
}
}, [meetingState]);
- // Native overlay: toggle meeting when user clicks phone icon in Swift overlay
+ // Native overlay already toggles the meeting in Rust. Refresh local state
+ // here instead of toggling again, otherwise one click can create or stop
+ // two meetings depending on which UI surfaces are mounted.
useEffect(() => {
let unlisten: (() => void) | null = null;
- listen("native-shortcut-toggle-meeting", () => {
- toggleMeeting();
+ listen<MeetingStatusResponse>("native-shortcut-toggle-meeting", (event) => {
+ const payload = event.payload;
+ if (typeof payload?.active === "boolean") {
+ if (payload.active) {
+ manualMeetingStartedAt.current = Date.now();
+ } else {
+ manualMeetingStartedAt.current = 0;
+ }
+ setMeetingState({
+ active: payload.active,
+ manualActive: payload.manualActive ?? false,
+ activeMeetingId: payload.activeMeetingId ?? null,
+ stoppableMeetingId: payload.stoppableMeetingId ?? payload.activeMeetingId ?? null,
+ meetingApp: payload.meetingApp ?? null,
+ detectionSource: payload.detectionSource ?? null,
+ });
+ return;
+ }
+ void (async () => {
+ try {
+ const res = await localFetch("/meetings/status");
+ const status = res.ok ? await res.json() as MeetingStatusResponse : null;
+ setMeetingState(computeMeetingActive(status, manualMeetingStartedAt.current));
+ } catch {
+ // ignore sync failures; websocket remains source of truth
+ }
+ })();
}).then((fn) => { unlisten = fn; });
return () => { unlisten?.(); };
- }, [toggleMeeting]);
+ }, []);
// Watch pipe: navigate to chat when user clicks "watch" on a running pipe
useEffect(() => {
@@ -566,7 +651,7 @@ function HomeContent() {
<TooltipTrigger asChild>
<button
onClick={toggleMeeting}
- disabled={meetingLoading || (meetingState.active && !meetingState.manualActive)}
+ disabled={meetingLoading}
className={cn(
"relative flex items-center justify-center h-5 w-5 rounded transition-colors",
isTranslucent ? "vibrant-nav-item hover:bg-white/10" : "text-muted-foreground hover:text-foreground hover:bg-muted"
@@ -579,7 +664,7 @@ function HomeContent() {
</button>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs">
- {meetingState.manualActive ? "stop meeting" : meetingState.active ? "meeting detected" : "start meeting"}
+ {meetingState.active ? "stop meeting" : "start meeting"}
</TooltipContent>
</Tooltip>
</div>
diff --git a/apps/screenpipe-app-tauri/app/shortcut-reminder/page.tsx b/apps/screenpipe-app-tauri/app/shortcut-reminder/page.tsx
index 17e86c1de..9c2895009 100644
--- a/apps/screenpipe-app-tauri/app/shortcut-reminder/page.tsx
+++ b/apps/screenpipe-app-tauri/app/shortcut-reminder/page.tsx
@@ -19,35 +19,70 @@ import { X, Phone } from "lucide-react";
import { useOverlayData } from "./use-overlay-data";
import { AudioEqualizer } from "./audio-equalizer";
import { ScreenMatrix } from "./screen-matrix";
+import { computeMeetingActive, type MeetingStatusResponse } from "@/lib/utils/meeting-state";
+import { appendAuthToken, ensureApiReady, getApiBaseUrl } from "@/lib/api";
function useMeetingState() {
- const [active, setActive] = useState(false);
+ const [meetingState, setMeetingState] = useState(() => computeMeetingActive(null, 0));
const [loading, setLoading] = useState(false);
useEffect(() => {
- let abortCtrl: AbortController | null = null;
- const check = () => {
- abortCtrl?.abort();
- abortCtrl = new AbortController();
- localFetch("/meetings/status", { signal: abortCtrl.signal })
- .then((r) => r.json())
- .then((d) => setActive(!!d.active))
- .catch(() => {});
+ let ws: WebSocket | null = null;
+ let retry: ReturnType<typeof setTimeout> | null = null;
+ let backoffMs = 1000;
+
+ const connect = () => {
+ void (async () => {
+ try {
+ await ensureApiReady();
+ const wsBase = getApiBaseUrl().replace("http://", "ws://");
+ ws = new WebSocket(appendAuthToken(`${wsBase}/ws/meeting-status`));
+ ws.onopen = () => {
+ backoffMs = 1000;
+ };
+ ws.onmessage = (event) => {
+ try {
+ const parsed = JSON.parse(event.data) as MeetingStatusResponse;
+ setMeetingState(computeMeetingActive(parsed, 0));
+ } catch {
+ // ignore malformed payloads
+ }
+ };
+ ws.onclose = (event) => {
+ if (event.code === 1000) return;
+ retry = setTimeout(connect, backoffMs);
+ backoffMs = Math.min(backoffMs * 2, 10000);
+ };
+ ws.onerror = () => {
+ ws?.close();
+ };
+ } catch {
+ retry = setTimeout(connect, backoffMs);
+ backoffMs = Math.min(backoffMs * 2, 10000);
+ }
+ })();
};
- check();
- const id = setInterval(check, 5000);
+
+ connect();
+
return () => {
- clearInterval(id);
- abortCtrl?.abort();
+ if (retry) clearTimeout(retry);
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
+ ws.close(1000, "unmount");
+ }
};
}, []);
const toggle = useCallback(async () => {
setLoading(true);
try {
- if (active) {
- await localFetch("/meetings/stop", { method: "POST" });
- setActive(false);
+ if (meetingState.active) {
+ await localFetch("/meetings/stop", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ id: meetingState.stoppableMeetingId }),
+ });
+ setMeetingState(computeMeetingActive(null, 0));
} else {
const res = await localFetch("/meetings/start", {
method: "POST",
@@ -55,16 +90,21 @@ function useMeetingState() {
body: JSON.stringify({ app: "manual" }),
});
if (res.ok) {
- setActive(true);
+ setMeetingState(computeMeetingActive({
+ active: true,
+ manualActive: true,
+ meetingApp: "manual",
+ detectionSource: "manual",
+ }, Date.now()));
}
}
} catch (e) {
console.error("meeting toggle failed:", e);
}
setLoading(false);
- }, [active]);
+ }, [meetingState]);
- return { active, loading, toggle };
+ return { active: meetingState.active, loading, toggle };
}
export default function ShortcutReminderPage() {
diff --git a/apps/screenpipe-app-tauri/lib/utils/meeting-state.test.ts b/apps/screenpipe-app-tauri/lib/utils/meeting-state.test.ts
index 6603df316..e573a62da 100644
--- a/apps/screenpipe-app-tauri/lib/utils/meeting-state.test.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/meeting-state.test.ts
@@ -6,40 +6,57 @@ import { describe, it, expect } from "bun:test";
import {
computeMeetingActive,
MEETING_GRACE_PERIOD_MS,
- type MeetingRow,
+ type MeetingStatusResponse,
} from "./meeting-state";
const NEVER_CLICKED = 0;
const NOW = 1_000_000;
-const manualActive: MeetingRow = { meeting_end: null, detection_source: "manual" };
-const teamsActive: MeetingRow = { meeting_end: null, detection_source: "ui_scan" };
-const zoomActive: MeetingRow = { meeting_end: null, detection_source: "ui_scan" };
-const ended: MeetingRow = { meeting_end: "2026-04-07T19:00:00Z", detection_source: "ui_scan" };
+const manualActive: MeetingStatusResponse = {
+ active: true, manualActive: true, activeMeetingId: 41, stoppableMeetingId: 41, meetingApp: "manual", detectionSource: "manual",
+};
+const manualLegacy: MeetingStatusResponse = {
+ active: true, manual: true, activeMeetingId: 42, stoppableMeetingId: 42, meetingApp: "manual", detectionSource: "manual",
+};
+const teamsActive: MeetingStatusResponse = {
+ active: true, manualActive: false, activeMeetingId: 51, stoppableMeetingId: 51, meetingApp: "teams", detectionSource: "ui_scan",
+};
+const zoomActive: MeetingStatusResponse = {
+ active: true, manualActive: false, activeMeetingId: 52, stoppableMeetingId: 52, meetingApp: "zoom", detectionSource: "ui_scan",
+};
+const inactive: MeetingStatusResponse = { active: false, manualActive: false };
describe("computeMeetingActive", () => {
describe("auto-detected meetings (the bug we're fixing)", () => {
it("lights up for an active Teams meeting", () => {
- const r = computeMeetingActive([teamsActive], NEVER_CLICKED, NOW);
+ const r = computeMeetingActive(teamsActive, NEVER_CLICKED, NOW);
expect(r.active).toBe(true);
expect(r.manualActive).toBe(false);
+ expect(r.stoppableMeetingId).toBe(51);
});
it("lights up for an active Zoom meeting", () => {
- const r = computeMeetingActive([zoomActive], NEVER_CLICKED, NOW);
+ const r = computeMeetingActive(zoomActive, NEVER_CLICKED, NOW);
expect(r.active).toBe(true);
expect(r.manualActive).toBe(false);
});
it("manualActive=false for ui_scan meetings (so user can't stop them via icon)", () => {
- const r = computeMeetingActive([teamsActive], NEVER_CLICKED, NOW);
+ const r = computeMeetingActive(teamsActive, NEVER_CLICKED, NOW);
expect(r.manualActive).toBe(false);
});
});
describe("manual meetings", () => {
it("lights up and is stoppable for an active manual meeting", () => {
- const r = computeMeetingActive([manualActive], NEVER_CLICKED, NOW);
+ const r = computeMeetingActive(manualActive, NEVER_CLICKED, NOW);
+ expect(r.active).toBe(true);
+ expect(r.manualActive).toBe(true);
+ expect(r.activeMeetingId).toBe(41);
+ });
+
+ it("supports the legacy 'manual' key for compatibility", () => {
+ const r = computeMeetingActive(manualLegacy, NEVER_CLICKED, NOW);
expect(r.active).toBe(true);
expect(r.manualActive).toBe(true);
});
@@ -47,61 +64,49 @@ describe("computeMeetingActive", () => {
describe("no active meeting", () => {
it("is off when there are no meetings at all", () => {
- const r = computeMeetingActive([], NEVER_CLICKED, NOW);
+ const r = computeMeetingActive(null, NEVER_CLICKED, NOW);
expect(r.active).toBe(false);
expect(r.manualActive).toBe(false);
+ expect(r.stoppableMeetingId).toBeNull();
});
- it("is off when only ended meetings exist", () => {
- const r = computeMeetingActive([ended], NEVER_CLICKED, NOW);
+ it("is off when status explicitly says inactive", () => {
+ const r = computeMeetingActive(inactive, NEVER_CLICKED, NOW);
expect(r.active).toBe(false);
expect(r.manualActive).toBe(false);
});
});
- describe("mixed meetings", () => {
- it("lights up if any meeting is active even when others ended", () => {
- const r = computeMeetingActive([ended, teamsActive], NEVER_CLICKED, NOW);
- expect(r.active).toBe(true);
- expect(r.manualActive).toBe(false);
- });
-
- it("manualActive=true if both manual and auto are active", () => {
- const r = computeMeetingActive([manualActive, teamsActive], NEVER_CLICKED, NOW);
- expect(r.active).toBe(true);
- expect(r.manualActive).toBe(true);
- });
- });
-
describe("grace period after user clicks start", () => {
it("trusts local click within grace period even if poll returns nothing", () => {
const startedAt = NOW - 1000;
- const r = computeMeetingActive([], startedAt, NOW);
+ const r = computeMeetingActive(null, startedAt, NOW);
expect(r.active).toBe(true);
expect(r.manualActive).toBe(true); // grace period implies manual click
+ expect(r.detectionSource).toBe("manual");
});
it("trusts local click at exactly the start of the grace period", () => {
- const r = computeMeetingActive([], NOW, NOW);
+ const r = computeMeetingActive(null, NOW, NOW);
expect(r.active).toBe(true);
});
it("clears state once grace period expires", () => {
const startedAt = NOW - MEETING_GRACE_PERIOD_MS - 1;
- const r = computeMeetingActive([], startedAt, NOW);
+ const r = computeMeetingActive(null, startedAt, NOW);
expect(r.active).toBe(false);
});
it("clears state right at the grace period boundary", () => {
const startedAt = NOW - MEETING_GRACE_PERIOD_MS;
- const r = computeMeetingActive([], startedAt, NOW);
+ const r = computeMeetingActive(null, startedAt, NOW);
expect(r.active).toBe(false);
});
it("does NOT consider startedAt=0 as 'within grace period'", () => {
// Edge case: if NOW is small (e.g. just after epoch in tests),
// startedAt=0 would falsely look like "0ms ago".
- const r = computeMeetingActive([], 0, 5_000);
+ const r = computeMeetingActive(null, 0, 5_000);
expect(r.active).toBe(false);
});
});
@@ -109,29 +114,24 @@ describe("computeMeetingActive", () => {
describe("server data wins over grace period when present", () => {
it("active meeting from server overrides grace period", () => {
const startedAt = NOW - 1000;
- const r = computeMeetingActive([teamsActive], startedAt, NOW);
+ const r = computeMeetingActive(teamsActive, startedAt, NOW);
expect(r.active).toBe(true);
- expect(r.manualActive).toBe(false); // ui_scan, not manual
+ expect(r.manualActive).toBe(false);
});
it("active meeting from server keeps icon on after grace period", () => {
const startedAt = NOW - MEETING_GRACE_PERIOD_MS - 5000;
- const r = computeMeetingActive([teamsActive], startedAt, NOW);
+ const r = computeMeetingActive(teamsActive, startedAt, NOW);
expect(r.active).toBe(true);
});
});
- describe("regression coverage for the manual-only filter bug", () => {
- it("does not require detection_source to be 'manual'", () => {
- // The bug we're fixing: previous code only counted manual meetings.
- const r = computeMeetingActive([teamsActive], NEVER_CLICKED, NOW);
- expect(r.active).toBe(true);
- });
-
- it("works with unknown detection_source values", () => {
- const exotic: MeetingRow = { meeting_end: null, detection_source: "future_source" };
- const r = computeMeetingActive([exotic], NEVER_CLICKED, NOW);
+ describe("status-shape compatibility", () => {
+ it("treats missing manual flags as non-manual active meetings", () => {
+ const r = computeMeetingActive({ active: true }, NEVER_CLICKED, NOW);
expect(r.active).toBe(true);
+ expect(r.manualActive).toBe(false);
+ expect(r.stoppableMeetingId).toBeNull();
});
});
});
diff --git a/apps/screenpipe-app-tauri/lib/utils/meeting-state.ts b/apps/screenpipe-app-tauri/lib/utils/meeting-state.ts
index dc832626e..43a0744e1 100644
--- a/apps/screenpipe-app-tauri/lib/utils/meeting-state.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/meeting-state.ts
@@ -16,11 +16,6 @@
* "active" state. We trust the local click for 10s after start.
*/
-export interface MeetingRow {
- meeting_end: string | null;
- detection_source: string;
-}
-
export const MEETING_GRACE_PERIOD_MS = 10_000;
export interface MeetingActiveState {
@@ -28,26 +23,48 @@ export interface MeetingActiveState {
active: boolean;
/** True only if the active meeting is a manual one the user can stop */
manualActive: boolean;
+ /** Exact active meeting row id, when known */
+ activeMeetingId: number | null;
+ /** Exact meeting id the UI should send to /meetings/stop */
+ stoppableMeetingId: number | null;
+ /** Meeting app name for the current active meeting */
+ meetingApp: string | null;
+ /** Source that created the current active meeting */
+ detectionSource: string | null;
+}
+
+export interface MeetingStatusResponse {
+ active?: boolean;
+ manual?: boolean;
+ manualActive?: boolean;
+ activeMeetingId?: number | null;
+ stoppableMeetingId?: number | null;
+ meetingApp?: string | null;
+ detectionSource?: string | null;
}
/**
- * Decide the phone-icon state given the latest poll response and the
- * timestamp of the last user click.
+ * Decide the phone-icon state given the latest meeting status response and
+ * the timestamp of the last user click.
*
- * @param meetings rows from GET /meetings
+ * @param status response from GET /meetings/status
* @param startedAtMs timestamp (ms) of last user click on "start" (0 if never)
* @param nowMs current time in ms (injectable for tests)
*/
export function computeMeetingActive(
- meetings: MeetingRow[],
+ status: MeetingStatusResponse | null | undefined,
startedAtMs: number,
nowMs: number = Date.now(),
): MeetingActiveState {
- const activeRows = meetings.filter((m) => m.meeting_end === null);
- const hasActiveManual = activeRows.some((m) => m.detection_source === "manual");
-
- if (activeRows.length > 0) {
- return { active: true, manualActive: hasActiveManual };
+ if (status?.active) {
+ return {
+ active: true,
+ manualActive: status.manualActive ?? status.manual ?? false,
+ activeMeetingId: status.activeMeetingId ?? null,
+ stoppableMeetingId: status.stoppableMeetingId ?? status.activeMeetingId ?? null,
+ meetingApp: status.meetingApp ?? null,
+ detectionSource: status.detectionSource ?? null,
+ };
}
// No active meeting from server — but if we're within the grace period
@@ -58,8 +75,22 @@ export function computeMeetingActive(
startedAtMs > 0 && nowMs - startedAtMs < MEETING_GRACE_PERIOD_MS;
if (inGracePeriod) {
- return { active: true, manualActive: true };
+ return {
+ active: true,
+ manualActive: true,
+ activeMeetingId: null,
+ stoppableMeetingId: null,
+ meetingApp: "manual",
+ detectionSource: "manual",
+ };
}
- return { active: false, manualActive: false };
+ return {
+ active: false,
+ manualActive: false,
+ activeMeetingId: null,
+ stoppableMeetingId: null,
+ meetingApp: null,
+ detectionSource: null,
+ };
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 6945e57dc..f7861d5cd 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -189,32 +189,66 @@ extern "C" fn native_shortcut_action_callback(action_ptr: *const std::os::raw::c
let client = reqwest::blocking::Client::new();
let status_req =
api.apply_auth_blocking(client.get(api.url("/meetings/status")));
- let status: Option<bool> = status_req
+ let status: Option<serde_json::Value> = status_req
.send()
.ok()
- .and_then(|r| r.json::<serde_json::Value>().ok())
+ .and_then(|r| r.json::<serde_json::Value>().ok());
+ let is_active = status
+ .as_ref()
.and_then(|v| v["active"].as_bool());
+ let stoppable_id = status
+ .as_ref()
+ .and_then(|v| v["stoppableMeetingId"].as_i64());
match status {
- Some(true) => {
- let req =
- api.apply_auth_blocking(client.post(api.url("/meetings/stop")));
- let _ = req.send();
+ Some(_) if is_active == Some(true) => {
+ let req = api.apply_auth_blocking(
+ client
+ .post(api.url("/meetings/stop"))
+ .header("Content-Type", "application/json")
+ .body(serde_json::json!({ "id": stoppable_id }).to_string()),
+ );
+ if req.send().is_ok() {
+ native_shortcut_reminder::set_meeting_active(false);
+ let _ = app_clone.emit(
+ "native-shortcut-toggle-meeting",
+ serde_json::json!({
+ "active": false,
+ "manualActive": false,
+ "activeMeetingId": serde_json::Value::Null,
+ "stoppableMeetingId": serde_json::Value::Null,
+ "meetingApp": serde_json::Value::Null,
+ "detectionSource": serde_json::Value::Null,
+ }),
+ );
+ }
}
- Some(false) => {
+ Some(_) if is_active == Some(false) => {
let req = api.apply_auth_blocking(
client
.post(api.url("/meetings/start"))
.header("Content-Type", "application/json")
.body(r#"{"app":"manual"}"#),
);
- let _ = req.send();
+ if let Ok(res) = req.send() {
+ let meeting = res.json::<serde_json::Value>().ok();
+ native_shortcut_reminder::set_meeting_active(true);
+ let _ = app_clone.emit(
+ "native-shortcut-toggle-meeting",
+ serde_json::json!({
+ "active": true,
+ "manualActive": true,
+ "activeMeetingId": meeting.as_ref().and_then(|v| v["id"].as_i64()),
+ "stoppableMeetingId": meeting.as_ref().and_then(|v| v["id"].as_i64()),
+ "meetingApp": meeting.as_ref().and_then(|v| v["meeting_app"].as_str()),
+ "detectionSource": meeting.as_ref().and_then(|v| v["detection_source"].as_str()).unwrap_or("manual"),
+ }),
+ );
+ }
}
- None => {
+ _ => {
warn!("failed to check meeting status");
}
}
- // Also emit to JS so the home page UI updates immediately if open
- let _ = app_clone.emit("native-shortcut-toggle-meeting", "");
}
_ => {}
}
@@ -1439,20 +1473,19 @@ pub async fn show_shortcut_reminder(
let guard = state.server.lock().await;
if let Some(ref core) = *guard {
let mut metrics_ws_url = format!("ws://127.0.0.1:{}/ws/metrics", core.port);
- let mut meetings_status_url =
- format!("http://127.0.0.1:{}/meetings/status", core.port);
+ let mut events_ws_url = format!("ws://127.0.0.1:{}/ws/meeting-status", core.port);
if let Some(ref key) = core.local_api_key {
let enc = urlencoding::encode(key);
metrics_ws_url = format!("{}?token={}", metrics_ws_url, enc);
- meetings_status_url = format!("{}?token={}", meetings_status_url, enc);
+ events_ws_url = format!("{}?token={}", events_ws_url, enc);
}
map.insert(
"metrics_ws_url".to_string(),
serde_json::json!(metrics_ws_url),
);
map.insert(
- "meetings_status_url".to_string(),
- serde_json::json!(meetings_status_url),
+ "events_ws_url".to_string(),
+ serde_json::json!(events_ws_url),
);
}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/native_shortcut_reminder.rs b/apps/screenpipe-app-tauri/src-tauri/src/native_shortcut_reminder.rs
index 733630e1a..22342b4d7 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/native_shortcut_reminder.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/native_shortcut_reminder.rs
@@ -16,6 +16,7 @@ mod ffi {
pub fn shortcut_is_available() -> c_int;
pub fn shortcut_show(json: *const c_char) -> c_int;
pub fn shortcut_hide() -> c_int;
+ pub fn shortcut_set_meeting_active(active: c_int);
pub fn shortcut_set_action_callback(cb: Option<extern "C" fn(*const c_char)>);
}
@@ -40,6 +41,12 @@ mod ffi {
unsafe { shortcut_hide() == 0 }
}
+ pub fn set_meeting_active(active: bool) {
+ unsafe {
+ shortcut_set_meeting_active(if active { 1 } else { 0 });
+ }
+ }
+
pub fn set_action_callback(cb: extern "C" fn(*const c_char)) {
unsafe {
shortcut_set_action_callback(Some(cb));
@@ -59,6 +66,7 @@ mod ffi {
pub fn hide() -> bool {
false
}
+ pub fn set_meeting_active(_active: bool) {}
pub fn set_action_callback(_cb: extern "C" fn(*const std::os::raw::c_char)) {}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/swift/shortcut_reminder.swift b/apps/screenpipe-app-tauri/src-tauri/swift/shortcut_reminder.swift
index f2739c25b..69701266b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/swift/shortcut_reminder.swift
+++ b/apps/screenpipe-app-tauri/src-tauri/swift/shortcut_reminder.swift
@@ -15,6 +15,13 @@ public func shortcutSetActionCallback(_ cb: @escaping ShortcutActionCallback) {
gShortcutCallback = cb
}
+@_cdecl("shortcut_set_meeting_active")
+public func shortcutSetMeetingActive(_ active: Int32) {
+ if #available(macOS 13.0, *) {
+ ShortcutReminderController.shared.setMeetingActive(active != 0)
+ }
+}
+
// MARK: - Metrics data pushed from Rust
struct OverlayMetrics {
@@ -371,12 +378,13 @@ class ShortcutReminderController: NSObject {
@Published var isExpanded = false
private var wsTask: URLSessionWebSocketTask?
private var wsRetryTimer: Timer?
- private var meetingPollTimer: Timer?
+ private var meetingWsTask: URLSessionWebSocketTask?
+ private var meetingWsRetryTimer: Timer?
private var prevFramesCaptured: Int?
private var prevOcrCompleted: Int?
/// Set from Rust `show_shortcut_reminder` when API auth is enabled (includes ?token=).
private var metricsWsUrl = "ws://127.0.0.1:3030/ws/metrics"
- private var meetingsStatusUrl = "http://127.0.0.1:3030/meetings/status"
+ private var eventsWsUrl = "ws://127.0.0.1:3030/ws/meeting-status"
func show(shortcuts: String?) {
DispatchQueue.main.async { [self] in
@@ -397,15 +405,14 @@ class ShortcutReminderController: NSObject {
panel?.orderFrontRegardless()
AnimationTick.shared.start()
connectWebSocket()
- startMeetingPoll()
+ connectMeetingEventsWebSocket()
}
}
func hide() {
AnimationTick.shared.stop()
disconnectWebSocket()
- meetingPollTimer?.invalidate()
- meetingPollTimer = nil
+ disconnectMeetingEventsWebSocket()
DispatchQueue.main.async { [self] in
panel?.orderOut(nil)
}
@@ -478,29 +485,58 @@ class ShortcutReminderController: NSObject {
}
}
- // MARK: - Meeting status polling
+ // MARK: - Meeting status events
- private func startMeetingPoll() {
- checkMeetingStatus()
- meetingPollTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
- self?.checkMeetingStatus()
- }
- RunLoop.main.add(meetingPollTimer!, forMode: .common)
- }
-
- private func checkMeetingStatus() {
- guard let url = URL(string: meetingsStatusUrl) else { return }
- URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
- guard let self = self, let data = data,
- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
- let active = json["active"] as? Bool ?? false
- DispatchQueue.main.async {
- if self.metrics.meetingActive != active {
- self.metrics.meetingActive = active
- self.updateContent()
+ private func connectMeetingEventsWebSocket() {
+ disconnectMeetingEventsWebSocket()
+ guard let url = URL(string: eventsWsUrl) else { return }
+ let session = URLSession(configuration: .default)
+ let task = session.webSocketTask(with: url)
+ self.meetingWsTask = task
+ task.resume()
+ receiveMeetingEvent()
+ }
+
+ private func disconnectMeetingEventsWebSocket() {
+ meetingWsRetryTimer?.invalidate()
+ meetingWsRetryTimer = nil
+ meetingWsTask?.cancel(with: .goingAway, reason: nil)
+ meetingWsTask = nil
+ }
+
+ private func receiveMeetingEvent() {
+ meetingWsTask?.receive { [weak self] result in
+ guard let self = self else { return }
+ switch result {
+ case .success(let message):
+ if case .string(let text) = message {
+ self.processMeetingEventMessage(text)
}
+ self.receiveMeetingEvent()
+ case .failure:
+ DispatchQueue.main.async {
+ self.meetingWsRetryTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { [weak self] _ in
+ self?.connectMeetingEventsWebSocket()
+ }
+ }
+ }
+ }
+ }
+
+ private func processMeetingEventMessage(_ text: String) {
+ guard let data = text.data(using: .utf8),
+ let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
+ let active = payload["active"] as? Bool ?? false
+ setMeetingActive(active)
+ }
+
+ func setMeetingActive(_ active: Bool) {
+ DispatchQueue.main.async { [self] in
+ if self.metrics.meetingActive != active {
+ self.metrics.meetingActive = active
+ self.updateContent()
}
- }.resume()
+ }
}
private func parseShortcuts(_ json: String) {
@@ -511,7 +547,7 @@ class ShortcutReminderController: NSObject {
if let s = dict["chat"] { chatShortcut = prettifyShortcut(s) }
if let s = dict["search"] { searchShortcut = prettifyShortcut(s) }
if let s = dict["metrics_ws_url"] { metricsWsUrl = s }
- if let s = dict["meetings_status_url"] { meetingsStatusUrl = s }
+ if let s = dict["events_ws_url"] { eventsWsUrl = s }
}
/// Convert "Super+Ctrl+S" → "⌘⌃S" for compact overlay display.
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 142117b19..6dd66204d 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -7013,6 +7013,17 @@ LIMIT ? OFFSET ?
Ok(row.0 > 0)
}
+ pub async fn get_active_meeting_by_id(&self, id: i64) -> Result<Option<MeetingRecord>, SqlxError> {
+ let meeting = sqlx::query_as::<_, MeetingRecord>(
+ "SELECT id, meeting_start, meeting_end, meeting_app, title, attendees, note, \
+ detection_source, created_at FROM meetings WHERE id = ?1 AND meeting_end IS NULL",
+ )
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(meeting)
+ }
+
pub async fn get_most_recent_active_meeting_id(&self) -> Result<Option<i64>, SqlxError> {
let row: Option<(i64,)> = sqlx::query_as(
"SELECT id FROM meetings WHERE meeting_end IS NULL ORDER BY id DESC LIMIT 1",
@@ -7022,6 +7033,17 @@ LIMIT ? OFFSET ?
Ok(row.map(|r| r.0))
}
+ pub async fn get_most_recent_active_meeting(&self) -> Result<Option<MeetingRecord>, SqlxError> {
+ let meeting = sqlx::query_as::<_, MeetingRecord>(
+ "SELECT id, meeting_start, meeting_end, meeting_app, title, attendees, note, \
+ detection_source, created_at FROM meetings WHERE meeting_end IS NULL \
+ ORDER BY id DESC LIMIT 1",
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(meeting)
+ }
+
pub async fn list_meetings(
&self,
start_time: Option<&str>,
diff --git a/crates/screenpipe-engine/src/meeting_detector.rs b/crates/screenpipe-engine/src/meeting_detector.rs
index 726d3b4a7..9645e7ab7 100644
--- a/crates/screenpipe-engine/src/meeting_detector.rs
+++ b/crates/screenpipe-engine/src/meeting_detector.rs
@@ -25,6 +25,7 @@
use chrono::{DateTime, Utc};
use futures::{FutureExt, StreamExt};
+use crate::routes::meetings::{emit_meeting_status_changed, resolve_meeting_status_from};
use screenpipe_db::DatabaseManager;
use screenpipe_events::subscribe_to_event;
use serde::{Deserialize, Serialize};
@@ -2190,6 +2191,9 @@ pub async fn run_meeting_detection_loop(
let mut cal_sub = subscribe_to_event::<Vec<CalendarEventSignal>>("calendar_events");
let mut calendar_events: Vec<CalendarEventSignal> = Vec::new();
+ // Subscribe to explicit stop signals from the API layer
+ let mut stop_sub = subscribe_to_event::<DetectorStopSignal>("detector_stop_tracking");
+
info!(
"meeting v2: detection loop started (base_interval={:?}, profiles={})",
base_interval,
@@ -2225,6 +2229,27 @@ pub async fn run_meeting_detection_loop(
calendar_events = event.data.into_iter().filter(|e| !e.is_all_day).collect();
}
+ // Handle explicit stop signals from the API layer
+ if let Some(event) = stop_sub.next().now_or_never().flatten() {
+ let stop_signal = event.data;
+ if let MeetingState::Active { meeting_id, app, .. } | MeetingState::Ending {
+ meeting_id,
+ app,
+ ..
+ } = &state
+ {
+ if *meeting_id == stop_signal.meeting_id && app == &stop_signal.app {
+ info!(
+ "meeting v2: forced to Idle by explicit stop (meeting_id={}, app={})",
+ meeting_id, app
+ );
+ state = MeetingState::Idle;
+ current_interval = IDLE_APPS_SCAN_INTERVAL;
+ sync_meeting_flag(false, &in_meeting_flag, &detector);
+ }
+ }
+ }
+
// Skip if manual meeting is active
{
let manual = manual_meeting.read().await;
@@ -2299,6 +2324,11 @@ pub async fn run_meeting_detection_loop(
) {
warn!("meeting v2: failed to emit meeting_ended event: {}", e);
}
+ if let Ok(status) =
+ resolve_meeting_status_from(db.as_ref(), manual_meeting.as_ref()).await
+ {
+ emit_meeting_status_changed(&status);
+ }
}
Err(e) => {
error!("meeting v2: failed to end meeting {}: {}", meeting_id, e);
@@ -2469,6 +2499,11 @@ pub async fn run_meeting_detection_loop(
is_browser,
};
}
+ if let Ok(status) =
+ resolve_meeting_status_from(db.as_ref(), manual_meeting.as_ref()).await
+ {
+ emit_meeting_status_changed(&status);
+ }
}
StateAction::EndMeeting { meeting_id } => {
if meeting_id >= 0 {
@@ -2483,6 +2518,11 @@ pub async fn run_meeting_detection_loop(
) {
warn!("meeting v2: failed to emit meeting_ended event: {}", e);
}
+ if let Ok(status) =
+ resolve_meeting_status_from(db.as_ref(), manual_meeting.as_ref()).await
+ {
+ emit_meeting_status_changed(&status);
+ }
}
Err(e) => {
error!("meeting v2: failed to end meeting {}: {}", meeting_id, e);
@@ -2620,6 +2660,12 @@ struct CalendarEventSignal {
pub is_all_day: bool,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct DetectorStopSignal {
+ pub meeting_id: i64,
+ pub app: String,
+}
+
/// Check if any non-all-day calendar event overlaps with the current time.
/// Returns (title, attendees) of the first matching event, or (None, None).
fn find_overlapping_calendar_event(
diff --git a/crates/screenpipe-engine/src/routes/meetings.rs b/crates/screenpipe-engine/src/routes/meetings.rs
index 97c4f612c..0e9eb3362 100644
--- a/crates/screenpipe-engine/src/routes/meetings.rs
+++ b/crates/screenpipe-engine/src/routes/meetings.rs
@@ -9,13 +9,15 @@ use axum::{
};
use oasgen::{oasgen, OaSchema};
+use screenpipe_db::DatabaseManager;
use screenpipe_db::MeetingRecord;
use crate::server::AppState;
use chrono::Utc;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
+use tokio::sync::RwLock;
#[derive(OaSchema, Deserialize, Debug)]
pub struct UpdateMeetingRequest {
@@ -44,6 +46,11 @@ pub struct StartMeetingRequest {
pub attendees: Option<String>,
}
+#[derive(OaSchema, Deserialize, Debug)]
+pub struct StopMeetingRequest {
+ pub id: Option<i64>,
+}
+
#[derive(OaSchema, Deserialize, Debug)]
pub struct ListMeetingsRequest {
pub start_time: Option<String>,
@@ -58,6 +65,106 @@ fn default_limit() -> u32 {
20
}
+#[derive(OaSchema, Debug, Serialize, Deserialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct MeetingStatusResponse {
+ pub active: bool,
+ pub manual: bool,
+ pub manual_active: bool,
+ pub active_meeting_id: Option<i64>,
+ pub stoppable_meeting_id: Option<i64>,
+ pub meeting_app: Option<String>,
+ pub detection_source: Option<String>,
+}
+
+async fn resolve_meeting_status(
+ state: &Arc<AppState>,
+) -> Result<MeetingStatusResponse, (StatusCode, JsonResponse<Value>)> {
+ resolve_meeting_status_from(&state.db, &state.manual_meeting)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e})),
+ )
+ })
+}
+
+pub async fn resolve_meeting_status_from(
+ db: &DatabaseManager,
+ manual_meeting: &RwLock<Option<i64>>,
+) -> Result<MeetingStatusResponse, String> {
+ let manual_id = {
+ let lock = manual_meeting.read().await;
+ *lock
+ };
+
+ if let Some(id) = manual_id {
+ match db.get_active_meeting_by_id(id).await {
+ Ok(Some(meeting)) => {
+ return Ok(MeetingStatusResponse {
+ active: true,
+ manual: true,
+ manual_active: true,
+ active_meeting_id: Some(meeting.id),
+ stoppable_meeting_id: Some(meeting.id),
+ meeting_app: Some(meeting.meeting_app),
+ detection_source: Some(meeting.detection_source),
+ });
+ }
+ Ok(None) => {
+ let mut lock = manual_meeting.write().await;
+ if *lock == Some(id) {
+ *lock = None;
+ }
+ }
+ Err(e) => {
+ return Err(e.to_string());
+ }
+ }
+ }
+
+ let active = db
+ .get_most_recent_active_meeting()
+ .await
+ .map_err(|e| e.to_string())?;
+
+ match active {
+ Some(meeting) => Ok(MeetingStatusResponse {
+ active: true,
+ manual: false,
+ manual_active: false,
+ active_meeting_id: Some(meeting.id),
+ stoppable_meeting_id: Some(meeting.id),
+ meeting_app: Some(meeting.meeting_app),
+ detection_source: Some(meeting.detection_source),
+ }),
+ None => Ok(MeetingStatusResponse {
+ active: false,
+ manual: false,
+ manual_active: false,
+ active_meeting_id: None,
+ stoppable_meeting_id: None,
+ meeting_app: None,
+ detection_source: None,
+ }),
+ }
+}
+
+pub fn emit_meeting_status_changed(status: &MeetingStatusResponse) {
+ tracing::info!(
+ "meeting_status_changed: active={}, manual={}, active_id={:?}, app={:?}, source={:?}",
+ status.active,
+ status.manual,
+ status.active_meeting_id,
+ status.meeting_app,
+ status.detection_source
+ );
+ if let Err(e) = screenpipe_events::send_event("meeting_status_changed", status.clone()) {
+ tracing::warn!("failed to emit meeting_status_changed event: {}", e);
+ }
+}
+
#[oasgen]
pub(crate) async fn list_meetings_handler(
State(state): State<Arc<AppState>>,
@@ -202,23 +309,8 @@ pub(crate) async fn merge_meetings_handler(
#[oasgen]
pub(crate) async fn meeting_status_handler(
State(state): State<Arc<AppState>>,
-) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
- // Check manual meeting first
- let manual_active = {
- let lock = state.manual_meeting.read().await;
- lock.is_some()
- };
-
- // Also check DB for any ongoing meeting (auto-detected)
- let any_active = if manual_active {
- true
- } else {
- state.db.has_active_meeting().await.unwrap_or(false)
- };
-
- Ok(JsonResponse(
- json!({ "active": any_active, "manual": manual_active }),
- ))
+) -> Result<JsonResponse<MeetingStatusResponse>, (StatusCode, JsonResponse<Value>)> {
+ Ok(JsonResponse(resolve_meeting_status(&state).await?))
}
#[oasgen]
@@ -248,6 +340,10 @@ pub(crate) async fn start_meeting_handler(
*lock = Some(id);
}
+ if let Ok(status) = resolve_meeting_status(&state).await {
+ emit_meeting_status_changed(&status);
+ }
+
// Emit event so triggered pipes can react
if let Err(e) = screenpipe_events::send_event(
"meeting_started",
@@ -269,35 +365,27 @@ pub(crate) async fn start_meeting_handler(
#[oasgen]
pub(crate) async fn stop_meeting_handler(
State(state): State<Arc<AppState>>,
+ axum::Json(body): axum::Json<StopMeetingRequest>,
) -> Result<JsonResponse<MeetingRecord>, (StatusCode, JsonResponse<Value>)> {
- let id = {
- let lock = state.manual_meeting.read().await;
- *lock
- };
-
- // If no manual meeting, find any active meeting (auto-detected) and end it.
- // This lets users stop auto-detected meetings (Google Meet, Zoom, etc.)
- // from the overlay button.
- let id = match id {
- Some(id) => id,
- None => {
- let active_id = state
- .db
- .get_most_recent_active_meeting_id()
- .await
- .map_err(|e| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": e.to_string()})),
- )
- })?;
- active_id.ok_or_else(|| {
- (
+ let requested_id = body.id;
+ let status = resolve_meeting_status(&state).await?;
+ let id = match requested_id {
+ Some(id) => {
+ if status.stoppable_meeting_id == Some(id) || status.active_meeting_id == Some(id) {
+ id
+ } else {
+ return Err((
StatusCode::BAD_REQUEST,
- JsonResponse(json!({"error": "no active meeting"})),
- )
- })?
+ JsonResponse(json!({"error": "requested meeting is not the active meeting"})),
+ ));
+ }
}
+ None => status.stoppable_meeting_id.ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ JsonResponse(json!({"error": "no active meeting"})),
+ )
+ })?,
};
let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
@@ -315,7 +403,13 @@ pub(crate) async fn stop_meeting_handler(
{
let mut lock = state.manual_meeting.write().await;
- *lock = None;
+ if *lock == Some(id) {
+ *lock = None;
+ }
+ }
+
+ if let Ok(status) = resolve_meeting_status(&state).await {
+ emit_meeting_status_changed(&status);
}
// Emit event so triggered pipes can react
@@ -332,5 +426,17 @@ pub(crate) async fn stop_meeting_handler(
)
})?;
+ // Signal detector to stop tracking this meeting immediately (skip grace period)
+ if let Err(e) = screenpipe_events::send_event(
+ "detector_stop_tracking",
+ serde_json::json!({ "meeting_id": id, "app": &meeting.meeting_app }),
+ ) {
+ tracing::warn!(
+ "failed to emit detector_stop_tracking event for meeting {}: {}",
+ id,
+ e
+ );
+ }
+
Ok(JsonResponse(meeting))
}
diff --git a/crates/screenpipe-engine/src/routes/websocket.rs b/crates/screenpipe-engine/src/routes/websocket.rs
index ca718642c..64a67fb1c 100644
--- a/crates/screenpipe-engine/src/routes/websocket.rs
+++ b/crates/screenpipe-engine/src/routes/websocket.rs
@@ -29,6 +29,7 @@ use tracing::{debug, error};
use crate::server::AppState;
use super::health::health_check;
+use super::meetings::{resolve_meeting_status_from, MeetingStatusResponse};
/// Maximum number of concurrent WebSocket connections allowed.
/// This prevents file descriptor exhaustion from too many open connections.
@@ -218,6 +219,56 @@ pub(crate) async fn ws_metrics_handler(
}
}
+pub(crate) async fn ws_meeting_status_handler(
+ ws: WebSocketUpgrade,
+ State(state): State<Arc<AppState>>,
+) -> Response {
+ match try_acquire_ws_connection(&state.ws_connection_count) {
+ Some(guard) => ws.on_upgrade(move |socket| handle_meeting_status_socket(socket, state, guard)),
+ None => Response::builder()
+ .status(StatusCode::SERVICE_UNAVAILABLE)
+ .body(Body::from("Too many WebSocket connections"))
+ .unwrap(),
+ }
+}
+
+async fn handle_meeting_status_socket(
+ mut socket: WebSocket,
+ state: Arc<AppState>,
+ _guard: WsConnectionGuard,
+) {
+ if let Ok(status) = resolve_meeting_status_from(state.db.as_ref(), state.manual_meeting.as_ref()).await {
+ if let Ok(json) = serde_json::to_string(&status) {
+ if socket.send(Message::Text(json)).await.is_err() {
+ return;
+ }
+ }
+ }
+
+ let mut stream = screenpipe_events::subscribe_to_event::<MeetingStatusResponse>("meeting_status_changed");
+ loop {
+ tokio::select! {
+ event = stream.next() => {
+ if let Some(event) = event {
+ let json = serde_json::to_string(&event.data).unwrap_or_default();
+ if let Err(e) = socket.send(Message::Text(json)).await {
+ error!("Failed to send meeting status: {}", e);
+ break;
+ }
+ }
+ }
+ _ = tokio::time::sleep(Duration::from_secs(15)) => {
+ let _ = socket.send(Message::Ping(vec![])).await;
+ }
+ result = socket.recv() => {
+ if result.is_none() {
+ break;
+ }
+ }
+ }
+ }
+}
+
async fn handle_metrics_socket(
mut socket: WebSocket,
state: Arc<AppState>,
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index bc0a6e163..c880f66d0 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -54,7 +54,7 @@ use crate::{
search_speakers_handler, undo_speaker_reassign_handler, update_speaker_handler,
},
streaming::{handle_video_export_post, handle_video_export_ws, stream_frames_handler},
- websocket::{ws_events_handler, ws_health_handler, ws_metrics_handler},
+ websocket::{ws_events_handler, ws_health_handler, ws_meeting_status_handler, ws_metrics_handler},
},
sync_api::{self, SyncState},
video_cache::FrameCache,
@@ -812,6 +812,7 @@ impl SCServer {
.route("/stream/frames", get(stream_frames_handler))
.route("/ws/events", get(ws_events_handler))
.route("/ws/health", get(ws_health_handler))
+ .route("/ws/meeting-status", get(ws_meeting_status_handler))
.route("/ws/metrics", get(ws_metrics_handler))
// Browser extension bridge — DEPRECATED top-level paths.
// Canonical paths now live under /connections/browser/* (see connections_api.rs).