The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(observability): scope the Event Log and core notifications to a workspace\n\nOne process serves every workspace it has opened — `mcp::host`'s `HOSTS`\nis insert-only, so a switch leaves the previous one running and\nsupervised — but the `/events/domain` envelope carried no workspace at\nall. A row left over from a workspace the user had switched away from\nwas indistinguishable from one belonging to the workspace they were in,\nand the log said "MCP server parked" with no way to tell whose.\n\nEach row now carries the opaque handle of the workspace it belongs to\nplus the handle that was active when it was emitted, and the panel keeps\nthe newest of the latter as current. That is what makes a switch visible\non a connection that stays open: the next row after one says a different\nworkspace is current, and the previous workspace's rows leave the\ndefault view. The panel defaults to the active workspace and switches to\nall, and since the NDJSON download exports exactly the rendered rows, it\nis scoped by the same control. Handles throughout, never `workspace_dir`\n— the log renders in a settings panel and downloads to a file, and the\npath is under the user's home directory.\n\nCore notifications carry the handle too. The publish-time gate already\nrefuses to broadcast from a switched-away workspace, but it resolves the\nactive workspace and then sends: two steps, so a switch in between can\nstill let one through, and `core_notification` reaches every connected\nclient with no per-client routing behind it. Carrying the identity turns\na boolean taken at an instant into something the receiver re-checks\nwhenever it renders. The client learns which workspace is current from\n`workspace_changed`, emitted on every switch and to each client as it\nconnects, so a client that joins between switches is not left blind.\n\nClient-side routing fails open where the core's gate fails closed, and\ndeliberately: the core decides whether to send, this is a second check on\nsomething already sent past that gate. A payload with no handle is not\nworkspace-bound and applies wherever it lands, and an unknown active\nworkspace must not drop everything for the rest of the session.\n\n`workspace_of` now delegates to `DomainEvent::workspace_dir` rather than\nkeeping its own MCP-only list.\n\nCloses #5966\n
Shanu161ef3cd59ee
diff --git a/app/src/components/settings/panels/EventLogPanel.tsx b/app/src/components/settings/panels/EventLogPanel.tsxindex 08b135aec9..2b941ac015 100644--- a/app/src/components/settings/panels/EventLogPanel.tsx+++ b/app/src/components/settings/panels/EventLogPanel.tsx@@ -19,8 +19,29 @@ interface EventEntry {*/detail: string;timestamp: string;+ /**+ * Opaque handle for the workspace this event belongs to, or `null` when the+ * event is not workspace-bound (#5966).+ *+ * A handle, never a path: the core hashes `workspace_dir` before it reaches+ * this envelope, because the log renders in a settings panel and downloads+ * as NDJSON, and the path is under the user's home directory.+ */+ workspace: string | null;}+/**+ * Which rows the log shows (#5966).+ *+ * One core process serves more than one workspace over its life — a switch+ * leaves the previous one open — so this single stream mixes them, and until+ * now a row from a workspace the reader had left was indistinguishable from+ * one belonging to the workspace they were in. `active` is the default+ * because someone watching a live log is almost always asking about the+ * workspace they are in; `all` keeps the process-wide view for debugging.+ */+type WorkspaceScope = 'active' | 'all';+const DOMAIN_BADGE_KEYS: Record<string, string> = {tool: 'settings.developerMenu.eventLog.badge.tool',agent: 'settings.developerMenu.eventLog.badge.agent',@@ -69,6 +90,19 @@ const EventLogPanel = () => {const [isLive, setIsLive] = useState(false);const [filterType, setFilterType] = useState<string>('');const [filterText, setFilterText] = useState('');+ const [scope, setScope] = useState<WorkspaceScope>('active');+ /**+ * Handle of the workspace the core is serving right now, or `null` while+ * that is unknown — the core could not resolve it, or has not resolved it+ * since a workspace marker was rewritten.+ *+ * Tracked as state rather than a ref because the row filter reads it: a+ * switch has to re-render the list so the previous workspace's rows fall+ * out of the default view. It is only ever *set* when the value actually+ * changes, so an idle stream does not re-render on every event.+ */+ const [activeWorkspace, setActiveWorkspace] = useState<string | null>(null);+ const activeWorkspaceRef = useRef<string | null>(null);const [autoScroll, setAutoScroll] = useState(true);const containerRef = useRef<HTMLDivElement>(null);const idRef = useRef(0);@@ -80,6 +114,23 @@ const EventLogPanel = () => {const connectRef = useRef<(() => Promise<void>) | null>(null);+ /**+ * Record which workspace the core says is current, if it said anything.+ *+ * The ref guard matters: this runs for every streamed row, and calling+ * `setActiveWorkspace` unconditionally would re-render the whole list on+ * each one. A missing or non-string value is ignored rather than treated as+ * `null` — the core omits the field when it could not resolve the+ * workspace, and forgetting a handle we already know would silently widen+ * the default view back to every workspace.+ */+ const rememberActiveWorkspace = (value: unknown) => {+ if (typeof value !== 'string' || !value) return;+ if (activeWorkspaceRef.current === value) return;+ activeWorkspaceRef.current = value;+ setActiveWorkspace(value);+ };+const connect = async () => {if (unmountedRef.current) return;try {@@ -135,8 +186,18 @@ const EventLogPanel = () => {if (data.new_entries === 'top' || data.new_entries === 'bottom') {newEntriesRef.current = data.new_entries;}+ // The connect-time answer, so a client that joins between+ // switches can scope the log immediately instead of waiting+ // for an event to tell it which workspace is current.+ rememberActiveWorkspace(data.active_workspace);continue;}+ // Every row also carries the workspace that was active when it+ // was emitted. That is what makes a *switch* visible on a+ // connection that stays open: the next row after one says a+ // different workspace is current, and the previous workspace's+ // rows drop out of the default view.+ rememberActiveWorkspace(data.active_workspace);const entry: EventEntry = {id: ++idRef.current,domain: data.domain || 'unknown',@@ -144,6 +205,7 @@ const EventLogPanel = () => {agent: data.agent || '',detail: data.detail || '',timestamp: data.timestamp || '',+ workspace: typeof data.workspace === 'string' ? data.workspace : null,};setEntries(prev => {const next = newEntriesRef.current === 'top' ? [entry, ...prev] : [...prev, entry];@@ -205,6 +267,18 @@ const EventLogPanel = () => {};const filteredEntries = entries.filter(e => {+ // Workspace scope first — it is the one filter that changes what the log+ // *means* rather than narrowing what it shows, and it also scopes the+ // NDJSON download, which exports exactly these rows.+ //+ // Two rows always survive it: one with no workspace of its own (most+ // events are process-wide and belong wherever they land), and every row+ // while `activeWorkspace` is still unknown — with nothing to compare+ // against, hiding rows would empty the panel and give the reader no way+ // to tell that from a quiet process.+ if (scope === 'active' && activeWorkspace && e.workspace && e.workspace !== activeWorkspace) {+ return false;+ }if (filterType && e.domain !== filterType) return false;if (filterText) {const q = filterText.toLowerCase();@@ -236,6 +310,16 @@ const EventLogPanel = () => {<SettingsPanel testId="event-log-panel" description={t('settings.developerMenu.eventLog.desc')}>{/* Status bar */}<div className="flex flex-wrap items-center gap-2">+ <SettingsSelect+ value={scope}+ onChange={e => setScope(e.target.value === 'all' ? 'all' : 'active')}+ aria-label={t('settings.developerMenu.eventLog.workspaceScope')}+ inputSize="sm">+ <option value="active">+ {t('settings.developerMenu.eventLog.workspaceScopeActive')}+ </option>+ <option value="all">{t('settings.developerMenu.eventLog.workspaceScopeAll')}</option>+ </SettingsSelect><SettingsSelectvalue={filterType}onChange={e => setFilterType(e.target.value)}diff --git a/app/src/components/settings/panels/__tests__/EventLogPanel.test.tsx b/app/src/components/settings/panels/__tests__/EventLogPanel.test.tsxindex 83b12e05dc..1468befe9e 100644--- a/app/src/components/settings/panels/__tests__/EventLogPanel.test.tsx+++ b/app/src/components/settings/panels/__tests__/EventLogPanel.test.tsx@@ -125,13 +125,18 @@ describe('EventLogPanel', () => {{ domain: 'tool', event: 'ToolA' },{ domain: 'agent', event: 'AgentB' },]);- const { container } = renderWithProviders(<EventLogPanel />);+ renderWithProviders(<EventLogPanel />);await waitFor(() => {expect(screen.getByText('ToolA')).toBeTruthy();});- const select = container.querySelector('select')!;+ // By label, not by position: the toolbar has more than one select since+ // the workspace-scope control landed (#5966), and `querySelector('select')`+ // silently picks whichever comes first in the DOM.+ const select = screen.getByLabelText(+ 'settings.developerMenu.eventLog.allTypes'+ ) as HTMLSelectElement;fireEvent.change(select, { target: { value: 'tool' } });await waitFor(() => {diff --git a/app/src/components/settings/panels/__tests__/EventLogPanel.workspaceScope.test.tsx b/app/src/components/settings/panels/__tests__/EventLogPanel.workspaceScope.test.tsxnew file mode 100644index 0000000000..55e0ddaaa8--- /dev/null+++ b/app/src/components/settings/panels/__tests__/EventLogPanel.workspaceScope.test.tsx@@ -0,0 +1,213 @@+/**+ * EventLogPanel — the workspace dimension (issue #5966).+ *+ * One core process serves more than one workspace over its life: a switch+ * leaves the previous workspace's subsystems running, and this single stream+ * carries both. Before the envelope named a workspace, a row left over from a+ * workspace the reader had switched away from was indistinguishable from one+ * belonging to the workspace they were in — the log said "MCP server parked"+ * and gave no way to tell whose.+ *+ * Everything here fails silently if it regresses. A dropped scope filter shows+ * another workspace's rows as current; an over-eager one hides the rows the+ * reader came for; and losing track of the active workspace after a switch+ * makes the default view keep presenting stale rows as live. Nothing throws in+ * any of those cases, and the panel keeps looking healthy.+ */+import { fireEvent, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { renderWithProviders } from '../../../../test/test-utils';+import EventLogPanel from '../EventLogPanel';++vi.mock('../../../../services/coreRpcClient', () => ({+ getCoreHttpBaseUrl: vi.fn().mockResolvedValue('http://localhost:9999'),+ getCoreRpcToken: vi.fn().mockResolvedValue('test-token'),+}));++vi.mock('../../hooks/useSettingsNavigation', () => ({+ useSettingsNavigation: () => ({ navigateBack: vi.fn(), breadcrumbs: [] }),+}));++vi.mock('../../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));++const WS_A = 'ws_1111111111111111';+const WS_B = 'ws_2222222222222222';++function mockFetchRaw(body: string) {+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(encoder.encode(body));+ controller.close();+ },+ });+ global.fetch = vi.fn().mockResolvedValue({ ok: true, body: stream });+}++/**+ * One row as the core emits it: what workspace it belongs to, and what the+ * core considered active at the moment it was emitted.+ */+const row = (opts: {+ event: string;+ workspace?: string | null;+ active?: string | null;+ domain?: string;+}) =>+ `data:${JSON.stringify({+ domain: opts.domain ?? 'mcp_client',+ event: opts.event,+ agent: '',+ detail: null,+ workspace: opts.workspace ?? null,+ active_workspace: opts.active ?? null,+ timestamp: '12:00:00',+ })}\n\n`;++const configFrame = (payload: Record<string, unknown>) =>+ `event:config\ndata:${JSON.stringify(payload)}\n\n`;++/** Switch the scope select to "all workspaces". */+function selectAllWorkspaces() {+ fireEvent.change(+ screen.getByLabelText('settings.developerMenu.eventLog.workspaceScope') as HTMLSelectElement,+ { target: { value: 'all' } }+ );+}++describe('EventLogPanel workspace scope', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('defaults to the active workspace and hides another workspace’s rows', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top', active_workspace: WS_A }) ++ row({ event: 'MineParked', workspace: WS_A, active: WS_A }) ++ row({ event: 'TheirsParked', workspace: WS_B, active: WS_A })+ );+ renderWithProviders(<EventLogPanel />);++ await waitFor(() => expect(screen.getByText('MineParked')).toBeTruthy());+ expect(screen.queryByText('TheirsParked')).toBeNull();+ });++ it('shows both workspaces when the scope is switched to all', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top', active_workspace: WS_A }) ++ row({ event: 'MineParked', workspace: WS_A, active: WS_A }) ++ row({ event: 'TheirsParked', workspace: WS_B, active: WS_A })+ );+ renderWithProviders(<EventLogPanel />);++ await waitFor(() => expect(screen.getByText('MineParked')).toBeTruthy());+ selectAllWorkspaces();++ await waitFor(() => expect(screen.getByText('TheirsParked')).toBeTruthy());+ expect(screen.getByText('MineParked')).toBeTruthy();+ });++ /**+ * The regression the issue is actually about. The stream stays open across a+ * workspace switch, so rows that were current a moment ago must stop being+ * current — and the ones that were being hidden must start showing. A panel+ * that pinned the active workspace at connect time passes every other test+ * here and fails this one.+ */+ it('re-scopes across a workspace switch without reconnecting', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top', active_workspace: WS_A }) ++ row({ event: 'BeforeSwitch', workspace: WS_A, active: WS_A }) ++ row({ event: 'AfterSwitch', workspace: WS_B, active: WS_B })+ );+ renderWithProviders(<EventLogPanel />);++ // Once the switch is observed, the workspace the user left drops out and+ // the one they moved to appears.+ await waitFor(() => expect(screen.getByText('AfterSwitch')).toBeTruthy());+ expect(screen.queryByText('BeforeSwitch')).toBeNull();++ // Nothing was discarded — 'all' still has both.+ selectAllWorkspaces();+ await waitFor(() => expect(screen.getByText('BeforeSwitch')).toBeTruthy());+ expect(screen.getByText('AfterSwitch')).toBeTruthy();+ });++ /**+ * Most events are process-wide. Scoping must narrow the log to one+ * workspace, not to the handful of families that happen to name one.+ */+ it('keeps rows that are not bound to any workspace', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top', active_workspace: WS_A }) ++ row({ event: 'ProcessWide', domain: 'tool', workspace: null, active: WS_A }) ++ row({ event: 'TheirsParked', workspace: WS_B, active: WS_A })+ );+ renderWithProviders(<EventLogPanel />);++ await waitFor(() => expect(screen.getByText('ProcessWide')).toBeTruthy());+ expect(screen.queryByText('TheirsParked')).toBeNull();+ });++ /**+ * With no active workspace to compare against — the core could not resolve+ * it — hiding rows would empty the panel and give the reader no way to tell+ * that from a quiet process. Show everything instead.+ */+ it('shows every row while the active workspace is unknown', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top' }) ++ row({ event: 'FromA', workspace: WS_A, active: null }) ++ row({ event: 'FromB', workspace: WS_B, active: null })+ );+ renderWithProviders(<EventLogPanel />);++ await waitFor(() => expect(screen.getByText('FromA')).toBeTruthy());+ expect(screen.getByText('FromB')).toBeTruthy();+ });++ /**+ * The download is the surface the privacy half of #5966 is about: it leaves+ * the app. It must carry the handle and never the path, and it must export+ * what the reader is looking at rather than the unscoped buffer.+ */+ it('exports only the scoped rows, carrying handles and no filesystem path', async () => {+ mockFetchRaw(+ configFrame({ max_entries: 200, new_entries: 'top', active_workspace: WS_A }) ++ row({ event: 'MineParked', workspace: WS_A, active: WS_A }) ++ row({ event: 'TheirsParked', workspace: WS_B, active: WS_A })+ );++ const blobs: string[] = [];+ const originalBlob = global.Blob;+ class CapturingBlob extends originalBlob {+ constructor(parts: BlobPart[], options?: BlobPropertyBag) {+ blobs.push(parts.map(String).join(''));+ super(parts, options);+ }+ }+ vi.stubGlobal('Blob', CapturingBlob);+ const createObjectURL = vi.fn().mockReturnValue('blob:mock');+ vi.stubGlobal('URL', { ...URL, createObjectURL, revokeObjectURL: vi.fn() });++ try {+ renderWithProviders(<EventLogPanel />);+ await waitFor(() => expect(screen.getByText('MineParked')).toBeTruthy());++ fireEvent.click(screen.getByText('settings.developerMenu.eventLog.download'));++ expect(blobs).toHaveLength(1);+ const exported = blobs[0];+ expect(exported).toContain('MineParked');+ expect(exported).not.toContain('TheirsParked');+ expect(exported).toContain(WS_A);+ // The whole point of the handle: no home directory reaches the file.+ expect(exported).not.toContain('/Users/');+ expect(exported).not.toContain('/home/');+ expect(exported).not.toContain('.openhuman');+ } finally {+ vi.unstubAllGlobals();+ }+ });+});diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex bdb533c128..4fd15db18a 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -4810,6 +4810,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'الحدث','settings.developerMenu.eventLog.desc':'تيار ملون مباشر لجميع العناصر والأدوات والأحداث النظامية',+ 'settings.developerMenu.eventLog.workspaceScope': 'نطاق مساحة العمل',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'مساحة العمل الحالية',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'كل مساحات العمل','settings.developerMenu.eventLog.allTypes': 'جميع الأنواع','settings.developerMenu.eventLog.filterAgent': '(فيلتر)','settings.developerMenu.eventLog.download': 'تحميل',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 61c7e2a9c2..5acd757da6 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -4921,6 +4921,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'ইভেন্টের লগ','settings.developerMenu.eventLog.desc':'লাইভ রঙ-কোডকৃত সব এজেন্ট, টুল, এবং সিস্টেম ইভেন্টের জন্য',+ 'settings.developerMenu.eventLog.workspaceScope': 'ওয়ার্কস্পেসের পরিসর',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'এই ওয়ার্কস্পেস',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'সব ওয়ার্কস্পেস','settings.developerMenu.eventLog.allTypes': 'সর্ব প্রকার','settings.developerMenu.eventLog.filterAgent': 'ফিল্টার...','settings.developerMenu.eventLog.download': 'ডাউনলোড করা হয়েছে',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 86663851b4..9438086a0f 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -5055,6 +5055,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Ereignisprotokoll','settings.developerMenu.eventLog.desc':'Farbcodierter Live-Stream aller Agenten-, Tool- und Systemereignisse',+ 'settings.developerMenu.eventLog.workspaceScope': 'Arbeitsbereich',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Dieser Arbeitsbereich',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Alle Arbeitsbereiche','settings.developerMenu.eventLog.allTypes': 'Alle Typen','settings.developerMenu.eventLog.filterAgent': 'Filter …','settings.developerMenu.eventLog.download': 'Herunterladen',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex 56292139ea..d1c401de1e 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -5624,6 +5624,9 @@ const en: TranslationMap = {'settings.developerMenu.eventLog.title': 'Event Log','settings.developerMenu.eventLog.desc':'Live colour-coded stream of all agent, tool, and system events',+ 'settings.developerMenu.eventLog.workspaceScope': 'Workspace scope',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'This workspace',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'All workspaces','settings.developerMenu.eventLog.allTypes': 'All types','settings.developerMenu.eventLog.filterAgent': 'Filter...','settings.developerMenu.eventLog.download': 'Download',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 45a891dee6..3e49414e13 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -5011,6 +5011,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Registro de eventos','settings.developerMenu.eventLog.desc':'Transmisión en vivo codificada por colores de todos los eventos de agentes, herramientas y sistemas',+ 'settings.developerMenu.eventLog.workspaceScope': 'Ámbito del espacio de trabajo',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Este espacio de trabajo',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Todos los espacios de trabajo','settings.developerMenu.eventLog.allTypes': 'Todos los tipos','settings.developerMenu.eventLog.filterAgent': 'Filtrar...','settings.developerMenu.eventLog.download': 'Descargar',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex dc08a4b6e2..3a9ff89c9f 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -5037,6 +5037,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Journal des événements','settings.developerMenu.eventLog.desc':'Flux en direct codé par couleur de tous les événements des agents, outils et systèmes',+ 'settings.developerMenu.eventLog.workspaceScope': 'Portée de l’espace de travail',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Cet espace de travail',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Tous les espaces de travail','settings.developerMenu.eventLog.allTypes': 'Tous les types','settings.developerMenu.eventLog.filterAgent': 'Filtrer...','settings.developerMenu.eventLog.download': 'Télécharger',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 5340fd82af..3db5cf87b9 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -4924,6 +4924,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'घटना लॉग','settings.developerMenu.eventLog.desc':'सभी एजेंट, टूल और सिस्टम इवेंट्स की लाइव कलर-कोडेड स्ट्रीम',+ 'settings.developerMenu.eventLog.workspaceScope': 'वर्कस्पेस का दायरा',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'यह वर्कस्पेस',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'सभी वर्कस्पेस','settings.developerMenu.eventLog.allTypes': 'सभी प्रकार','settings.developerMenu.eventLog.filterAgent': 'फ़िल्टर...','settings.developerMenu.eventLog.download': 'डाउनलोड',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 1f732130f0..4a76827d54 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -4950,6 +4950,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Log Peristiwa','settings.developerMenu.eventLog.desc':'Siaran warna langsung dari semua agen, alat, dan peristiwa sistem',+ 'settings.developerMenu.eventLog.workspaceScope': 'Cakupan ruang kerja',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Ruang kerja ini',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Semua ruang kerja','settings.developerMenu.eventLog.allTypes': 'Semua jenis','settings.developerMenu.eventLog.filterAgent': 'Filter...','settings.developerMenu.eventLog.download': 'Unduh',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 7de497defc..1ccba3d6ed 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -5001,6 +5001,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Registro eventi','settings.developerMenu.eventLog.desc':'Flusso in diretta codificato a colori di tutti gli eventi di agenti, strumenti e sistemi',+ 'settings.developerMenu.eventLog.workspaceScope': 'Ambito dello spazio di lavoro',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Questo spazio di lavoro',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Tutti gli spazi di lavoro','settings.developerMenu.eventLog.allTypes': 'Tutti i tipi','settings.developerMenu.eventLog.filterAgent': 'Filtro...','settings.developerMenu.eventLog.download': 'Scarica',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex bc924d51ba..a021a8eaf3 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -4867,6 +4867,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': '이벤트 로그','settings.developerMenu.eventLog.desc':'모든 에이전트, 도구, 시스템 이벤트를 색상으로 구분해 실시간으로 표시합니다.',+ 'settings.developerMenu.eventLog.workspaceScope': '워크스페이스 범위',+ 'settings.developerMenu.eventLog.workspaceScopeActive': '현재 워크스페이스',+ 'settings.developerMenu.eventLog.workspaceScopeAll': '모든 워크스페이스','settings.developerMenu.eventLog.allTypes': '모든 유형','settings.developerMenu.eventLog.filterAgent': '필터...','settings.developerMenu.eventLog.download': '다운로드',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 73a8c75028..4b9a2af6f7 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -5001,6 +5001,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Dziennik zdarzeń','settings.developerMenu.eventLog.desc':'Kolorowany strumień na żywo wszystkich zdarzeń agenta, narzędzi i systemu',+ 'settings.developerMenu.eventLog.workspaceScope': 'Zakres przestrzeni roboczej',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Ta przestrzeń robocza',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Wszystkie przestrzenie robocze','settings.developerMenu.eventLog.allTypes': 'Wszystkie typy','settings.developerMenu.eventLog.filterAgent': 'Filtruj...','settings.developerMenu.eventLog.download': 'Pobierz',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 4a19b91d6b..f24f22078a 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -4995,6 +4995,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Registro de Eventos','settings.developerMenu.eventLog.desc':'Transmissão ao vivo com cores codificadas de todos os eventos de agentes, ferramentas e sistemas',+ 'settings.developerMenu.eventLog.workspaceScope': 'Âmbito do espaço de trabalho',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Este espaço de trabalho',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Todos os espaços de trabalho','settings.developerMenu.eventLog.allTypes': 'Todos os tipos','settings.developerMenu.eventLog.filterAgent': 'Filtrar...','settings.developerMenu.eventLog.download': 'Baixar',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex a1b9881191..120a2a40ff 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -4972,6 +4972,9 @@ const messages: TranslationMap = {'settings.developerMenu.eventLog.title': 'Журнал событий','settings.developerMenu.eventLog.desc':'Живой поток с цветовой кодировкой обо всех событиях агента, инструмента и системы.',+ 'settings.developerMenu.eventLog.workspaceScope': 'Область рабочего пространства',+ 'settings.developerMenu.eventLog.workspaceScopeActive': 'Текущее рабочее пространство',+ 'settings.developerMenu.eventLog.workspaceScopeAll': 'Все рабочие пространства','settings.developerMenu.eventLog.allTypes': 'Все типы','settings.developerMenu.eventLog.filterAgent': 'Фильтр...','settings.developerMenu.eventLog.download': 'Скачать',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex dca8353188..f0112e3a53 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -4652,6 +4652,9 @@ const messages: TranslationMap = {'settings.developerMenu.webhooks.desc': '检查运行时 Webhook 注册和捕获的请求日志','settings.developerMenu.eventLog.title': '事件日志','settings.developerMenu.eventLog.desc': '实时显示所有智能体、工具和系统事件的彩色编码流',+ 'settings.developerMenu.eventLog.workspaceScope': '工作区范围',+ 'settings.developerMenu.eventLog.workspaceScopeActive': '当前工作区',+ 'settings.developerMenu.eventLog.workspaceScopeAll': '所有工作区','settings.developerMenu.eventLog.allTypes': '所有类型','settings.developerMenu.eventLog.filterAgent': '筛选...','settings.developerMenu.eventLog.download': '下载',diff --git a/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.ts b/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.tsnew file mode 100644index 0000000000..0c66ab5866--- /dev/null+++ b/app/src/lib/nativeNotifications/__tests__/workspaceRouting.test.ts@@ -0,0 +1,125 @@+/**+ * Core notifications are routed by workspace on the client (issue #5966).+ *+ * The core already refuses to broadcast a workspace-bound notification from a+ * workspace the user has switched away from. But it decides that by resolving+ * the active workspace and *then* sending — two steps, so a switch in between+ * still lets one through, and `core_notification` reaches every connected+ * client with no per-client routing behind it. The payload therefore carries+ * the workspace's opaque handle, and this module re-checks it at the moment+ * it renders.+ *+ * The failure this prevents is not cosmetic: the banner prints an MCP server's+ * qualified name and its transport error, so a leaked one shows another+ * account's server and its failure text inside the account the user is in.+ *+ * The two fail-open paths below are the ones most likely to be "tightened"+ * into a bug later, which is why each is pinned with its reason.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { store } from '../../../store';+import { setPreference } from '../../../store/notificationSlice';+import {+ __handleCoreNotificationForTests,+ __resetForTests,+ __setActiveWorkspaceForTests,+} from '../service';++vi.mock('../tauriBridge', () => ({ showNativeNotification: vi.fn() }));++vi.mock('../../../services/socketService', () => ({+ socketService: { on: vi.fn(), off: vi.fn() },+}));++const WS_A = 'ws_1111111111111111';+const WS_B = 'ws_2222222222222222';++function notify(overrides: { id: string; workspace?: string | null }) {+ __handleCoreNotificationForTests({+ id: overrides.id,+ category: 'system',+ title: 'MCP server parked',+ body: 'ac.inference.sh/mcp is not being retried.',+ timestamp_ms: 1,+ workspace: overrides.workspace,+ });+}++const items = () => store.getState().notifications.items;++describe('core notification workspace routing', () => {+ beforeEach(() => {+ __resetForTests();+ vi.clearAllMocks();+ store.dispatch({ type: 'notifications/clearAll' });+ store.dispatch(setPreference({ category: 'system', enabled: true }));+ });++ it('accepts a notification from the workspace the client is in', () => {+ __setActiveWorkspaceForTests(WS_A);+ notify({ id: 'mcp:mine', workspace: WS_A });+ expect(items()).toHaveLength(1);+ expect(items()[0].id).toBe('mcp:mine');+ });++ it('drops a notification from a workspace the user has switched away from', () => {+ __setActiveWorkspaceForTests(WS_A);+ notify({ id: 'mcp:theirs', workspace: WS_B });+ expect(items()).toHaveLength(0);+ });++ /**+ * Most notifications — cron, webhook, sub-agent, a rejected API key — are+ * not bound to a workspace and apply wherever they land. Treating a missing+ * handle as a mismatch would silence all of them.+ */+ it('accepts a notification that names no workspace', () => {+ __setActiveWorkspaceForTests(WS_A);+ notify({ id: 'cron:daily', workspace: null });+ expect(items()).toHaveLength(1);+ });++ /**+ * Rows persisted before the field existed deserialize without it, so this is+ * the same case as above reached by a different route: an upgrade must not+ * hide a user's stored notification history.+ */+ it('accepts a notification from before the field existed', () => {+ __setActiveWorkspaceForTests(WS_A);+ __handleCoreNotificationForTests({+ id: 'legacy:1',+ category: 'system',+ title: 'Webhook error',+ body: 'skill-x webhook returned HTTP 500',+ timestamp_ms: 1,+ });+ expect(items()).toHaveLength(1);+ });++ /**+ * Fails open, deliberately, and opposite to the core's fail-closed publish+ * gate. Here the notification has already been sent past that gate; dropping+ * it because the seed has not arrived yet would swallow every notification+ * for the rest of the session, with nothing on screen to say why.+ */+ it('accepts a workspace-bound notification while the active workspace is unknown', () => {+ __setActiveWorkspaceForTests(null);+ notify({ id: 'mcp:unknown-active', workspace: WS_B });+ expect(items()).toHaveLength(1);+ });++ it('follows a workspace switch', () => {+ __setActiveWorkspaceForTests(WS_A);+ notify({ id: 'mcp:a', workspace: WS_A });+ expect(items()).toHaveLength(1);++ __setActiveWorkspaceForTests(WS_B);+ notify({ id: 'mcp:a-again', workspace: WS_A });+ expect(items()).toHaveLength(1);++ notify({ id: 'mcp:b', workspace: WS_B });+ expect(items()).toHaveLength(2);+ expect(items().some(item => item.id === 'mcp:b')).toBe(true);+ });+});diff --git a/app/src/lib/nativeNotifications/service.ts b/app/src/lib/nativeNotifications/service.tsindex d9aa7c9d5b..b2b45cc5d8 100644--- a/app/src/lib/nativeNotifications/service.ts+++ b/app/src/lib/nativeNotifications/service.ts@@ -18,8 +18,20 @@ let started = false;let chatDoneListener: ((...args: unknown[]) => void) | null = null;let chatErrorListener: ((...args: unknown[]) => void) | null = null;let coreNotificationListener: ((...args: unknown[]) => void) | null = null;+let workspaceChangedListener: ((...args: unknown[]) => void) | null = null;let disconnectListener: ((...args: unknown[]) => void) | null = null;+/**+ * Opaque handle of the workspace the core is serving, or `null` while that is+ * unknown (issue #5966).+ *+ * Seeded by the core the moment this client connects and updated whenever the+ * active workspace changes, both over `workspace_changed`. A handle, never a+ * path — the core hashes `workspace_dir` before sending it, since the path is+ * under the user's home directory and this reaches every connected client.+ */+let activeWorkspace: string | null = null;+interface ChatDonePayload {thread_id?: string;request_id?: string;@@ -44,6 +56,40 @@ interface CoreNotificationPayload {// The Rust core serializes these camelCase, so the shape already matches// the Redux `NotificationAction` type — pass through verbatim.actions?: NotificationAction[];+ // Opaque handle of the workspace this notification belongs to, absent when+ // it is not workspace-bound (issue #5966). See `isForActiveWorkspace`.+ workspace?: string | null;+}++interface WorkspaceChangedPayload {+ workspace?: string | null;+}++/**+ * Whether a core notification belongs where this client is looking.+ *+ * The core already refuses to broadcast a notification from a workspace the+ * user has switched away from, but it decides that by resolving the active+ * workspace and then sending — two steps, so a switch in between can still+ * let one through. Re-checking here turns that publish-time boolean into an+ * identity the receiver can verify, which is what actually closes the window.+ *+ * Both unknowns pass rather than fail:+ *+ * - a payload with no `workspace` is not workspace-bound (cron, webhook,+ * sub-agent, rejected API key) and applies wherever it lands — as does one+ * persisted before the field existed;+ * - an unknown `activeWorkspace` means the seed has not arrived or the core+ * could not resolve it, and dropping everything in that state would+ * silently swallow every notification for the rest of the session.+ *+ * Failing open here is the opposite of the core's fail-closed gate, and+ * deliberately so: the core is the one deciding whether to *send*, this is a+ * second check on something already sent past that gate.+ */+function isForActiveWorkspace(payload: CoreNotificationPayload): boolean {+ if (!payload.workspace || !activeWorkspace) return true;+ return payload.workspace === activeWorkspace;}function windowIsFocused(): boolean {@@ -134,6 +180,15 @@ export function startNativeNotificationsService(): void {log('[socket] core_notification missing id/title dropped');return;}+ if (!isForActiveWorkspace(p)) {+ log(+ '[socket] core_notification id=%s dropped: workspace=%s active=%s',+ p.id,+ p.workspace,+ activeWorkspace+ );+ return;+ }const serverTs = p.timestamp_ms && p.timestamp_ms > 0 ? p.timestamp_ms : Date.now();dispatchAndMaybeBanner(p.category,@@ -148,6 +203,20 @@ export function startNativeNotificationsService(): void {);};+ // The core emits this once when this client connects and again on every+ // workspace switch, so `activeWorkspace` is current without polling and+ // without this module having to resolve anything itself (#5966).+ workspaceChangedListener = (...args: unknown[]) => {+ const p = (args[0] ?? {}) as WorkspaceChangedPayload;+ if (typeof p.workspace !== 'string' || !p.workspace) {+ log('[socket] workspace_changed without a handle ignored');+ return;+ }+ if (activeWorkspace === p.workspace) return;+ log('[socket] workspace_changed %s -> %s', activeWorkspace, p.workspace);+ activeWorkspace = p.workspace;+ };+disconnectListener = (...args: unknown[]) => {const reason = typeof args[0] === 'string' ? args[0] : 'unknown';log('[socket] disconnect reason=%s', reason);@@ -161,9 +230,12 @@ export function startNativeNotificationsService(): void {socketService.on('chat_done', chatDoneListener);socketService.on('chat_error', chatErrorListener);socketService.on('core_notification', coreNotificationListener);+ socketService.on('workspace_changed', workspaceChangedListener);socketService.on('disconnect', disconnectListener);- log('started — subscribed to chat_done, chat_error, core_notification, disconnect');+ log(+ 'started — subscribed to chat_done, chat_error, core_notification, workspace_changed, disconnect'+ );}export function stopNativeNotificationsService(): void {@@ -181,6 +253,10 @@ export function stopNativeNotificationsService(): void {socketService.off('core_notification', coreNotificationListener);coreNotificationListener = null;}+ if (workspaceChangedListener) {+ socketService.off('workspace_changed', workspaceChangedListener);+ workspaceChangedListener = null;+ }if (disconnectListener) {socketService.off('disconnect', disconnectListener);disconnectListener = null;@@ -203,6 +279,7 @@ export function __handleChatDoneForTests(payload: ChatDonePayload): void {/** Exposed for tests — dispatch as if a core_notification arrived. */export function __handleCoreNotificationForTests(payload: CoreNotificationPayload): void {if (!payload.id || !payload.title) return;+ if (!isForActiveWorkspace(payload)) return;const serverTs =payload.timestamp_ms && payload.timestamp_ms > 0 ? payload.timestamp_ms : Date.now();dispatchAndMaybeBanner(@@ -218,11 +295,21 @@ export function __handleCoreNotificationForTests(payload: CoreNotificationPayloa);}+/**+ * Exposed for tests — set the workspace this client believes is active, as if+ * a `workspace_changed` had arrived.+ */+export function __setActiveWorkspaceForTests(workspace: string | null): void {+ activeWorkspace = workspace;+}+/** Exposed for tests — resets module singletons between runs. */export function __resetForTests(): void {started = false;chatDoneListener = null;chatErrorListener = null;coreNotificationListener = null;+ workspaceChangedListener = null;disconnectListener = null;+ activeWorkspace = null;}diff --git a/src/core/jsonrpc.rs b/src/core/jsonrpc.rsindex e7c940a299..cc08aeeede 100644--- a/src/core/jsonrpc.rs+++ b/src/core/jsonrpc.rs@@ -1593,11 +1593,29 @@ async fn domain_events_handler(headers: axum::http::HeaderMap) -> Response {log::debug!("[events/domain] client connected, streaming domain events");+ // The active workspace, resolved once here so a client that connects+ // mid-life starts out knowing which rows are its own rather than+ // waiting for the next event to tell it (#5966). This is the one place+ // in this handler that can afford the authoritative read — it happens+ // per connection, not per event — and it refills the cache the row+ // stamping below relies on.+ let active_workspace = crate::openhuman::config::active_workspace_dir()+ .await+ .map(|dir| crate::openhuman::config::workspace_handle(&dir))+ .map_err(|error| {+ log::warn!(+ "[events/domain] could not resolve the active workspace ({error}); \+ the client will scope the log once an event says which workspace is active"+ );+ })+ .ok();+// Send config as first SSE event so frontend can apply settings.let config_event = Event::default().event("config").data(serde_json::to_string(&json!({"max_entries": es_cfg.max_entries,"new_entries": es_cfg.new_entries,+ "active_workspace": active_workspace,})).unwrap_or_default(),);@@ -1624,11 +1642,34 @@ async fn domain_events_handler(headers: axum::http::HeaderMap) -> Response {// discarded, so they opt into one already-redacted line (#5931). It is// `null` for every other variant, which renders as no change.let detail = event.log_detail();+ // Which workspace this row belongs to, and which one is current+ // (#5966). One process serves more than one workspace over its life,+ // so without these two a row left over from a workspace the user has+ // switched away from is indistinguishable from one belonging to the+ // workspace they are in.+ //+ // Both are *handles*, never `workspace_dir` itself: this envelope+ // feeds a settings panel and its NDJSON download, and the path is+ // under the user's home directory.+ //+ // `active` is read from the cache rather than resolved. This closure+ // is synchronous — `tokio_stream`'s `filter_map` — so it could not+ // await a resolve, and it runs for every domain event the process+ // publishes, so it should not want to. `None` means "not resolved+ // since the last workspace marker write", which the client treats as+ // unknown rather than as a mismatch.+ let workspace = event+ .workspace_dir()+ .map(crate::openhuman::config::workspace_handle);+ let active = crate::openhuman::config::active_workspace_dir_cached()+ .map(|dir| crate::openhuman::config::workspace_handle(&dir));let data = json!({"domain": domain,"event": event_name,"agent": agent,"detail": detail,+ "workspace": workspace,+ "active_workspace": active,"timestamp": chrono::Utc::now().format("%H:%M:%S").to_string(),});let data_str = serde_json::to_string(&data).ok()?;diff --git a/src/core/socketio.rs b/src/core/socketio.rsindex 7014b53df1..29c2128ef9 100644--- a/src/core/socketio.rs+++ b/src/core/socketio.rs@@ -499,6 +499,38 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {log::debug!("[socketio] emit event=ready to_client={}", socket.id);let _ = socket.emit("ready", &ready_payload);+ // Seed this client with the workspace that is current (#5966).+ // The `workspace_changed` bridge in `spawn_web_channel_bridge`+ // only fires on a switch, so a client that connects between+ // switches — the common case, since the app connects at launch —+ // would otherwise have no idea which workspace is active and+ // could not scope anything.+ //+ // Spawned because this handler is synchronous and the resolve is+ // not. Emitting to `socket` rather than broadcasting keeps a+ // late-joining client from re-announcing a workspace every other+ // client already knows about.+ {+ let socket = socket.clone();+ let client_id = client_id.clone();+ tokio::spawn(async move {+ match crate::openhuman::config::active_workspace_dir().await {+ Ok(dir) => {+ let handle = crate::openhuman::config::workspace_handle(&dir);+ log::debug!(+ "[socketio] emit event=workspace_changed to_client={client_id} workspace={handle}"+ );+ let payload = json!({ "workspace": handle });+ let _ = socket.emit("workspace_changed", &payload);+ let _ = socket.emit("workspace:changed", &payload);+ }+ Err(error) => log::warn!(+ "[socketio] could not resolve the active workspace to seed client={client_id}: {error}"+ ),+ }+ });+ }+// Handler for JSON-RPC over WebSocket.socket.on("rpc:request",@@ -686,6 +718,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let io_memory_sync = io.clone();let io_channel_status = io.clone();let io_companion = io.clone();+ let io_workspace = io.clone();// 2. Dictation hotkey events → broadcast to all connected clients.tokio::spawn(async move {@@ -846,6 +879,58 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {log::debug!("[socketio] auth session_expired bridge stopped");});+ // 6a. ActiveWorkspaceChanged → broadcast `workspace_changed` carrying the+ // new workspace's opaque handle (#5966).+ //+ // `core_notification` is emitted to every connected client with no+ // per-client routing, and the publish-time gate that decides whether a+ // workspace-bound notification may be broadcast resolves the active+ // workspace and then sends — two steps, not one. A switch in between+ // still lets one through. Telling clients the handle of the workspace+ // that is current lets the receiver re-check on render instead of+ // trusting a boolean taken at an instant.+ //+ // The handle, never `workspace_dir`: this reaches every connected+ // client and the path is under the user's home directory.+ tokio::spawn(async move {+ let bus = {+ const RETRY_INTERVAL_MS: u64 = 250;+ const MAX_WAIT_SECS: u64 = 30;+ let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;+ let mut attempts: u64 = 0;+ loop {+ if let Some(bus) = crate::core::bus::BUS.get() {+ break bus;+ }+ attempts += 1;+ if attempts > max_attempts {+ log::warn!(+ "[socketio] event_bus not initialised after {}s — workspace bridge giving up",+ MAX_WAIT_SECS+ );+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(RETRY_INTERVAL_MS)).await;+ }+ };+ let mut rx = bus.receiver();+ loop {+ let Some(event) = rx.recv().await else {+ break;+ };+ if let crate::core::events::DomainEvent::ActiveWorkspaceChanged { workspace_dir } =+ event+ {+ let handle = crate::openhuman::config::workspace_handle(&workspace_dir);+ log::info!("[socketio] broadcast workspace_changed workspace={handle}");+ let payload = serde_json::json!({ "workspace": handle });+ let _ = io_workspace.emit("workspace_changed", &payload);+ let _ = io_workspace.emit("workspace:changed", &payload);+ }+ }+ log::debug!("[socketio] workspace_changed bridge stopped");+ });+// 6b. McpSetupSecretRequested → broadcast `mcp_setup:secret_requested`// so the UI can render a native input dialog. Only the opaque// ref + safe display fields are forwarded; raw secret valuesdiff --git a/src/openhuman/desktop/notifications/bus.rs b/src/openhuman/desktop/notifications/bus.rsindex 15f4d44a10..c75d43538b 100644--- a/src/openhuman/desktop/notifications/bus.rs+++ b/src/openhuman/desktop/notifications/bus.rs@@ -185,18 +185,16 @@ fn announces_to(/// The workspace an event belongs to, for the variants that name one.////// `None` means the event is not bound to a workspace and any subscriber may-/// act on it. Only the MCP supervisor variants are bound today, because they-/// are the only ones this bridge handles that one process produces for more-/// than one workspace (#5931).+/// act on it.+///+/// This used to list the MCP supervisor variants here, which was correct for+/// what the bridge handled at the time but wrong as a general rule: the+/// channel and artifact families carry the same field and were not matched,+/// so a bridge that grew an arm for one of them would have gated it against+/// nothing. The list now lives on the event itself (#5966), where a new+/// workspace-bound variant is one arm to add rather than several to find.fn workspace_of(event: &DomainEvent) -> Option<&std::path::Path> {- match event {- DomainEvent::McpServerProbeTimedOut { workspace_dir, .. }- | DomainEvent::McpServerTransportDropped { workspace_dir, .. }- | DomainEvent::McpServerReconnected { workspace_dir, .. }- | DomainEvent::McpServerReconnectFailed { workspace_dir, .. }- | DomainEvent::McpServerParked { workspace_dir, .. } => Some(workspace_dir.as_path()),- _ => None,- }+ event.workspace_dir()}fn now_ms() -> u64 {@@ -208,7 +206,26 @@ fn now_ms() -> u64 {/// Pure translation function — kept free so unit tests can drive it/// without spinning up tokio or the broadcast channel.+///+/// The workspace handle is stamped here rather than inside [`translate`],+/// once, from the event's own+/// [`workspace_dir`](DomainEvent::workspace_dir). Letting each arm decide+/// would reproduce the shape of the bug #5966 exists to fix: the arms that+/// happened to be written with a workspace in mind would carry the identity+/// and the rest would silently not, and which is which would depend on the+/// order the arms were added.pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvent> {+ let mut notification = translate(event)?;+ notification.workspace = event+ .workspace_dir()+ .map(crate::openhuman::config::workspace_handle);+ Some(notification)+}++/// The per-variant translation. Every arm leaves `workspace: None`; the+/// identity is applied uniformly by [`event_to_notification`], which is the+/// only caller.+fn translate(event: &DomainEvent) -> Option<CoreNotificationEvent> {let ts = now_ms();match event {DomainEvent::CronJobCompleted {@@ -229,6 +246,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/settings/cron-jobs".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),DomainEvent::WebhookProcessed {skill_id,@@ -256,6 +274,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/settings/webhooks-triggers".into()),timestamp_ms: ts,actions: None,+ workspace: None,})}DomainEvent::SubagentCompleted {@@ -272,6 +291,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/chat".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),DomainEvent::SubagentFailed {parent_session,@@ -289,6 +309,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/chat".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),DomainEvent::NotificationTriaged {id,@@ -316,6 +337,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/notifications".into()),timestamp_ms: ts,actions: None,+ workspace: None,})}DomainEvent::ProviderApiKeyRejected { provider, message } => Some(CoreNotificationEvent {@@ -333,6 +355,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/connections?tab=llm".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),// The MCP reconnect supervisor's verdicts (#5931), published by// `mcp::registry::supervisor_events`. Only the cases a user can act on@@ -369,6 +392,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/connections?tab=mcp".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),DomainEvent::McpServerReconnected {server_id,@@ -387,6 +411,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/connections?tab=mcp".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),DomainEvent::McpServerParked {server_id,@@ -405,6 +430,7 @@ pub fn event_to_notification(event: &DomainEvent) -> Option<CoreNotificationEvendeep_link: Some("/connections?tab=mcp".into()),timestamp_ms: ts,actions: None,+ workspace: None,}),_ => None,}diff --git a/src/openhuman/desktop/notifications/bus_tests.rs b/src/openhuman/desktop/notifications/bus_tests.rsindex 9212ea1739..9505dda2f3 100644--- a/src/openhuman/desktop/notifications/bus_tests.rs+++ b/src/openhuman/desktop/notifications/bus_tests.rs@@ -207,6 +207,7 @@ fn publish_and_subscribe_deliver_event() {deep_link: None,timestamp_ms: 0,actions: None,+ workspace: None,};let sent = publish_core_notification(evt.clone());@@ -243,6 +244,7 @@ fn publish_with_no_subscribers_does_not_panic() {deep_link: None,timestamp_ms: 42,actions: None,+ workspace: None,});// count is 0 when no subscribers, but the call itself must not panic.let _ = count;@@ -320,3 +322,85 @@ async fn subscriber_without_config_does_not_persist_but_still_translates() {// Nothing to assert beyond "did not panic / persist" — the translation is// covered by event_to_notification tests above.}++// ── event_to_notification: workspace identity (#5966) ──────────────────────++/// A workspace-bound notification carries its workspace's handle, so the+/// receiver can re-check routing when it renders instead of trusting the+/// publish-time gate — which resolves the active workspace and then sends,+/// two steps a switch can slip between.+#[test]+fn a_workspace_bound_notification_carries_its_workspace_handle() {+ let workspace = std::path::PathBuf::from("/tmp/openhuman-ws-a");+ let n = event_to_notification(&DomainEvent::McpServerParked {+ server_id: "srv-1".into(),+ qualified_name: "ac.inference.sh/mcp".into(),+ error: "launcher runtime missing".into(),+ workspace_dir: workspace.clone(),+ })+ .expect("a parked server notifies");++ assert_eq!(+ n.workspace,+ Some(crate::openhuman::config::workspace_handle(&workspace))+ );+}++/// The handle is what goes on the wire *instead of* the path. This payload+/// reaches every connected client, so a regression that forwarded+/// `workspace_dir` would put the user's home directory in front of all of+/// them.+#[test]+fn the_notification_handle_is_not_the_path() {+ let workspace =+ std::path::PathBuf::from("/Users/rumpelstiltskin/.openhuman/users/abc/workspace");+ let n = event_to_notification(&DomainEvent::McpServerParked {+ server_id: "srv-1".into(),+ qualified_name: "ac.inference.sh/mcp".into(),+ error: "launcher runtime missing".into(),+ workspace_dir: workspace,+ })+ .expect("a parked server notifies");++ let handle = n.workspace.expect("bound events carry a handle");+ assert!(+ !handle.contains("rumpelstiltskin"),+ "handle leaked the path: {handle}"+ );+ assert!(+ !handle.contains('/'),+ "handle leaked a path separator: {handle}"+ );+}++/// Two different workspaces must be distinguishable, or the receiver's check+/// passes for everything and the routing is decorative.+#[test]+fn different_workspaces_produce_different_notification_handles() {+ let parked = |dir: &str| {+ event_to_notification(&DomainEvent::McpServerParked {+ server_id: "srv-1".into(),+ qualified_name: "ac.inference.sh/mcp".into(),+ error: "launcher runtime missing".into(),+ workspace_dir: std::path::PathBuf::from(dir),+ })+ .expect("a parked server notifies")+ .workspace+ };+ assert_ne!(parked("/tmp/openhuman-ws-a"), parked("/tmp/openhuman-ws-b"));+}++/// Cron, webhook, sub-agent and rejected-API-key notifications are not bound+/// to a workspace and apply wherever they land. Stamping them with one would+/// make the receiver drop them the moment the user switched.+#[test]+fn a_process_wide_notification_names_no_workspace() {+ let n = event_to_notification(&DomainEvent::CronJobCompleted {+ job_id: "daily-digest".into(),+ success: true,+ output: String::new(),+ })+ .expect("a completed cron job notifies");++ assert_eq!(n.workspace, None);+}diff --git a/src/openhuman/desktop/notifications/store_tests.rs b/src/openhuman/desktop/notifications/store_tests.rsindex f3d590fd39..5c44dfe885 100644--- a/src/openhuman/desktop/notifications/store_tests.rs+++ b/src/openhuman/desktop/notifications/store_tests.rs@@ -291,6 +291,7 @@ fn sample_core_event(id: &str, ts: u64) -> CoreNotificationEvent {deep_link: Some("/settings/cron-jobs".to_string()),timestamp_ms: ts,actions: None,+ workspace: None,}}diff --git a/src/openhuman/desktop/notifications/types.rs b/src/openhuman/desktop/notifications/types.rsindex 4c9c4ce7a7..d7d135440d 100644--- a/src/openhuman/desktop/notifications/types.rs+++ b/src/openhuman/desktop/notifications/types.rs@@ -43,6 +43,28 @@ pub struct CoreNotificationEvent {/// Backward-compatible: old events without this field deserialize to `None`.#[serde(default, skip_serializing_if = "Option::is_none")]pub actions: Option<Vec<CoreNotificationAction>>,+ /// Opaque handle for the workspace this notification belongs to, when it+ /// belongs to one (#5966).+ ///+ /// The publish-time gate in `bus::should_announce` already refuses to+ /// broadcast a notification from a workspace the user has switched away+ /// from, but that decision and the broadcast are not one atomic step:+ /// resolving the active workspace and sending are separate, so a switch+ /// in between can still let one through. Carrying the identity turns a+ /// boolean taken at an instant into something the receiver can re-check+ /// whenever it renders, which is what actually closes the window.+ ///+ /// A *handle*, never `workspace_dir` itself — the path is under the+ /// user's home directory and this payload reaches every connected client.+ /// See [`workspace_handle`](crate::openhuman::config::workspace_handle).+ ///+ /// `None` means the notification is not workspace-bound (cron, webhook,+ /// sub-agent, rejected API key) and applies wherever it lands. Also+ /// `None` for rows persisted before this field existed, which is why it+ /// is `default` — a receiver must treat absence as "not bound", not as a+ /// mismatch, or upgrading would silently hide every stored notification.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub workspace: Option<String>,}/// A single action button attached to a notification.diff --git a/src/openhuman/desktop/notifications/types_tests.rs b/src/openhuman/desktop/notifications/types_tests.rsindex 15e413f942..4035888825 100644--- a/src/openhuman/desktop/notifications/types_tests.rs+++ b/src/openhuman/desktop/notifications/types_tests.rs@@ -47,6 +47,7 @@ fn core_notification_serialize_skips_empty_actions() {deep_link: None,timestamp_ms: 1,actions: None,+ workspace: None,};let s = serde_json::to_string(&event).unwrap();assert!(!s.contains("actions"));diff --git a/src/openhuman/flows/ops_part_09.rs b/src/openhuman/flows/ops_part_09.rsindex a658096d4c..94c10ecb1e 100644--- a/src/openhuman/flows/ops_part_09.rs+++ b/src/openhuman/flows/ops_part_09.rs@@ -537,6 +537,7 @@ fn notify_pending_approval(flow: &Flow, thread_id: &str, pending_approvals: &[Stlabel: "Review".to_string(),payload: Some(action_payload),}]),+ workspace: None,});}diff --git a/src/openhuman/security/approval/gate.rs b/src/openhuman/security/approval/gate.rsindex b738318b96..27912defdf 100644--- a/src/openhuman/security/approval/gate.rs+++ b/src/openhuman/security/approval/gate.rs@@ -331,6 +331,7 @@ fn publish_flow_gate_notification(payload: Some(base_payload(ApprovalDecision::Deny)),},]),+ workspace: None,});}