Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: DOM selector test always fails without an already-open browser tab

Adam Eivy8649ba054a1f
diff --git a/client/src/components/install/QueueInstallInvestigationButton.jsx b/client/src/components/install/QueueInstallInvestigationButton.jsx
index d18b572b1e..61fc9a4201 100644
--- a/client/src/components/install/QueueInstallInvestigationButton.jsx
+++ b/client/src/components/install/QueueInstallInvestigationButton.jsx
@@ -2,30 +2,18 @@
* "Queue agent to investigate" action for an installer failure (#5981).
*
* An install error used to be a dead end — Close was the only affordance — even
- * though PortOS already owns an autonomous-agent queue. This button hands the
- * failure straight to that queue: it builds a reproducible task from the
- * installer name, the failing stage, the error and the streamed log tail, and
- * posts it via `addCosTask` with no `app`, which targets PortOS itself (the
- * installer code lives in this repo).
+ * though PortOS already owns an autonomous-agent queue. This button builds a
+ * reproducible task from the installer name, the failing stage, the error and
+ * the streamed log tail, and hands it to the generic `QueueInvestigationButton`
+ * (which owns queueing, dedup, and the button states — shared with other
+ * failure surfaces like the DOM-selector test).
*
* Rendered by `InstallErrorFooter` (both install modals) and directly by
* `LocalSetupPanel`, which draws its own error region.
*/
-import { useState } from 'react';
-import { Bot, Check } from 'lucide-react';
-import { useAsyncAction } from '../../hooks/useAsyncAction';
import { buildInstallFailureTask } from '../../lib/installFailureTask';
-import { addCosTask } from '../../services/api';
-import toast from '../ui/Toast';
-
-// The task's identity as an investigation (#6043) is the only posture flag sent:
-// the server recognizes `isInvestigation`, derives the dedup fingerprint itself,
-// and applies `CLIENT_INVESTIGATION_DELIVERY` (`server/lib/investigationTasks.js`)
-// — worktree-isolated, PR-gated, reviewed rather than merged on green because a
-// human asked for this one. Keeping the delivery server-side is what stops this
-// button from drifting out of step with the auto-filed posture again.
-const INSTALL_INVESTIGATION_MARKER = { isInvestigation: true };
+import QueueInvestigationButton from '../ui/QueueInvestigationButton';
export default function QueueInstallInvestigationButton({
label,
@@ -35,49 +23,6 @@ export default function QueueInstallInvestigationButton({
surface,
className = '',
}) {
- // null = not queued yet · 'queued' = this click created the task ·
- // 'duplicate' = the store already held one. They read differently to the user:
- // the store's 409 also fires for a task it has BLOCKED, which will not run
- // without intervention, so this must not claim an agent is on it.
- const [queueResult, setQueueResult] = useState(null);
- // `useAsyncAction` owns the failure toast, so the request itself is silent —
- // otherwise the user gets two toasts for one failed queue.
- const [queueTask, queueing] = useAsyncAction(async () => {
- const task = buildInstallFailureTask({ label, stage, error, logs, surface });
- // The description is deterministic per installer + stage, so retrying the
- // same failing install and clicking again hits the store's duplicate guard
- // (409 DUPLICATE_TASK). A task already exists — not a failure to report.
- const duplicateMessage = await addCosTask({ ...task, ...INSTALL_INVESTIGATION_MARKER }, { silent: true })
- .then(() => null)
- .catch((err) => {
- // The server names the existing task's status ("already pending" /
- // "already blocked"); pass it through rather than guessing.
- if (err?.code === 'DUPLICATE_TASK') return err.message || 'A task for this failure already exists';
- throw err;
- });
- setQueueResult(duplicateMessage ? 'duplicate' : 'queued');
- if (duplicateMessage) toast(duplicateMessage, { icon: '🤖' });
- else toast.success('Queued an agent to investigate this failure');
- }, { errorMessage: 'Failed to queue the investigation task' });
-
- return (
- <button
- type="button"
- onClick={queueTask}
- disabled={queueing || queueResult !== null}
- title={queueResult === 'queued'
- ? 'Queued — track it in Agent Ops'
- : queueResult === 'duplicate'
- ? 'A CoS task for this failure already exists — see Agent Ops'
- : 'Queue a PortOS agent task to investigate this install failure'}
- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 disabled:hover:bg-port-accent ${className}`}
- >
- {queueResult ? <Check size={14} /> : <Bot size={14} />}
- {queueResult === 'queued'
- ? 'Agent queued'
- : queueResult === 'duplicate'
- ? 'Task already exists'
- : queueing ? 'Queueing…' : 'Queue agent to investigate'}
- </button>
- );
+ const task = buildInstallFailureTask({ label, stage, error, logs, surface });
+ return <QueueInvestigationButton task={task} className={className} />;
}
diff --git a/client/src/components/messages/SyncTab.jsx b/client/src/components/messages/SyncTab.jsx
index 38c3373f01..434cc14f74 100644
--- a/client/src/components/messages/SyncTab.jsx
+++ b/client/src/components/messages/SyncTab.jsx
@@ -1,11 +1,23 @@
import { useState, useEffect, useCallback } from 'react';
-import { RefreshCw, AlertCircle, Settings, Globe, Mail, MailOpen } from 'lucide-react';
+import { RefreshCw, AlertCircle, CheckCircle2, Settings, Globe, Mail, MailOpen } from 'lucide-react';
import toast from '../ui/Toast';
import { FormField } from '../ui/FormField';
+import QueueInvestigationButton from '../ui/QueueInvestigationButton';
import { formatDateTime } from '../../utils/formatters';
+import { buildSelectorTestFailureTask } from '../../lib/selectorTestFailureTask';
import * as api from '../../services/api';
import socket from '../../services/socket';
+// Human-facing summary per `testSelectors()` status — kept out of JSX so the
+// failure-task builder and the toast can share the same wording.
+const TEST_STATUS_TEXT = {
+ ok: 'All selectors matched on the live page',
+ 'no-browser': 'No browser tab available — is portos-browser running?',
+ 'auth-required': 'Login required — open the browser and sign in first',
+ 'no-selectors': 'No selectors configured for this provider',
+ partial: 'Some selectors matched zero elements on the live page',
+};
+
// Default selectors for supported providers — ensures editor cards always render,
// even on fresh installs before selectors.json exists.
const DEFAULT_SELECTORS = {
@@ -18,6 +30,7 @@ export default function SyncTab({ accounts, onRefresh }) {
const [rawSelectors, setRawSelectors] = useState({});
const [editingSelector, setEditingSelector] = useState(null);
const [selectorForm, setSelectorForm] = useState({});
+ const [testResults, setTestResults] = useState({});
// Merge fetched selectors with defaults so every supported provider always appears
const selectors = Object.fromEntries(
@@ -87,8 +100,15 @@ export default function SyncTab({ accounts, onRefresh }) {
};
const handleTestSelectors = async (provider) => {
- const result = await api.testMessageSelectors(provider).catch(() => null);
- if (result) toast.success(`Selector test: ${result.status}`);
+ setTestResults(prev => ({ ...prev, [provider]: { status: 'testing' } }));
+ const result = await api.testMessageSelectors(provider).catch((err) => ({
+ status: 'error',
+ error: err?.message || 'Test request failed',
+ }));
+ setTestResults(prev => ({ ...prev, [provider]: result }));
+ const summary = TEST_STATUS_TEXT[result.status] || result.error || 'Selector test failed';
+ if (result.status === 'ok') toast.success(summary);
+ else toast.error(summary);
};
return (
@@ -170,9 +190,10 @@ export default function SyncTab({ accounts, onRefresh }) {
<div className="flex items-center gap-2">
<button
onClick={() => handleTestSelectors(provider)}
- className="text-xs text-gray-400 hover:text-white transition-colors"
+ disabled={testResults[provider]?.status === 'testing'}
+ className="text-xs text-gray-400 hover:text-white transition-colors disabled:opacity-50"
>
- Test
+ {testResults[provider]?.status === 'testing' ? 'Testing…' : 'Test'}
</button>
<button
onClick={() => {
@@ -223,6 +244,34 @@ export default function SyncTab({ accounts, onRefresh }) {
))}
</div>
)}
+ {testResults[provider] && testResults[provider].status !== 'testing' && (
+ <div className={`mt-3 p-2 rounded border text-xs ${
+ testResults[provider].status === 'ok'
+ ? 'border-port-success/30 bg-port-success/10 text-port-success'
+ : 'border-port-error/30 bg-port-error/10 text-port-error'
+ }`}>
+ <div className="flex items-start justify-between gap-2">
+ <span className="flex items-center gap-1">
+ {testResults[provider].status === 'ok' ? <CheckCircle2 size={14} /> : <AlertCircle size={14} />}
+ {TEST_STATUS_TEXT[testResults[provider].status] || testResults[provider].error || 'Selector test failed'}
+ </span>
+ {testResults[provider].status !== 'ok' && (
+ <QueueInvestigationButton
+ task={buildSelectorTestFailureTask({ provider, ...testResults[provider] })}
+ />
+ )}
+ </div>
+ {testResults[provider].results && Object.keys(testResults[provider].results).length > 0 && (
+ <ul className="mt-1 space-y-0.5 font-mono text-gray-400">
+ {Object.entries(testResults[provider].results).map(([key, r]) => (
+ <li key={key} className={r.matches > 0 ? '' : 'text-port-error'}>
+ {key}: {r.matches} match{r.matches === 1 ? '' : 'es'}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
</div>
))}
</div>
diff --git a/client/src/components/messages/SyncTab.test.jsx b/client/src/components/messages/SyncTab.test.jsx
new file mode 100644
index 0000000000..ec1f2bfd60
--- /dev/null
+++ b/client/src/components/messages/SyncTab.test.jsx
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ getMessageSelectors: vi.fn(),
+ testMessageSelectors: vi.fn(),
+ addCosTask: vi.fn(),
+}));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), {
+ error: vi.fn(),
+ success: vi.fn(),
+}));
+const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
+
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({ default: toast }));
+vi.mock('../../services/socket', () => ({ default: socket }));
+
+const SyncTab = (await import('./SyncTab')).default;
+
+const renderTab = () => render(<SyncTab accounts={[]} onRefresh={vi.fn()} />);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getMessageSelectors.mockResolvedValue({});
+});
+
+describe('SyncTab DOM selector test', () => {
+ it('reports success with no investigate button when every selector matches', async () => {
+ api.testMessageSelectors.mockResolvedValue({
+ provider: 'teams',
+ status: 'ok',
+ results: { messageItem: { selector: "[role='listitem']", matches: 8 } },
+ });
+ renderTab();
+
+ fireEvent.click(screen.getAllByText('Test')[1]); // teams card
+
+ await waitFor(() => expect(screen.getByText(/all selectors matched/i)).toBeTruthy());
+ expect(toast.success).toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: /queue agent to investigate/i })).toBeNull();
+ });
+
+ it('reports failure and offers to queue an investigation agent', async () => {
+ api.testMessageSelectors.mockResolvedValue({
+ provider: 'outlook',
+ status: 'no-browser',
+ results: {},
+ error: 'Failed to open a browser tab — is portos-browser running?',
+ });
+ renderTab();
+
+ fireEvent.click(screen.getAllByText('Test')[0]); // outlook card
+
+ await waitFor(() => expect(screen.getByText(/no browser tab available/i)).toBeTruthy());
+ expect(toast.error).toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: /queue agent to investigate/i })).toBeTruthy();
+ });
+
+ it('queues a CoS investigation task naming the failing provider and status', async () => {
+ api.testMessageSelectors.mockResolvedValue({
+ provider: 'outlook',
+ status: 'partial',
+ results: { messageRow: { selector: "[role='listbox'] [role='option']", matches: 0 } },
+ });
+ api.addCosTask.mockResolvedValue({ id: 'task-1' });
+ renderTab();
+
+ fireEvent.click(screen.getAllByText('Test')[0]);
+ await waitFor(() => expect(screen.getByText(/some selectors matched zero elements/i)).toBeTruthy());
+ expect(screen.getByText(/messageRow: 0 matches/i)).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: /queue agent to investigate/i }));
+
+ await waitFor(() => expect(api.addCosTask).toHaveBeenCalledTimes(1));
+ const [task, options] = api.addCosTask.mock.calls[0];
+ expect(task.isInvestigation).toBe(true);
+ expect(task.description).toMatch(/outlook/i);
+ expect(task.prompt).toContain('partial');
+ expect(options).toEqual({ silent: true });
+ await waitFor(() => expect(screen.getByRole('button', { name: /agent queued/i })).toBeTruthy());
+ });
+});
diff --git a/client/src/components/ui/QueueInvestigationButton.jsx b/client/src/components/ui/QueueInvestigationButton.jsx
new file mode 100644
index 0000000000..6b550b2409
--- /dev/null
+++ b/client/src/components/ui/QueueInvestigationButton.jsx
@@ -0,0 +1,72 @@
+/**
+ * Generic "Queue agent to investigate" action (#5981) for any UI-detected
+ * failure that should hand a reproducible task to the CoS queue.
+ *
+ * The caller builds the task (`{ description, prompt }`, e.g. via
+ * `buildInstallFailureTask` or `buildSelectorTestFailureTask`) — this
+ * component owns everything downstream: posting it with the durable
+ * `isInvestigation` marker, handling the store's 409 `DUPLICATE_TASK` as an
+ * "already queued" state rather than an error, and the three button states.
+ * `QueueInstallInvestigationButton` is a thin wrapper of this for its
+ * existing installer-failure call sites.
+ */
+
+import { useState } from 'react';
+import { Bot, Check } from 'lucide-react';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { addCosTask } from '../../services/api';
+import toast from './Toast';
+
+// The task's identity as an investigation (#6043) is the only posture flag sent:
+// the server recognizes `isInvestigation`, derives the dedup fingerprint itself,
+// and applies `CLIENT_INVESTIGATION_DELIVERY` (`server/lib/investigationTasks.js`)
+// — worktree-isolated, PR-gated, reviewed rather than merged on green because a
+// human asked for this one.
+const INVESTIGATION_MARKER = { isInvestigation: true };
+
+export default function QueueInvestigationButton({ task, className = '' }) {
+ // null = not queued yet · 'queued' = this click created the task ·
+ // 'duplicate' = the store already held one. They read differently to the user:
+ // the store's 409 also fires for a task it has BLOCKED, which will not run
+ // without intervention, so this must not claim an agent is on it.
+ const [queueResult, setQueueResult] = useState(null);
+ // `useAsyncAction` owns the failure toast, so the request itself is silent —
+ // otherwise the user gets two toasts for one failed queue.
+ const [queueTask, queueing] = useAsyncAction(async () => {
+ // The description is deterministic per failure, so retrying the same
+ // failure and clicking again hits the store's duplicate guard (409
+ // DUPLICATE_TASK). A task already exists — not a failure to report.
+ const duplicateMessage = await addCosTask({ ...task, ...INVESTIGATION_MARKER }, { silent: true })
+ .then(() => null)
+ .catch((err) => {
+ // The server names the existing task's status ("already pending" /
+ // "already blocked"); pass it through rather than guessing.
+ if (err?.code === 'DUPLICATE_TASK') return err.message || 'A task for this failure already exists';
+ throw err;
+ });
+ setQueueResult(duplicateMessage ? 'duplicate' : 'queued');
+ if (duplicateMessage) toast(duplicateMessage, { icon: '🤖' });
+ else toast.success('Queued an agent to investigate this failure');
+ }, { errorMessage: 'Failed to queue the investigation task' });
+
+ return (
+ <button
+ type="button"
+ onClick={queueTask}
+ disabled={queueing || queueResult !== null}
+ title={queueResult === 'queued'
+ ? 'Queued — track it in Agent Ops'
+ : queueResult === 'duplicate'
+ ? 'A CoS task for this failure already exists — see Agent Ops'
+ : 'Queue a PortOS agent task to investigate this failure'}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 disabled:hover:bg-port-accent ${className}`}
+ >
+ {queueResult ? <Check size={14} /> : <Bot size={14} />}
+ {queueResult === 'queued'
+ ? 'Agent queued'
+ : queueResult === 'duplicate'
+ ? 'Task already exists'
+ : queueing ? 'Queueing…' : 'Queue agent to investigate'}
+ </button>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f6dd9fd565..e8387d301e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -72,6 +72,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `loraEffect.js` | How the LoRA manager card renders an adapter-effect measurement (#4872). `LORA_EFFECT_STATUSES` is re-exported from `server/lib/loraEffect.js`; `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (only `zero` is styled as an error, because only `zero` refuses a render server-side) and `loraEffectDetail(report)` are client-only — the detail line returns `null` when the badge already says everything, where the server's `formatLoraEffect` always returns a sentence for its log. |
| `loraTriggers.js` | The picker's `+ trigger` append (#4665). `firstTriggerWord` / `promptHasTriggerWord` / `separatorFor` are re-exported from `server/lib/loraTriggers.js`, so the hint reads the rule the render enforces. `appendTriggerWords(prompt, words, effectivePrompt?)` is client-only: it adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`, including the shared LTX + MiniMax H3 Ref2VA audio-to-video runtime predicate. |
+| `selectorTestFailureTask.js` | Build the CoS task payload behind the DOM-selector-test "Investigate & fix" action (Settings > Messages > Sync tab): `buildSelectorTestFailureTask({ provider, status, results, error })` → `{ description, prompt }` naming the provider, the `testSelectors()` status, the per-selector match counts, and the relevant source files. Fed to the generic `QueueInvestigationButton` (`components/ui/QueueInvestigationButton.jsx`), the same queueing primitive `installFailureTask.js` uses. |
| `slashdoCatalog.js` | The Agent Operations buttons. `SLASHDO_WORKFLOWS` is `server/lib/slashdoCatalog.js`'s list decorated with a per-command Tailwind tone, and `slashdoWorkflowsForApp(isSwiftApp)` filters it through the server's own `slashdoWorkflowAppliesTo` — so the panel cannot be a workflow short. `SLASHDO_NAMESPACE` + `slashdoLabel(command)` (the `/do:x` UI spelling) stay local: the server module that owns the namespace reaches for the provider registry. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. Re-exported from `server/lib/isSafeHref.js`; `utils/urlNormalize.js` re-exports it again as `isHttpUrl`. |
| `issueLength.js` | The Length Profile picker's helpers. `LENGTH_PROFILES`, `DEFAULT_LENGTH_PROFILE` and the `CUSTOM_*` bounds are re-exported from `server/lib/issueLength.js` (the same profiles the server computes targets from); `clampInt` and `summarizeLengthProfile` are client-only form/display helpers. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 4e5085b182..62999e43f5 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -67,6 +67,7 @@ export * from './reviewerPins.js';
export * from './loraEffect.js';
export * from './loraTriggers.js';
export * from './runnerFamilies.js';
+export * from './selectorTestFailureTask.js';
export * from './slashdoCatalog.js';
export * from './videoFinish.js';
export * from './videoGenParams.js';
diff --git a/client/src/lib/selectorTestFailureTask.js b/client/src/lib/selectorTestFailureTask.js
new file mode 100644
index 0000000000..10914ae168
--- /dev/null
+++ b/client/src/lib/selectorTestFailureTask.js
@@ -0,0 +1,62 @@
+/**
+ * Build the CoS task payload for the "Investigate & fix" action on a failing
+ * DOM-selector test (Settings > Messages > Sync tab > DOM Selectors).
+ *
+ * Pure: no React, no network. The caller hands the result straight to
+ * `QueueInvestigationButton`.
+ */
+
+const STATUS_PROSE = {
+ 'no-browser': 'PortOS could not open or find a browser tab for this provider in the CDP browser — portos-browser may not be running.',
+ 'auth-required': 'The open browser tab is on a login/redirect page, so the selectors could not be evaluated against the real inbox — the account may need to sign in again.',
+ 'no-selectors': 'No selectors are configured for this provider.',
+ partial: 'At least one configured selector matched zero elements on the live page — the provider likely changed its DOM structure.',
+};
+
+function formatResults(results) {
+ const entries = Object.entries(results || {});
+ if (entries.length === 0) return '(no selectors were evaluated)';
+ return entries
+ .map(([name, r]) => `- ${name}: \`${r?.selector}\` -> ${r?.matches ?? 0} match${r?.matches === 1 ? '' : 'es'}`)
+ .join('\n');
+}
+
+/**
+ * @param {object} input
+ * @param {string} input.provider - 'outlook' | 'teams'
+ * @param {string} input.status - the `testSelectors()` status ('no-browser' | 'auth-required' | 'no-selectors' | 'partial' | 'error')
+ * @param {object} [input.results] - per-selector `{ selector, matches }` from the test response.
+ * @param {string} [input.error] - the test response's `error`, when present.
+ * @returns {{ description: string, prompt: string }} ready for `QueueInvestigationButton`.
+ */
+export function buildSelectorTestFailureTask({ provider, status, results, error } = {}) {
+ const name = provider === 'teams' ? 'Teams' : 'Outlook';
+ const description = `Fix failing DOM selector test for ${name} message sync`;
+ const prose = STATUS_PROSE[status] || 'The selector test did not report success.';
+
+ const sections = [
+ `The DOM Selectors test for ${name} (Settings > Messages > Sync tab) is failing. Investigate the root cause and fix it.`,
+ '',
+ `Provider: ${name}`,
+ `Test status: ${status || '(unknown)'}`,
+ prose,
+ ];
+ if (error) sections.push(`Error: ${error}`);
+ sections.push(
+ '',
+ 'Per-selector results from the last test run:',
+ formatResults(results),
+ '',
+ 'Relevant code: server/services/messagePlaywrightSync.js (testSelectors, buildExtractionScript), '
+ + 'server/services/browserService.js (findOrOpenPage, isAuthPage, evaluateOnPage), '
+ + 'client/src/components/messages/SyncTab.jsx (the DOM Selectors panel).',
+ '',
+ 'Reproduce against the portos-browser CDP instance (Settings > Browser), find why the configured '
+ + 'selector(s) no longer match the live page DOM — the provider may have changed its markup, or the '
+ + 'selector may not be the one the real scraper actually reads (the Outlook extraction script currently '
+ + "hardcodes its own selectors rather than reading messageRow from data/messages/selectors.json) — and "
+ + 'fix the selector(s) or the code that reads them so the test reports "ok".',
+ );
+
+ return { description, prompt: sections.join('\n') };
+}
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index ed12494e2c..2021fbd8b1 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -508,13 +508,24 @@ export async function sendPlaywright(account, draft) {
}
/**
- * Test selectors against the current page
+ * Test selectors against the live provider page.
+ * Reuses the same page as a real sync (`findOrOpenPage`, so a not-yet-open tab
+ * is opened rather than failing outright — a tab already open for this
+ * provider is reused, never re-navigated) and the same auth check
+ * (`isAuthPage`), so a stale login redirect is reported as `auth-required`
+ * instead of silently evaluating to zero matches and reading as a broken
+ * selector.
*/
export async function testSelectors(provider) {
const targetUrl = provider === 'teams' ? TEAMS_URL : OUTLOOK_URL;
- const pages = await getPages().catch(() => []);
- const page = pages.find(p => p.url?.includes(new URL(targetUrl).hostname));
- if (!page) return { provider, results: {}, status: 'no_page', error: 'No browser tab open for this provider' };
+ const page = await findOrOpenPage(targetUrl).catch(() => null);
+ if (!page) {
+ return { provider, results: {}, status: 'no-browser', error: 'Failed to open a browser tab — is portos-browser running?' };
+ }
+
+ if (isAuthPage(page)) {
+ return { provider, results: {}, status: 'auth-required', error: 'Login required — sign into the provider first' };
+ }
const allSelectors = await getSelectors();
const sels = allSelectors[provider] || {};
diff --git a/server/services/messagePlaywrightSync.test.js b/server/services/messagePlaywrightSync.test.js
new file mode 100644
index 0000000000..92fe68eee2
--- /dev/null
+++ b/server/services/messagePlaywrightSync.test.js
@@ -0,0 +1,95 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const findOrOpenPage = vi.fn();
+const isAuthPage = vi.fn();
+const evaluateOnPage = vi.fn();
+const listCdpPages = vi.fn();
+vi.mock('./browserService.js', () => ({ findOrOpenPage, isAuthPage, evaluateOnPage, listCdpPages }));
+
+const tryReadFile = vi.fn();
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return { ...actual, tryReadFile };
+});
+
+const { testSelectors } = await import('./messagePlaywrightSync.js');
+
+const OPEN_PAGE = { url: 'https://outlook.office.com/mail/', webSocketDebuggerUrl: 'ws://x' };
+
+describe('testSelectors', () => {
+ beforeEach(() => {
+ findOrOpenPage.mockReset();
+ isAuthPage.mockReset();
+ evaluateOnPage.mockReset();
+ tryReadFile.mockReset();
+ });
+
+ it('reports no-browser when no CDP tab could be found or opened', async () => {
+ findOrOpenPage.mockResolvedValue(null);
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('no-browser');
+ expect(result.results).toEqual({});
+ expect(isAuthPage).not.toHaveBeenCalled();
+ });
+
+ it('reports auth-required without evaluating selectors when the tab is a login redirect', async () => {
+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);
+ isAuthPage.mockReturnValue(true);
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('auth-required');
+ expect(evaluateOnPage).not.toHaveBeenCalled();
+ });
+
+ it('reports no-selectors when the provider has none configured', async () => {
+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);
+ isAuthPage.mockReturnValue(false);
+ tryReadFile.mockResolvedValue(JSON.stringify({}));
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('no-selectors');
+ expect(evaluateOnPage).not.toHaveBeenCalled();
+ });
+
+ it('reports ok when every configured selector matches at least one element', async () => {
+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);
+ isAuthPage.mockReturnValue(false);
+ tryReadFile.mockResolvedValue(JSON.stringify({ outlook: { messageRow: "[role='listbox'] [role='option']" } }));
+ evaluateOnPage.mockResolvedValue(12);
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('ok');
+ expect(result.results.messageRow).toEqual({ selector: "[role='listbox'] [role='option']", matches: 12 });
+ });
+
+ it('reports partial when at least one configured selector matches zero elements', async () => {
+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);
+ isAuthPage.mockReturnValue(false);
+ tryReadFile.mockResolvedValue(JSON.stringify({
+ outlook: { messageRow: "[role='listbox'] [role='option']", extra: '.gone' },
+ }));
+ evaluateOnPage.mockResolvedValueOnce(3).mockResolvedValueOnce(0);
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('partial');
+ expect(result.results.extra).toEqual({ selector: '.gone', matches: 0 });
+ });
+
+ it('treats a failed evaluation (null) as zero matches rather than throwing', async () => {
+ findOrOpenPage.mockResolvedValue(OPEN_PAGE);
+ isAuthPage.mockReturnValue(false);
+ tryReadFile.mockResolvedValue(JSON.stringify({ outlook: { messageRow: "[role='listbox'] [role='option']" } }));
+ evaluateOnPage.mockResolvedValue(null);
+
+ const result = await testSelectors('outlook');
+
+ expect(result.status).toBe('partial');
+ expect(result.results.messageRow.matches).toBe(0);
+ });
+});