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
test(e2e): add browser coverage for plan review, durable reply and parallel turns
M3gA-Mindc979918e9037
diff --git a/app/test/e2e/specs/chat-external-link.spec.ts b/app/test/e2e/specs/chat-external-link.spec.tsnew file mode 100644index 0000000000..c21103e16a--- /dev/null+++ b/app/test/e2e/specs/chat-external-link.spec.ts@@ -0,0 +1,132 @@+import { expect } from '@wdio/globals';++import { waitForApp } from '../helpers/app-helpers';+import { waitForTestId } from '../helpers/element-helpers';+import { resetApp } from '../helpers/reset-app';+import { navigateViaHash } from '../helpers/shared-flows';++/**+ * External navigation — a remote page never loads in the main webview.+ *+ * Matrix 4.2.11 is 🟡 and says *"automated desktop E2E is a follow-up (the WDIO+ * desktop runner still assumes CEF)"*. **That parenthetical is stale.** The+ * Appium/CEF backend was removed in #5478 precisely because CDP does not exist+ * under Wry; the runner is a single `tauri-driver` WebDriver session against+ * the native WebKit webview (`app/scripts/e2e-run-session.sh:14-15`,+ * `app/test/wdio.conf.ts:10-14`), and the shell is+ * `pub(crate) type AppRuntime = tauri::Wry` unconditionally+ * (`crates/openhuman-app/src/lib.rs:131`). The stated blocker is gone.+ *+ * This is the one case in this slice that cannot be a Playwright spec. The+ * claim is about the *shell's* policy: `external_navigation::init()`'s+ * `on_navigation` hook returns `false` for any http(s) navigation of the `main`+ * window that is not the app origin or the dev server, cancelling it and handing+ * the URL to the OS opener (`crates/openhuman-app/src/external_navigation.rs:54-89`).+ * A browser has no such hook, so a Playwright version would assert nothing.+ *+ * RU (`external_navigation_tests.rs`) proves `navigation_handoff` returns the+ * right answer. It cannot prove the plugin is *installed on the main window in+ * the shipping build* — a wiring regression (registered late, or on the wrong+ * webview) passes every existing test while the main webview, which holds the+ * app's IPC bridge, loads someone else's origin. That is a security boundary,+ * not a UX defect, which is why it is worth a desktop spec of its own.+ *+ * ## No network leaves this machine+ *+ * The probe host is under `.invalid`, the TLD RFC 2606 reserves as guaranteed+ * never to resolve. The assertion is that navigation did NOT happen, so the URL+ * never needs to load; and when the policy works as intended it hands the URL to+ * the OS opener, whose own lookup fails at DNS. Nothing contacts a real service+ * on either branch.+ */++const USER_ID = 'e2e-chat-external-link';+const REMOTE_URL = 'https://openhuman-e2e.invalid/external-link-probe';++/** The app's own URL, whatever scheme the shell serves it under. */+async function currentUrl(): Promise<string> {+ return browser.getUrl();+}++function isAppUrl(url: string): boolean {+ return /^(tauri:|https?:\/\/(tauri\.localhost|localhost|127\.0\.0\.1))/.test(url);+}++describe('External link navigation policy', () => {+ before(async () => {+ await waitForApp();+ await resetApp(USER_ID);+ await navigateViaHash('/chat');+ await waitForTestId('root-shell-sidebar');+ });++ it('observes an in-app navigation, so "unchanged" below means something', async () => {+ // The control. Without it, every assertion in this file could pass against+ // a `getUrl()` that had stopped reporting changes at all.+ const before = await currentUrl();+ await navigateViaHash('/settings');+ await browser.waitUntil(async () => (await currentUrl()) !== before, {+ timeout: 15_000,+ timeoutMsg:+ 'getUrl() never observed an in-app route change, so it cannot witness a remote one',+ });++ await navigateViaHash('/chat');+ await waitForTestId('root-shell-sidebar');+ });++ it('refuses a scripted remote navigation of the main webview', async () => {+ const before = await currentUrl();+ expect(isAppUrl(before)).toBe(true);++ await browser.execute((url: string) => {+ window.location.href = url;+ }, REMOTE_URL);++ // Give a real navigation time to commit. If the policy were absent this is+ // long enough for the webview to have left the app.+ await browser.pause(4_000);++ // Asserted as a string rather than a boolean so a failure prints the URL+ // the webview actually reached — `expect(false).toBe(true)` would not.+ // WDIO's `expect` takes no message argument.+ const after = await currentUrl();+ expect(isAppUrl(after) ? 'stayed in the app' : `navigated away to ${after}`).toBe(+ 'stayed in the app'+ );+ expect(after).not.toContain('openhuman-e2e.invalid');+ });++ it('refuses a remote link click in the main webview', async () => {+ // The scripted case above and this one fail differently: an `href`+ // assignment and a user-gesture link click take different paths into the+ // webview, and a policy installed on only one of them would pass the other.+ const before = await currentUrl();+ expect(isAppUrl(before)).toBe(true);++ await browser.execute((url: string) => {+ const anchor = document.createElement('a');+ anchor.id = 'e2e-external-link-probe';+ anchor.href = url;+ anchor.target = '_self';+ anchor.textContent = 'external probe';+ document.body.appendChild(anchor);+ anchor.click();+ }, REMOTE_URL);++ await browser.pause(4_000);++ const after = await currentUrl();+ expect(isAppUrl(after) ? 'stayed in the app' : `link click navigated to ${after}`).toBe(+ 'stayed in the app'+ );++ // The app must still be the app: a cancelled navigation should leave the+ // renderer untouched, not tear its tree down.+ await waitForTestId('root-shell-sidebar');++ await browser.execute(() => {+ document.getElementById('e2e-external-link-probe')?.remove();+ });+ });+});diff --git a/app/test/e2e/specs/credential-channels-flow.spec.ts b/app/test/e2e/specs/credential-channels-flow.spec.tsnew file mode 100644index 0000000000..a375741867--- /dev/null+++ b/app/test/e2e/specs/credential-channels-flow.spec.ts@@ -0,0 +1,284 @@+/**+ * Credential channels — Yuanbao (10.1.5) and Email/IMAP-SMTP (10.1.6).+ *+ * Both are `api_key` channels: the user pastes credentials into the generic+ * `ChannelSetupModal` and the core validates them against the channel's+ * `ChannelDefinition`. Neither had a spec at any UI layer —+ * `git grep -l 'yuanbao\|imap' app/test/e2e/specs app/test/playwright/specs`+ * returned nothing — which is what matrix rows 10.1.5 ("No WDIO spec yet") and+ * 10.1.6 ("WDIO connect-flow [is a] follow-up") record.+ *+ * ## What this asserts, and what it deliberately leaves to the Rust unit tests+ *+ * The Rust side already covers the *ops layer* for both channels:+ * `channels/controllers/ops_yuanbao_email_tests.rs` and+ * `ops/connect_email_config_tests_tests.rs` cover credential→config mapping,+ * defaults, port/sender parsing, persist + disconnect and pre-network+ * invalid-port rejection. Re-asserting any of that here would duplicate it.+ *+ * What no layer covered is the **RPC surface these channels are reached+ * through**: that each one is in the definition table `channels_list` serves,+ * that `channels_describe` returns the field set the setup modal renders its+ * inputs from, and that connect→status→disconnect round-trips over the wire.+ * A channel can be fully implemented in `ops` and still be unreachable if it+ * drops out of `all_channel_definitions()` — `channels_connect` resolves the+ * definition first (`tinychannels/src/backend.rs:208-210`) and fails with+ * "unknown channel" before any of the covered code runs. Slack and WhatsApp are+ * both in that state today; nothing caught it.+ *+ * Mirrors the C.1/C.2/C.3/C.4/C.8/C.9 shape of `telegram-channel-flow.spec.ts`,+ * which is the house pattern for a channel lifecycle.+ *+ * No network: `api_key` connect stores credentials locally. The Yuanbao+ * sign-token preflight and the IMAP login are not reached — this spec never+ * supplies credentials that would pass validation into a live call, and the+ * mock backend is the only server running.+ */+import { waitForApp } from '../helpers/app-helpers';+import { callOpenhumanRpc } from '../helpers/core-rpc';+import { resetApp } from '../helpers/reset-app';+import { startMockServer, stopMockServer } from '../mock-server';++const LOG_PREFIX = '[CredentialChannels]';++interface AuthModeSpec {+ mode?: string;+ fields?: { key?: string; required?: boolean }[];+}++interface ChannelDefinition {+ id?: string;+ display_name?: string;+ auth_modes?: AuthModeSpec[];+ authModes?: AuthModeSpec[];+}++interface ChannelStatusEntry {+ channelId?: string;+ channel_id?: string;+ connected?: boolean;+ hasCredentials?: boolean;+ has_credentials?: boolean;+}++/** `RpcOutcome` wraps payloads inconsistently across controllers; drill down. */+function unwrap(result: unknown): unknown {+ const outer = (result as Record<string, unknown> | null) ?? {};+ if (Array.isArray(outer)) return outer;+ return (outer as Record<string, unknown>).result ?? outer;+}++function asArray(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function authModesOf(def: ChannelDefinition | undefined): AuthModeSpec[] {+ return asArray(def?.auth_modes ?? def?.authModes) as AuthModeSpec[];+}++/** Field keys declared for one auth mode, as the setup modal would read them. */+function fieldKeysFor(def: ChannelDefinition | undefined, mode: string): string[] {+ const spec = authModesOf(def).find(m => m.mode === mode);+ return asArray(spec?.fields)+ .map(f => (f as { key?: string }).key)+ .filter((k): k is string => typeof k === 'string');+}++async function describeChannel(channel: string): Promise<ChannelDefinition | undefined> {+ const out = await callOpenhumanRpc('openhuman.channels_describe', { channel });+ expect(out.ok).toBe(true);+ return unwrap(out.result) as ChannelDefinition | undefined;+}++async function statusFor(channel: string): Promise<ChannelStatusEntry | undefined> {+ const out = await callOpenhumanRpc('openhuman.channels_status', { channel });+ expect(out.ok).toBe(true);+ const payload = unwrap(out.result);+ const entries = asArray(+ Array.isArray(payload) ? payload : (payload as Record<string, unknown>)?.entries+ ) as ChannelStatusEntry[];+ return entries.find(e => (e.channelId ?? e.channel_id) === channel);+}++function isConnected(entry: ChannelStatusEntry | undefined): boolean {+ return entry?.connected === true;+}++/**+ * The two credential channels under test, with the field keys their+ * definitions declare (`tinychannels-bus/src/controllers/definitions.rs`:+ * `yuanbao_definition` :634, `email_definition` :533).+ */+const CREDENTIAL_CHANNELS = [+ {+ channel: 'yuanbao',+ label: 'Yuanbao',+ requiredFields: ['app_key', 'app_secret'],+ validCredentials: {+ app_key: 'e2e-yuanbao-app-key',+ app_secret: 'e2e-yuanbao-app-secret',+ },+ /** Omits `app_secret`, which the definition marks required. */+ incompleteCredentials: { app_key: 'e2e-yuanbao-app-key' },+ missingFieldHint: 'app_secret',+ },+ {+ channel: 'email',+ label: 'Email (IMAP/SMTP)',+ requiredFields: ['imap_host', 'username'],+ validCredentials: {+ imap_host: 'imap.e2e.invalid',+ imap_port: '993',+ username: '[email protected]',+ password: 'e2e-app-password',+ },+ /** Omits `username`, which the definition marks required. */+ incompleteCredentials: { imap_host: 'imap.e2e.invalid' },+ missingFieldHint: 'username',+ },+] as const;++describe('Credential channels — Yuanbao and Email (IMAP/SMTP)', () => {+ before(async function beforeSuite() {+ this.timeout(90_000);+ await startMockServer();+ await waitForApp();+ await resetApp('e2e-credential-channels');+ });++ after(async () => {+ await stopMockServer();+ });++ it('D.1 channels_list includes both credential channels with an api_key auth mode', async function () {+ this.timeout(30_000);+ const out = await callOpenhumanRpc('openhuman.channels_list', {});+ expect(out.ok).toBe(true);++ const payload = unwrap(out.result);+ const channels = asArray(+ Array.isArray(payload) ? payload : (payload as Record<string, unknown>)?.channels+ ) as ChannelDefinition[];+ expect(channels.length).toBeGreaterThan(0);++ for (const { channel, label } of CREDENTIAL_CHANNELS) {+ const def = channels.find(c => c.id === channel);+ if (!def) {+ throw new Error(+ `${label} is missing from channels_list, so the setup UI cannot offer it and ` ++ `channels_connect would fail with "unknown channel: ${channel}"`+ );+ }+ if (!authModesOf(def).some(m => m.mode === 'api_key')) {+ throw new Error(`${label} should advertise the api_key auth mode`);+ }+ }+ });++ for (const spec of CREDENTIAL_CHANNELS) {+ const { channel, label, requiredFields, validCredentials, incompleteCredentials } = spec;++ it(`D.2 channels_describe for ${channel} returns the fields the setup modal renders`, async function () {+ this.timeout(30_000);+ const def = await describeChannel(channel);+ expect(def?.id).toBe(channel);++ const keys = fieldKeysFor(def, 'api_key');+ for (const field of requiredFields) {+ if (!keys.includes(field)) {+ throw new Error(+ `${label}'s api_key auth mode should declare the "${field}" field — the generic ` ++ `ChannelSetupModal builds its inputs from this list, so a field that drops out ` ++ `of the definition silently disappears from the connect form. Got: ${keys.join(', ')}`+ );+ }+ }+ });++ it(`D.3 ${channel} connect with complete credentials reports connected`, async function () {+ this.timeout(60_000);+ // Start from a known-disconnected state so a leftover connection from an+ // earlier run cannot make the assertion below pass without a connect.+ await callOpenhumanRpc('openhuman.channels_disconnect', {+ channel,+ authMode: 'api_key',+ });+ if (isConnected(await statusFor(channel))) {+ throw new Error(+ `precondition: ${label} should be disconnected before the connect under test`+ );+ }++ const out = await callOpenhumanRpc('openhuman.channels_connect', {+ channel,+ authMode: 'api_key',+ credentials: validCredentials,+ });+ if (!out.ok) {+ throw new Error(`${label} connect should be accepted: ${JSON.stringify(out)}`);+ }++ if (!isConnected(await statusFor(channel))) {+ throw new Error(+ `${label} reported a successful connect but channels_status does not show it ` ++ `connected — the credentials were accepted and then not persisted`+ );+ }+ console.log(`${LOG_PREFIX} D.3 ${channel}: connected`);+ });++ it(`D.4 ${channel} connect missing a required credential is rejected`, async function () {+ this.timeout(60_000);+ await callOpenhumanRpc('openhuman.channels_disconnect', {+ channel,+ authMode: 'api_key',+ });++ const out = await callOpenhumanRpc('openhuman.channels_connect', {+ channel,+ authMode: 'api_key',+ credentials: incompleteCredentials,+ });++ if (out.ok) {+ throw new Error(+ `${label} accepted a connect that omits the required "${spec.missingFieldHint}" field; ` ++ `validate_credentials is not being applied, so an incomplete setup would be stored ` ++ `and fail later at send time instead of in the form`+ );+ }++ if (isConnected(await statusFor(channel))) {+ throw new Error(`${label} rejected the incomplete credentials but still reports connected`);+ }+ console.log(`${LOG_PREFIX} D.4 ${channel}: incomplete credentials rejected`);+ });++ it(`D.5 ${channel} disconnect clears the stored connection`, async function () {+ this.timeout(60_000);+ await callOpenhumanRpc('openhuman.channels_connect', {+ channel,+ authMode: 'api_key',+ credentials: validCredentials,+ });+ if (!isConnected(await statusFor(channel))) {+ throw new Error(+ `precondition: ${label} should be connected before the disconnect under test`+ );+ }++ const out = await callOpenhumanRpc('openhuman.channels_disconnect', {+ channel,+ authMode: 'api_key',+ });+ expect(out.ok).toBe(true);++ if (isConnected(await statusFor(channel))) {+ throw new Error(+ `${label} disconnect returned ok but channels_status still reports it connected`+ );+ }+ console.log(`${LOG_PREFIX} D.5 ${channel}: disconnected`);+ });+ }+});diff --git a/app/test/playwright/helpers/chat-drive.ts b/app/test/playwright/helpers/chat-drive.tsnew file mode 100644index 0000000000..438d59c710--- /dev/null+++ b/app/test/playwright/helpers/chat-drive.ts@@ -0,0 +1,206 @@+/**+ * Drive a chat turn the way the product does, without touching the composer.+ *+ * Every turn in these specs goes out over `openhuman.channel_web_chat` — the+ * same RPC `chatService.sendChatMessage` calls (`src/services/chatService.ts:1631`).+ * Two reasons, and only the second is about a bug:+ *+ * 1. It separates what is under test from how the text got there. A spec about+ * stream routing or a parked gate should not fail because the composer+ * changed, and a composer regression should not be reported as a routing+ * one.+ * 2. `ComposerTextBridge` used to chain a synchronous `setState` per keystroke+ * past React's nested-update limit, so an automated driver typing at speed+ * took the chat surface to its error boundary+ * (`src/features/conversations/components/AssistantUiChat.composerSync.test.tsx`).+ * That is fixed and pinned by a unit test, but nothing here needs to depend+ * on it staying fixed.+ *+ * The one thing the RPC cannot invent is `client_id`: the core routes the+ * stream to the socket that id belongs to, so a made-up one runs the turn and+ * delivers it nowhere this page can see. We read the live socket id out of the+ * store (`src/store/socketSlice.ts`, exposed as `window.__OPENHUMAN_STORE__`),+ * and send from inside the page so the request carries the renderer's own+ * credentials.+ */+import { expect, type Page } from '@playwright/test';++const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'}`;++interface MockRequestEntry {+ method: string;+ url: string;+ body: string;+ timestamp: number;+}++/** Reset the mock backend's behaviours, state and request log. */+export async function resetMock(): Promise<void> {+ await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ });+}++/**+ * Set one behaviour key. The `{ key, value }` form is a single-key set on the+ * admin route (`scripts/mock-api/admin.mjs:99`) and is what every other spec in+ * this suite uses; the `{ behavior: {...} }` form merges a whole object.+ */+export async function setMockBehavior(key: string, value: string): Promise<void> {+ await fetch(`${MOCK_ADMIN_BASE}/__admin/behavior`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ key, value }),+ });+}++/**+ * Script the mock LLM by keyword (`scripts/mock-api/routes/llm.mjs:505-560`).+ * A rule may carry `toolCalls`, in which case the mock answers with+ * `finish_reason: "tool_calls"` — which is how a spec makes the agent call a+ * specific tool without a real model.+ */+export async function setKeywordRules(rules: unknown[]): Promise<void> {+ await setMockBehavior('llmKeywordRules', JSON.stringify(rules));+}++/** Every request the mock has served since the last reset, newest last. */+export async function mockRequests(): Promise<MockRequestEntry[]> {+ const res = await fetch(`${MOCK_ADMIN_BASE}/__admin/requests`);+ const payload = (await res.json()) as { data?: MockRequestEntry[] };+ return payload.data ?? [];+}++/** Upstream request bodies the mock has seen, as raw strings. */+export async function upstreamBodies(): Promise<string[]> {+ return (await mockRequests()).map(entry => entry.body).filter(body => Boolean(body));+}++/**+ * The socket id the core must route this page's streams to.+ *+ * `socket.byUser` is keyed by user id and can hold a `__pending__` entry before+ * the user resolves, so we take the first entry that is actually connected+ * rather than assuming a key.+ */+export async function connectedSocketId(page: Page): Promise<string | null> {+ return page.evaluate(() => {+ const store = (+ window as unknown as {+ __OPENHUMAN_STORE__?: {+ getState?: () => {+ socket?: { byUser?: Record<string, { status?: string; socketId?: string | null }> };+ };+ };+ }+ ).__OPENHUMAN_STORE__;+ const byUser = store?.getState?.().socket?.byUser ?? {};+ for (const entry of Object.values(byUser)) {+ if (entry?.status === 'connected' && entry.socketId) return entry.socketId;+ }+ return null;+ });+}++export async function waitForConnectedSocketId(page: Page, timeout = 30_000): Promise<string> {+ await expect+ .poll(async () => connectedSocketId(page), {+ timeout,+ message: 'the renderer never reported a connected socket, so no turn could be routed to it',+ })+ .not.toBeNull();+ return (await connectedSocketId(page)) as string;+}++/** The thread the UI currently has selected. */+export async function selectedThreadId(page: Page): Promise<string | null> {+ return page.evaluate(() => {+ const store = (+ window as unknown as {+ __OPENHUMAN_STORE__?: {+ getState?: () => { thread?: { selectedThreadId?: string | null } };+ };+ }+ ).__OPENHUMAN_STORE__;+ return store?.getState?.().thread?.selectedThreadId ?? null;+ });+}++export async function waitForSelectedThreadId(page: Page, timeout = 20_000): Promise<string> {+ await expect.poll(async () => selectedThreadId(page), { timeout }).not.toBeNull();+ return (await selectedThreadId(page)) as string;+}++/**+ * Call any core RPC from inside the page, with the renderer's own URL and+ * bearer token (seeded into localStorage by `seedBrowserCoreMode`).+ *+ * Deliberately not the Node-side `callCoreRpc` from `core-rpc.ts`: a turn sent+ * from Node would be a different client, and the stream would never reach this+ * page.+ */+export async function callRpcFromPage<T = unknown>(+ page: Page,+ method: string,+ params: Record<string, unknown>+): Promise<T> {+ return page.evaluate(+ async ({ method, params }) => {+ const url = window.localStorage.getItem('openhuman_core_rpc_url');+ const token = window.localStorage.getItem('openhuman_core_rpc_token');+ if (!url || !token) throw new Error('page has no core RPC url/token in localStorage');+ const response = await fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),+ });+ const payload = (await response.json()) as { result?: unknown; error?: { message?: string } };+ if (payload.error) throw new Error(`RPC ${method} failed: ${payload.error.message}`);+ return payload.result;+ },+ { method, params }+ ) as Promise<T>;+}++export interface SendOptions {+ /** 'interrupt' (default), 'steer', 'followup', 'collect', or 'parallel'. */+ queueMode?: string;+ runMode?: 'plan' | 'build';+}++/**+ * Send `message` on `threadId` as this page's user, and return once the core+ * has accepted it. The turn then streams to this page over the socket exactly+ * as a typed message would.+ */+export async function sendTurn(+ page: Page,+ threadId: string,+ message: string,+ options: SendOptions = {}+): Promise<void> {+ const clientId = await waitForConnectedSocketId(page);+ await callRpcFromPage(page, 'openhuman.channel_web_chat', {+ client_id: clientId,+ thread_id: threadId,+ message,+ source: 'type',+ ...(options.queueMode ? { queue_mode: options.queueMode } : {}),+ ...(options.runMode ? { run_mode: options.runMode } : {}),+ });+}++/** Create a thread from the sidebar and return its id. */+export async function startNewThread(page: Page): Promise<string> {+ const previous = await selectedThreadId(page);+ const sidebar = page.getByTestId('new-thread-sidebar-button');+ if (await sidebar.isVisible().catch(() => false)) {+ await sidebar.click({ force: true });+ } else {+ await page.getByTestId('new-thread-button').click({ force: true });+ }+ await expect.poll(async () => selectedThreadId(page), { timeout: 20_000 }).not.toBe(previous);+ return waitForSelectedThreadId(page);+}diff --git a/app/test/playwright/specs/chat-durable-reply.spec.ts b/app/test/playwright/specs/chat-durable-reply.spec.tsnew file mode 100644index 0000000000..459eb24651--- /dev/null+++ b/app/test/playwright/specs/chat-durable-reply.spec.ts@@ -0,0 +1,148 @@+/**+ * Durable agent reply — losing the stream costs a repaint, not the answer.+ *+ * Matrix 4.2.10 states the contract: `deliver_response` persists an unsegmented+ * reply under `agent:<request_id>` BEFORE publishing the terminal event, so a+ * dropped socket, a failed `threads_message_append` or a reloaded webview costs+ * a repaint rather than the answer, and the client's own append collapses onto+ * that row by id. Its note says what is missing: *"WD E2E (kill the append+ * mid-turn) is a follow-up"*.+ *+ * The existing layers cover the two ends. RU+ * (`web_chat/reply_persistence_tests.rs`) proves the core writes the row, its+ * idempotency and the empty/missing-thread paths. VU+ * (`providers/__tests__/ChatRuntimeProvider.test.tsx`) proves the mirrored id+ * and the refetch — against a mocked client. Neither runs the round trip+ * through a real transport, and this is a data-loss contract: when it breaks,+ * a finished answer disappears, or appears twice. Nothing errors either way.+ *+ * Two instruments, deliberately different:+ *+ * 1. A reload mid-stream. Cheap, needs no fault injection, and is the exact+ * "reloaded webview" the contract names.+ * 2. Failing one real `threads_message_append` over the wire. The renderer+ * posts that RPC itself (`src/services/api/threadApi.ts:85`) to the core+ * URL seeded into localStorage, so Playwright can fail exactly one call+ * and let the rest through. There is no fault-injection hook on the core+ * side and none is needed.+ *+ * "Exactly once" is the assertion in both cases, not "present". A broken+ * collapse-by-id shows up as two copies of the answer, which no "is it there"+ * check would catch.+ */+import { expect, type Page, test } from '@playwright/test';++import {+ resetMock,+ sendTurn,+ setMockBehavior,+ waitForSelectedThreadId,+} from '../helpers/chat-drive';+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';++const USER_ID = 'pw-chat-durable-reply';++const PROMPT = 'DURABLE-REPLY-PROMPT';+/** A distinctive tail so the settled reply is unmistakable in the transcript. */+const TAIL = 'DURABLE-TAIL-MARKER';++/**+ * Long enough that a reload lands mid-stream rather than after it. `safeDelayMs`+ * in the mock clamps to 1000ms, so the length comes from the chunk count.+ */+const SLOW_STREAM = [+ ...Array.from({ length: 14 }, (_, i) => ({ text: `durable${i} `, delayMs: 1000 })),+ { text: TAIL, delayMs: 1000 },+ { finish: 'stop' },+];++async function openChat(page: Page): Promise<void> {+ await bootAuthenticatedPage(page, USER_ID, '/chat');+ await dismissWalkthroughIfPresent(page);+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });+}++/** How many times the settled reply's tail appears in the transcript. */+async function tailOccurrences(page: Page): Promise<number> {+ return page.evaluate(marker => {+ const root = document.querySelector('#root');+ const text = root?.textContent ?? '';+ return text.split(marker).length - 1;+ }, TAIL);+}++test.describe.configure({ timeout: 180_000 });++test.describe('Durable agent reply', () => {+ test.beforeEach(async () => {+ await resetMock();+ await setMockBehavior('llmStreamScript', JSON.stringify(SLOW_STREAM));+ await setMockBehavior('llmStreamChunkDelayMs', '1000');+ });++ test('a reload mid-stream still ends with the answer, exactly once', async ({ page }) => {+ await openChat(page);+ const threadId = await waitForSelectedThreadId(page);+ await sendTurn(page, threadId, PROMPT);++ // Wait for real streamed tokens, so the reload genuinely lands mid-turn and+ // this is not a race with an empty transcript.+ await expect(page.getByText('durable0', { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });+ await expect(+ page.getByText(TAIL, { exact: false }),+ 'the reload must happen BEFORE the reply settles, or this proves nothing'+ ).toHaveCount(0);++ await page.reload();+ await dismissWalkthroughIfPresent(page);+ await page.goto(`/#/chat/${threadId}`);++ // The core wrote the reply before announcing it, so the reopened thread has+ // it even though this page never saw `chat_done`.+ await expect(page.getByText(TAIL, { exact: false }).last()).toBeVisible({ timeout: 90_000 });+ await expect+ .poll(async () => tailOccurrences(page), {+ timeout: 20_000,+ message: 'the recovered reply must collapse onto one row, not duplicate it',+ })+ .toBe(1);+ });++ test('a failed threads_message_append does not lose the answer', async ({ page }) => {+ await openChat(page);+ const threadId = await waitForSelectedThreadId(page);++ // Fail exactly one append, then get out of the way. Anything else on this+ // endpoint — and every later append — goes through untouched, so what is+ // under test is the recovery, not a crippled client.+ let failed = 0;+ await page.route(+ url => url.pathname.endsWith('/rpc'),+ async route => {+ const body = route.request().postData() ?? '';+ if (failed === 0 && body.includes('openhuman.threads_message_append')) {+ failed += 1;+ await route.fulfill({+ status: 500,+ contentType: 'application/json',+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 0,+ error: { code: -32000, message: 'injected append failure' },+ }),+ });+ return;+ }+ await route.continue();+ }+ );++ await sendTurn(page, threadId, PROMPT);++ await expect(page.getByText(TAIL, { exact: false }).last()).toBeVisible({ timeout: 120_000 });+ expect(failed, 'the injected failure never fired, so this case proved nothing').toBe(1);+ await expect.poll(async () => tailOccurrences(page), { timeout: 20_000 }).toBe(1);+ });+});diff --git a/app/test/playwright/specs/chat-parallel-turns.spec.ts b/app/test/playwright/specs/chat-parallel-turns.spec.tsnew file mode 100644index 0000000000..054fc75a7a--- /dev/null+++ b/app/test/playwright/specs/chat-parallel-turns.spec.ts@@ -0,0 +1,146 @@+/**+ * Two turns in flight at once — across threads, and forked inside one.+ *+ * Matrix 4.2.4 is 🟡 with *"dedicated WD E2E is a follow-up"*. Its RU coverage+ * (`web_chat/web_tests.rs`) drives concurrent same-/cross-thread dispatch and+ * cooperative cancellation; its VU coverage (`chatRuntimeSlice`,+ * `ChatRuntimeProvider`) drives the parallel-lane routing through the slice.+ * Both are real, and neither has two live sockets.+ *+ * This is deliberately NOT in `chat-thread-isolation.spec.ts`, which owns the+ * adjacent surface. That file has exactly one turn in flight in every case —+ * thread B is idle throughout — and a routing bug that keys a stream by "the+ * selected thread" instead of by thread id is invisible with one stream and+ * catastrophic with two: the second turn's tokens land in whichever thread the+ * user happens to be looking at. It also drives its turns by typing, which+ * these do not (see `helpers/chat-drive.ts`).+ *+ * Both cases need per-turn content, so the mock is scripted with keyword rules+ * carrying their own `streamScript` rather than the global `llmStreamScript`+ * (which would hand both turns the same text and make them indistinguishable).+ */+import { expect, type Locator, type Page, test } from '@playwright/test';++import {+ resetMock,+ selectedThreadId,+ sendTurn,+ setKeywordRules,+ startNewThread,+ waitForSelectedThreadId,+} from '../helpers/chat-drive';+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';++const USER_ID = 'pw-chat-parallel-turns';++const ALPHA_PROMPT = 'ALPHA-TURN please';+const BRAVO_PROMPT = 'BRAVO-TURN please';++/** `safeDelayMs` clamps to 1000ms, so the run length comes from chunk count. */+function slowScript(prefix: string, chunks: number): unknown[] {+ return [+ ...Array.from({ length: chunks }, (_, i) => ({ text: `${prefix}${i} `, delayMs: 1000 })),+ { finish: 'stop' },+ ];+}++const RULES = [+ { keyword: 'ALPHA-TURN', streamScript: slowScript('alpha', 18) },+ { keyword: 'BRAVO-TURN', streamScript: slowScript('bravo', 18) },+];++const stopButton = (page: Page): Locator => page.getByTestId('stop-generation-button');++async function openChat(page: Page): Promise<void> {+ await bootAuthenticatedPage(page, USER_ID, '/chat');+ await dismissWalkthroughIfPresent(page);+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });+}++/** Whole-transcript text, for contiguity assertions a locator cannot express. */+async function transcriptText(page: Page): Promise<string> {+ return page.evaluate(() => document.querySelector('#root')?.textContent ?? '');+}++test.describe.configure({ timeout: 180_000 });++test.describe('Concurrent turns', () => {+ test.beforeEach(async () => {+ await resetMock();+ await setKeywordRules(RULES);+ });++ test('two threads streaming at once keep their own tokens', async ({ page }) => {+ await openChat(page);++ const threadA = await waitForSelectedThreadId(page);+ await sendTurn(page, threadA, ALPHA_PROMPT);+ await expect(page.getByText('alpha0', { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });++ const threadB = await startNewThread(page);+ expect(threadB, 'the second thread must be a different thread').not.toBe(threadA);+ await sendTurn(page, threadB, BRAVO_PROMPT);++ // Both turns are now genuinely in flight. B is selected, so B's tokens are+ // what this viewport may show — and only B's.+ await expect(page.getByText('bravo0', { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });+ await expect(+ page.getByText('alpha0', { exact: false }),+ "the other thread's live tokens must not bleed into this one"+ ).toHaveCount(0);+ await expect(stopButton(page), 'B has its own turn to stop').toBeVisible({ timeout: 15_000 });++ // Switch back while BOTH are still running: A must show its own stream,+ // unaffected by the fact that a second turn started after it.+ const rowA = page.getByTestId(`thread-row-${threadA}`);+ await expect(rowA).toBeVisible({ timeout: 15_000 });+ await rowA.click({ force: true });+ await expect.poll(async () => selectedThreadId(page), { timeout: 15_000 }).toBe(threadA);++ await expect(page.getByText('alpha0', { exact: false }).last()).toBeVisible({+ timeout: 20_000,+ });+ await expect(+ page.getByText('bravo0', { exact: false }),+ 'a turn started on another thread must never render here'+ ).toHaveCount(0);+ });++ test('two turns forked inside one thread do not interleave into one message', async ({+ page,+ }) => {+ await openChat(page);+ const threadId = await waitForSelectedThreadId(page);++ // `queue_mode: 'parallel'` is the product's own name for this — the other+ // modes ('interrupt' is the default, plus 'steer' / 'followup' / 'collect')+ // would make this a supersede or a queue, not a fork+ // (`web_chat/schemas.rs`, the `queue_mode` input).+ await sendTurn(page, threadId, ALPHA_PROMPT, { queueMode: 'parallel' });+ await expect(page.getByText('alpha0', { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });+ await sendTurn(page, threadId, BRAVO_PROMPT, { queueMode: 'parallel' });++ await expect(page.getByText('bravo0', { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });++ // Presence is not the assertion — two lanes folded into one bubble would+ // still contain both strings. Contiguity is: if the lanes interleaved,+ // `alpha0 alpha1 alpha2` could not survive as a run.+ await expect+ .poll(async () => transcriptText(page), {+ timeout: 90_000,+ message: 'the forked lanes interleaved instead of rendering as separate runs',+ })+ .toContain('alpha0 alpha1 alpha2');+ await expect+ .poll(async () => transcriptText(page), { timeout: 90_000 })+ .toContain('bravo0 bravo1 bravo2');+ });+});diff --git a/app/test/playwright/specs/chat-plan-review.spec.ts b/app/test/playwright/specs/chat-plan-review.spec.tsnew file mode 100644index 0000000000..3829669432--- /dev/null+++ b/app/test/playwright/specs/chat-plan-review.spec.ts@@ -0,0 +1,222 @@+/**+ * Plan-mode review — the live turn really parks, and the user's decision+ * really releases it.+ *+ * Matrix 4.2.7 is ✅ on RU + RI + VU, and the note says why that is not enough:+ * *"WD E2E (agent-driven park flow) tracked as follow-up"*. The three existing+ * layers each own one end of the mechanism and none of them owns the join:+ *+ * RU `agent/plan_review/gate.rs` — the oneshot parks, resolves, TTL-rejects.+ * RI `tests/json_rpc_e2e.rs` — `plan_review_decide` answers.+ * VU `aui/PlanReviewPart.test.tsx` — the card renders and calls the RPC.+ *+ * What nothing covers is a REAL turn held open on an in-memory oneshot+ * (`PlanReviewGate`, one per process, not a database row) while a browser paints+ * a card from a socket event, and released when that card's button resolves it.+ * Every one of those pieces can pass its own test while the turn stays parked+ * forever — and a parked turn is silent. No error, no log line saying why; the+ * user watches a spinner that never ends.+ *+ * Turns are driven over `openhuman.channel_web_chat` (see `helpers/chat-drive.ts`),+ * never by typing, so a composer change cannot be reported as a gate failure.+ *+ * The agent is scripted through the mock's keyword rules. Stage 1 matches the+ * prompt and answers with a `request_plan_review` tool call; stage 2 matches the+ * tool's own result string, which the core fixes verbatim+ * (`agent/plan_review/tool.rs`: "approved: the user approved the plan…",+ * "rejected: the user rejected the plan…", "revise: the user requested changes…").+ * That is what makes the approve/reject assertions real rather than cosmetic:+ * the branch the gate took has to reach the model for the next stage to fire.+ */+import { expect, type Locator, type Page, test } from '@playwright/test';++import {+ resetMock,+ selectedThreadId,+ sendTurn,+ setKeywordRules,+ startNewThread,+ upstreamBodies,+ waitForSelectedThreadId,+} from '../helpers/chat-drive';+import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';++const USER_ID = 'pw-chat-plan-review';++const PROMPT = 'PLANME rebuild the index';+const SUMMARY = 'PLAN-SUMMARY-MARKER';+const EXECUTED = 'PLAN-EXECUTED-MARKER';+const ABANDONED = 'PLAN-ABANDONED-MARKER';+const REVISED = 'PLAN-REVISED-MARKER';+const FEEDBACK = 'FEEDBACK-MARKER-do-it-in-two-steps';++/** The core's own wording for each resolution, as the tool hands it back. */+const APPROVED_RESULT = 'approved: the user approved';+const REJECTED_RESULT = 'rejected: the user rejected';+const REVISE_RESULT = 'revise: the user requested changes';++const RULES = [+ {+ keyword: 'PLANME',+ toolCalls: [+ {+ name: 'request_plan_review',+ arguments: { summary: SUMMARY, steps: ['read the index', 'rewrite it'] },+ },+ ],+ },+ { keyword: APPROVED_RESULT, content: EXECUTED },+ { keyword: REJECTED_RESULT, content: ABANDONED },+ { keyword: REVISE_RESULT, content: REVISED },+];++const planCard = (page: Page): Locator => page.getByTestId('plan-review-card');+const approveButton = (page: Page): Locator =>+ page.locator('[data-analytics-id="plan-review-approve-once"]');+const rejectButton = (page: Page): Locator =>+ page.locator('[data-analytics-id="plan-review-deny"]');+const reviseButton = (page: Page): Locator =>+ page.locator('[data-analytics-id="plan-review-approve-always"]');+const sendFeedbackButton = (page: Page): Locator =>+ page.locator('[data-analytics-id="plan-review-send-feedback-submit"]');+const stopButton = (page: Page): Locator => page.getByTestId('stop-generation-button');++async function openChat(page: Page): Promise<void> {+ await bootAuthenticatedPage(page, USER_ID, '/chat');+ await dismissWalkthroughIfPresent(page);+ await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });+}++/** Send the scripted prompt and wait until the turn is genuinely parked. */+async function parkAReview(page: Page): Promise<string> {+ const threadId = await waitForSelectedThreadId(page);+ await sendTurn(page, threadId, PROMPT);+ await expect(planCard(page), 'the scripted plan review never reached the browser').toBeVisible({+ timeout: 60_000,+ });+ return threadId;+}++/** True once any upstream request body carries `needle`. */+async function upstreamSaw(needle: string): Promise<boolean> {+ return (await upstreamBodies()).some(body => body.includes(needle));+}++// Same reasoning as chat-thread-isolation.spec.ts: the first browser spec of a+// shard pays the app's cold start, and these turns additionally wait on a real+// parked gate. The assertions are unchanged; only the budget moves.+test.describe.configure({ timeout: 120_000 });++test.describe('Plan-mode review', () => {+ test.beforeEach(async () => {+ await resetMock();+ await setKeywordRules(RULES);+ });++ test('a parked review holds the turn open and shows the plan, with no answer yet', async ({+ page,+ }) => {+ await openChat(page);+ await parkAReview(page);++ // The plan the agent asked about, not a generic card.+ await expect(planCard(page).getByText(SUMMARY, { exact: false })).toBeVisible({+ timeout: 15_000,+ });+ // The turn is still running — this is the property a unit test cannot hold.+ await expect(stopButton(page), 'a parked turn is still in flight').toBeVisible({+ timeout: 15_000,+ });+ // And the agent has NOT proceeded. If the gate failed open, stage 2 would+ // already have fired and this marker would be on screen.+ await expect(page.getByText(EXECUTED, { exact: false })).toHaveCount(0);+ expect(+ await upstreamSaw(APPROVED_RESULT),+ 'nothing was approved, so no approval result may have reached the model'+ ).toBe(false);+ });++ test('Approve resumes the same turn and the agent executes', async ({ page }) => {+ await openChat(page);+ await parkAReview(page);++ await approveButton(page).click({ force: true });++ // The released turn runs stage 2 and finishes in the same thread.+ await expect(+ page.getByText(EXECUTED, { exact: false }).last(),+ 'approving must resume the parked turn, not merely dismiss its card'+ ).toBeVisible({ timeout: 60_000 });+ expect(+ await upstreamSaw(APPROVED_RESULT),+ 'the approve resolution must reach the model as the tool result'+ ).toBe(true);+ await expect(planCard(page)).toHaveCount(0);+ });++ test('Reject resumes the turn and the agent does not execute', async ({ page }) => {+ await openChat(page);+ await parkAReview(page);++ await rejectButton(page).click({ force: true });++ await expect(page.getByText(ABANDONED, { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });+ // The assertion that makes approve and reject different things rather than+ // two ways to close a card: the approval wording must never have been sent.+ expect(+ await upstreamSaw(REJECTED_RESULT),+ 'the reject resolution must reach the model as the tool result'+ ).toBe(true);+ expect(+ await upstreamSaw(APPROVED_RESULT),+ 'a rejected plan must never hand the model an approval'+ ).toBe(false);+ await expect(page.getByText(EXECUTED, { exact: false })).toHaveCount(0);+ });++ test('Revise sends the typed feedback to the model', async ({ page }) => {+ await openChat(page);+ await parkAReview(page);++ await reviseButton(page).click({ force: true });+ const feedback = page.getByTestId('plan-review-feedback');+ await expect(feedback).toBeVisible({ timeout: 10_000 });+ // A plain textarea the user types into, not the assistant-ui composer.+ await feedback.fill(FEEDBACK);+ await sendFeedbackButton(page).click({ force: true });++ await expect(page.getByText(REVISED, { exact: false }).last()).toBeVisible({ timeout: 60_000 });+ // "The textarea accepted text" is worthless if the text never leaves. The+ // point of this case is the payload, not the affordance.+ expect(+ await upstreamSaw(FEEDBACK),+ 'the revision feedback must reach the model, not just the card'+ ).toBe(true);+ });++ test('a parked review stays with its own thread across a switch', async ({ page }) => {+ await openChat(page);+ const threadA = await parkAReview(page);++ await startNewThread(page);+ await expect.poll(async () => selectedThreadId(page), { timeout: 15_000 }).not.toBe(threadA);+ await expect(+ planCard(page),+ 'a review parked on another thread must not offer a decision here'+ ).toHaveCount(0);++ const rowA = page.getByTestId(`thread-row-${threadA}`);+ await expect(rowA).toBeVisible({ timeout: 15_000 });+ await rowA.click({ force: true });+ await expect.poll(async () => selectedThreadId(page), { timeout: 15_000 }).toBe(threadA);++ // Still parked, and still decidable — coming back must not have orphaned it.+ await expect(planCard(page)).toBeVisible({ timeout: 20_000 });+ await approveButton(page).click({ force: true });+ await expect(page.getByText(EXECUTED, { exact: false }).last()).toBeVisible({+ timeout: 60_000,+ });+ });+});