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
chore(test): remove skipped e2e specs and update coverage matrix
Steven Enamakelb96a83f682b1
diff --git a/app/scripts/e2e-run-all-flows.sh b/app/scripts/e2e-run-all-flows.shindex 889da632ab..2bceb57b17 100755--- a/app/scripts/e2e-run-all-flows.sh+++ b/app/scripts/e2e-run-all-flows.sh@@ -259,7 +259,6 @@ if should_run_suite "chat"; thenrun "test/e2e/specs/chat-harness-send-stream.spec.ts" "chat-send-stream" "chat"run "test/e2e/specs/chat-harness-cancel.spec.ts" "chat-cancel" "chat"run "test/e2e/specs/chat-harness-scroll-render.spec.ts" "chat-scroll-render" "chat"- run "test/e2e/specs/chat-harness-subagent.spec.ts" "chat-subagent" "chat"run "test/e2e/specs/chat-harness-wallet-flow.spec.ts" "chat-wallet" "chat"run "test/e2e/specs/chat-tool-call-flow.spec.ts" "chat-tool-call" "chat"run "test/e2e/specs/chat-multi-tool-round.spec.ts" "chat-multi-tool" "chat"@@ -313,7 +312,6 @@ if should_run_suite "webhooks"; thenecho "## Running suite: webhooks"run "test/e2e/specs/webhooks-ingress-flow.spec.ts" "webhooks-ingress" "webhooks"run "test/e2e/specs/webhooks-tunnel-flow.spec.ts" "webhooks-tunnel" "webhooks"- run "test/e2e/specs/harness-channel-bridge-flow.spec.ts" "harness-channel-bridge" "webhooks"run "test/e2e/specs/harness-composio-tool-flow.spec.ts" "harness-composio-tool" "webhooks"_mini_summary "webhooks"fidiff --git a/app/test/e2e/specs/agent-harness-behaviors.spec.ts b/app/test/e2e/specs/agent-harness-behaviors.spec.tsindex 42df64c46b..b27691c95b 100644--- a/app/test/e2e/specs/agent-harness-behaviors.spec.ts+++ b/app/test/e2e/specs/agent-harness-behaviors.spec.ts@@ -2,12 +2,11 @@* Agent-harness behaviors — approval gate, subagent clarification, inference* phases, and the tool timeline, driven through the real web-chat stack.*- * Pattern source of truth: `chat-harness-subagent.spec.ts` (orchestrator →- * subagent delegation, Redux polling via `__OPENHUMAN_STORE__`) and- * `chat-harness-subagent-continue.spec.ts` (clarification continuation). This- * spec reuses their proven flow: start a fresh thread, send a prompt, drive the- * mock LLM with `llmForcedResponses`, and assert against the live Redux runtime- * slice + the rendered DOM.+ * This spec starts fresh threads, drives the mock LLM with+ * `llmForcedResponses`, and asserts against the live Redux runtime slice and+ * rendered DOM. Subagent clarification continuation is also exercised by the+ * separate `chat-harness-subagent-continue.spec.ts`; that browser flow is+ * currently skipped under #6389 and is not pass evidence.** Approval gate notes (verified against the codebase, not the issue text):* - `ApprovalGate` installs by default under the desktop shell and parks@@ -126,8 +125,7 @@ async function readTimeline(threadId: string): Promise<TimelineEntry[]> {}, threadId)) as TimelineEntry[];}-/** Start a brand-new chat thread and return its id. Mirrors the new-thread- * flow proven in `chat-harness-subagent.spec.ts`. */+/** Start a brand-new chat thread and return its id. */async function startNewThread(): Promise<string> {await browser.waitUntil(async () => await chatMounted(), {timeout: 15_000,diff --git a/app/test/e2e/specs/chat-harness-subagent.spec.ts b/app/test/e2e/specs/chat-harness-subagent.spec.tsdeleted file mode 100644index da3125a8bb..0000000000--- a/app/test/e2e/specs/chat-harness-subagent.spec.ts+++ /dev/null@@ -1,295 +0,0 @@-/**- * Chat harness — orchestrator → subagent flow.- *- * The default chat agent after onboarding is the **orchestrator**- * (`crates/openhuman-core/src/channels/providers/web.rs::pick_target_agent_id`).- * Its `[subagents] allowlist = [...]` section synthesises one delegated archetype tool- * per archetype at build time (see- * `crates/openhuman-core/src/tools/orchestrator_tools.rs`). When the LLM calls- * `research` (or any other delegated archetype tool), the tool dispatches- * to a sub-agent which runs the agent harness loop a level deeper —- * which means the LLM gets hit at least once more for the sub-agent.- *- * Scripting: `llmKeywordRules` (content-addressed, never depleted).- * A prior version of this spec used the `llmForcedResponses` FIFO but- * that queue drains one entry per `/chat/completions` regardless of who- * called (#4517): the sub-agent's own harness loop plus any ancillary- * summarisation/memory-prep call shifts responses out of order and the- * scripted final canary lands on the wrong turn (or never renders).- * Keyword rules route each call by a substring of its latest- * user/tool message, so extra calls that don't match any rule fall- * through to the mock's dynamic default — the scripted turns are never- * consumed by an off-turn caller.- *- * What this spec scripts and verifies:- *- * 1. Configure `llmKeywordRules` with three rules keyed on- * per-turn-unique tokens:- * A) orchestrator turn (user PROMPT) — emits `research` tool_call- * B) researcher turn (delegate prompt) — plain text finding- * C) orchestrator turn (tool result) — final synthesis (canary)- *- * 2. Send the user prompt and watch the runtime:- * UI:- * - The redux `chatRuntime.inferenceStatusByThread[<thread>]`- * transitions through `phase: 'subagent'` at some point.- * - `chatRuntime.toolTimelineByThread[<thread>]` records an- * entry whose `id` starts with `<thread>:subagent:`.- * - Or the async delegation acknowledgement renders in the- * conversation (the durable signal after the parent turn ends).- * - The final orchestrator text (canary) renders in the DOM.- *- * Rust:- * - IN_FLIGHT clears after `chat_done`.- *- * Mock backend:- * - The mock LLM received at least 2 POSTs to- * `/openai/v1/chat/completions` (orchestrator + sub-agent).- *- * Workspace:- * - The persisted thread JSONL contains the final canary text.- */-import { waitForApp } from '../helpers/app-helpers';-import {- chatMounted,- clickByTitle,- clickSend,- getSelectedThreadId,- hexEncodeThreadId,- typeIntoComposer,- waitForSocketConnected,-} from '../helpers/chat-harness';-import { callOpenhumanRpc } from '../helpers/core-rpc';-import { textExists, visibleTextExists } from '../helpers/element-helpers';-import { resetApp } from '../helpers/reset-app';-import { navigateViaHash } from '../helpers/shared-flows';-import { getRequestLog, setMockBehavior, startMockServer, stopMockServer } from '../mock-server';--const USER_ID = 'e2e-chat-harness-subagent';-// Per-turn tokens chosen so pickProbeText's substring match routes each-// call to exactly one rule regardless of any extra ancillary-// tool/context/summary call the harness may issue on top of the three-// happy-path turns.-const PROMPT = 'Please delegate a llama-research task and return the marker.';-const DELEGATE_PROMPT = 'Return the coded marker phrase.';-const RESEARCHER_REPLY = 'The researcher trace signal is FORTY-TWO.';-const CANARY_FINAL = 'subagent-canary-final-7afe2';-const ASYNC_DELEGATION_ACK = 'Accepted async sub-agent';--// Content-addressed keyword rules — never depleted, immune to extra-// ancillary /chat/completions calls (#4517).-const KEYWORD_RULES = [- // Sub-agent turn — dispatch_subagent renders the arg as "Task:\n<arg>"- // (archetype_delegation.rs render_structured_handoff), so DELEGATE_PROMPT- // surfaces verbatim in the researcher's user message.- { keyword: 'coded marker phrase', content: RESEARCHER_REPLY },- // Orchestrator's post-delegation turn — the sub-agent's output is handed- // back as the `role: tool` message content- // (dispatch.rs `ToolResult::success(outcome.output)`).- { keyword: 'researcher trace signal', content: `Done. The result is: ${CANARY_FINAL}` },- // Orchestrator's initial turn — the fire-and-forget thread-title-gen- // call (threadSlice.ts, tools: None) sees the same probe, but- // chat_with_system consumes `content` and ignores unexpected tool_calls,- // so a delegation-triggering rule here is safe for both callers.- {- keyword: 'llama-research',- content: 'Delegating to researcher.',- toolCalls: [- {- id: 'call_research_1',- name: 'delegate_to',- arguments: JSON.stringify({ agent: 'research', prompt: DELEGATE_PROMPT }),- },- ],- },-];--interface RuntimeSnapshot {- phase?: string;- activeSubagent?: string;- timelineIds: string[];- timelineNames: string[];-}--async function snapshotRuntime(threadId: string): Promise<RuntimeSnapshot> {- return (await browser.execute((tid: string) => {- const winAny = window as unknown as { __OPENHUMAN_STORE__?: { getState: () => unknown } };- const state = winAny.__OPENHUMAN_STORE__?.getState() as- | {- chatRuntime?: {- inferenceStatusByThread?: Record<string, { phase?: string; activeSubagent?: string }>;- toolTimelineByThread?: Record<string, Array<{ id?: string; name?: string }>>;- };- }- | undefined;- const status = state?.chatRuntime?.inferenceStatusByThread?.[tid];- const timeline = state?.chatRuntime?.toolTimelineByThread?.[tid] ?? [];- return {- phase: status?.phase,- activeSubagent: status?.activeSubagent,- timelineIds: timeline.map(e => e?.id ?? ''),- timelineNames: timeline.map(e => e?.name ?? ''),- };- }, threadId)) as RuntimeSnapshot;-}--async function hasRenderedSubagentTimeline(): Promise<boolean> {- return (await browser.execute(() => {- // The assistant-ui transcript renders a delegation as a sub-agent card and- // any other tool as a tool-call card.- const rows = Array.from(- document.querySelectorAll(- '[data-testid="assistant-ui-subagent-call"], [data-testid="assistant-ui-tool-call"]'- )- );- return rows.some(row => {- const text = row.textContent ?? '';- return /Research|Researching|subagent/i.test(text);- });- })) as boolean;-}--describe('Chat harness — orchestrator → subagent flow', () => {- before(async function beforeSuite() {- this.timeout(90_000);- await startMockServer();- await waitForApp();- // clearAuthSession drops any session token a prior chat-harness spec in- // this shard left behind, so the orchestrator/sub-agent run starts from a- // clean signed-in state rather than a polluted one (the source of the- // intermittent "final canary never arrives" failures).- await resetApp(USER_ID, { clearAuthSession: true });- setMockBehavior('llmKeywordRules', JSON.stringify(KEYWORD_RULES));- // Faster streaming for non-tool-call responses so this spec doesn't- // need 30s of patience for three full streams.- setMockBehavior('llmStreamChunkDelayMs', '10');- });-- after(async () => {- setMockBehavior('llmKeywordRules', '');- setMockBehavior('llmStreamChunkDelayMs', '');- await stopMockServer();- });-- // TODO(#6389): orchestrator final synthesis is lost after the TinyAgents update.- it.skip(// https://github.com/tinyhumansai/openhuman/issues/6389- 'orchestrator delegates to researcher and produces the final canary', async function () {- this.timeout(90_000);- await navigateViaHash('/chat');- await browser.waitUntil(async () => await chatMounted(), {- timeout: 15_000,- timeoutMsg: 'Conversations did not mount',- });- expect(await clickByTitle('New thread', 8_000)).toBe(true);-- const threadId = (await browser.waitUntil(async () => await getSelectedThreadId(), {- timeout: 8_000,- timeoutMsg: 'thread.selectedThreadId never populated',- })) as string;- expect(typeof threadId).toBe('string');-- await typeIntoComposer(PROMPT);- const socketReady = await waitForSocketConnected(30_000);- if (!socketReady) {- console.warn('[chat-harness-subagent] socket did not connect within 30 s — send may fail');- }- expect(- await browser.waitUntil(async () => await clickSend(), {- timeout: 5_000,- timeoutMsg: 'Send button never enabled',- })- ).toBe(true);-- // Watch the runtime: at some point during the turn the phase- // should flip to 'subagent' and a `subagent:researcher` timeline- // entry should appear.- let sawSubagentPhase = false;- let sawSubagentTimeline = false;- let sawAsyncDelegationAck = false;- const deadline = Date.now() + 45_000;- while (Date.now() < deadline) {- const snap = await snapshotRuntime(threadId);- if (snap.phase === 'subagent') sawSubagentPhase = true;- if (- snap.timelineIds.some(id => id.includes(':subagent:')) ||- snap.timelineNames.some(n => n.startsWith('subagent:'))- ) {- sawSubagentTimeline = true;- }- sawAsyncDelegationAck =- sawAsyncDelegationAck || (await visibleTextExists(ASYNC_DELEGATION_ACK));- if ((sawSubagentPhase && sawSubagentTimeline) || sawAsyncDelegationAck) break;- if (await visibleTextExists(CANARY_FINAL)) {- sawSubagentTimeline = sawSubagentTimeline || (await hasRenderedSubagentTimeline());- sawAsyncDelegationAck =- sawAsyncDelegationAck || (await visibleTextExists(ASYNC_DELEGATION_ACK));- break;- }- await browser.pause(200);- }-- sawSubagentTimeline = sawSubagentTimeline || (await hasRenderedSubagentTimeline());-- // At least one delegation signal must have fired. Async delegation- // completes the parent tool call immediately, so its phase/timeline can- // disappear before the 200 ms poll; the acknowledgement remains visible.- expect(sawSubagentPhase || sawSubagentTimeline || sawAsyncDelegationAck).toBe(true);-- // Final canary must land in the DOM after the orchestrator wraps up.- await browser.waitUntil(async () => await textExists(CANARY_FINAL), {- timeout: 30_000,- timeoutMsg: 'orchestrator never produced the final canary text',- });-- // IN_FLIGHT must drain after chat_done.- await browser.waitUntil(- async () => {- const snap = await callOpenhumanRpc<{ result: { entries: Array<unknown> } }>(- 'openhuman.test_support_in_flight_chats',- {}- );- return snap.ok && (snap.result?.result?.entries?.length ?? 0) === 0;- },- { timeout: 10_000, timeoutMsg: 'IN_FLIGHT never cleared after orchestrator finished' }- );- });-- // TODO(#6389): this assertion depends on the skipped final-synthesis turn above.- it.skip(// https://github.com/tinyhumansai/openhuman/issues/6389- 'the mock LLM saw multiple chat-completions requests (parent + sub-agent)', async () => {- const log = getRequestLog() as Array<{ method: string; url: string; body?: string }>;- const llmHits = log.filter(- r => r.method === 'POST' && r.url.includes('/openai/v1/chat/completions')- );- // Orchestrator turn 1 (emits tool_call) + sub-agent turn + orchestrator turn 2 = 3.- // Accept ≥2 to stay robust against orchestrator-skipping or tool-loop- // optimisations that fold the final synthesis into the tool response.- expect(llmHits.length).toBeGreaterThanOrEqual(2);- });-- // TODO(#6389): depends on the missing orchestrator final synthesis.- it.skip(// https://github.com/tinyhumansai/openhuman/issues/6389- 'persisted thread file records the final orchestrator text', async () => {- const threadId = await getSelectedThreadId();- expect(typeof threadId).toBe('string');- const relPath = `memory/conversations/threads/${hexEncodeThreadId(threadId as string)}.jsonl`;-- let content = '';- // The orchestrator's final synthesis may take extra time to persist:- // the agent harness flushes the JSONL asynchronously after the stream- // completes. Allow up to 30s for disk write to land.- const deadline = Date.now() + 30_000;- while (Date.now() < deadline) {- const read = await callOpenhumanRpc<{ result: { content_utf8: string } }>(- 'openhuman.test_support_read_workspace_file',- { rel_path: relPath, max_bytes: 131_072 }- );- if (read.ok && read.result?.result?.content_utf8) {- content = read.result.result.content_utf8;- if (content.includes(CANARY_FINAL)) break;- }- await browser.pause(500);- }- expect(content).toContain(CANARY_FINAL);- });-});diff --git a/app/test/e2e/specs/harness-channel-bridge-flow.spec.ts b/app/test/e2e/specs/harness-channel-bridge-flow.spec.tsdeleted file mode 100644index bf093d263c..0000000000--- a/app/test/e2e/specs/harness-channel-bridge-flow.spec.ts+++ /dev/null@@ -1,790 +0,0 @@-// @ts-nocheck-/**- * Harness — Cross-channel bridge flow (WS-D spec 4).- *- * Exercises the full cross-channel loop: Telegram inbound messages feeding- * the agent harness tool-call pipeline, and outbound Telegram replies produced- * by the core. Also covers the lighter-weight "web chat referencing channel- * state" scenario and a concurrency stress scenario.- *- * Infrastructure prerequisites (WS-A + WS-B must be merged):- * - Mock Telegram Bot API routes: /bot<token>/getMe, /bot<token>/getUpdates,- * /bot<token>/sendMessage, /bot<token>/sendChatAction, etc.- * - OPENHUMAN_TELEGRAM_API_BASE env var override so the in-process core- * points at the mock server rather than api.telegram.org.- * - Admin endpoints: POST /__admin/telegram/inject-update,- * GET /__admin/telegram/sent, POST /__admin/telegram/reset.- * - mock-server.ts re-exports: injectTelegramUpdate, getTelegramSentMessages,- * resetTelegramMock.- *- * Scenarios:- * CB1 — Telegram message creates a cron job- * CB2 — Telegram message triggers a composio action (GMAIL_GET_MAIL)- * CB3 — Telegram-driven memory recall- * CB4 — Web chat references Telegram state (lightweight keyword check)- * CB5 — Channel inbound during a running chat (concurrency stress)- *- * Tool name corrections (verified across WS-D 1-3 agent):- * - "cron_add" (not cron_create)- * - "cron_remove" (not cron_delete)- * - "memory_recall"- * - "web_search_tool" (not web_search)- * - Composio: tool name = "composio", action name in function.name- *- * Connect payload shape (from crates/openhuman-core/src/channels/controllers/schemas.rs):- * { channel: "telegram", authMode: "bot_token", credentials: { bot_token: "..." } }- *- * Observation strategy:- * - LLM forced-response queue drives multi-turn sequences.- * - Outbound Telegram messages are asserted via getTelegramSentMessages().- * - Cron creation is confirmed via oracle RPC (openhuman.cron_list).- * - Composio execute is confirmed via mock request log.- *- * Concurrency note (CB5):- * The in-process core serialises agent turns per-thread (one active run at a- * time per thread) but a Telegram inbound message creates a new thread, so- * it CAN run concurrently with an ongoing web chat turn. CB5 documents the- * actual behaviour with a TODO if the core queues rather than parallelises.- */-import { waitForApp } from '../helpers/app-helpers';-import {- approvePendingToolCall,- chatMounted,- clickByTitle,- clickSend,- getSelectedThreadId,- typeIntoComposer,- waitForAssistantReplyContaining,- waitForSocketConnected,-} from '../helpers/chat-harness';-import { callOpenhumanRpc } from '../helpers/core-rpc';-import { textExists } from '../helpers/element-helpers';-import { resetApp } from '../helpers/reset-app';-import { navigateViaHash } from '../helpers/shared-flows';-import {- buildTelegramUpdate,- connectTelegramBot,- disconnectTelegramBot,- injectTelegramUpdate as tgInject,- resetTelegramMock as tgReset,- waitForTelegramReply,-} from '../helpers/telegram';-import {- clearRequestLog,- getRequestLog,- resetMockBehavior,- setMockBehavior,- startMockServer,- stopMockServer,-} from '../mock-server';--const LOG_PREFIX = '[ChannelBridge]';-const USER_ID = 'e2e-harness-channel-bridge-flow';--// ----------------------------------------------------------------------------// Telegram test fixtures-// -----------------------------------------------------------------------------const TEST_BOT_TOKEN = 'e2e-test-bot-token-12345';-const TEST_CHAT_ID = 1001;-const TEST_USER_ID = 2001;-const TEST_BOT_USERNAME = 'e2e_test_bot';--// ----------------------------------------------------------------------------// Oracle helpers-// -----------------------------------------------------------------------------/** List cron jobs via oracle RPC. */-async function listCronJobs(): Promise<Array<{ id?: string; name?: string; schedule?: string }>> {- const out = await callOpenhumanRpc('openhuman.cron_list', {});- if (!out.ok) {- console.warn(`${LOG_PREFIX} cron_list RPC failed: ${JSON.stringify(out)}`);- return [];- }- const result = (out.result as { result?: unknown } | undefined)?.result ?? out.result;- return Array.isArray(result) ? result : [];-}--// ----------------------------------------------------------------------------// Telegram channel setup helpers-// -----------------------------------------------------------------------------/** Connect the Telegram channel via the shared telegram helper.- * Requires WS-A (mock getMe endpoint) + WS-B (OPENHUMAN_TELEGRAM_API_BASE). */-async function connectTelegramChannel(): Promise<boolean> {- console.log(`${LOG_PREFIX} connectTelegramChannel: calling connectTelegramBot`);- try {- const result = await connectTelegramBot({ botToken: TEST_BOT_TOKEN });- if (!result.ok) {- console.warn(- `${LOG_PREFIX} connectTelegramChannel: failed — ${result.error ?? result.message}. ` +- `This is expected if OPENHUMAN_TELEGRAM_API_BASE is not set (WS-B not merged) ` +- `or if the mock Telegram routes are not in place (WS-A not merged).`- );- return false;- }- console.log(- `${LOG_PREFIX} connectTelegramChannel: connected (restartRequired=${result.restartRequired})`- );- if (result.restartRequired) {- console.warn(- `${LOG_PREFIX} connectTelegramChannel: config saved but live listener requires a core restart; ` +- `using web-chat fallback for Telegram inbound assertions`- );- return false;- }- return true;- } catch (err) {- console.warn(`${LOG_PREFIX} connectTelegramChannel: threw — ${err}`);- return false;- }-}--/** Disconnect the Telegram channel. Best-effort — called in after(). */-async function disconnectTelegramChannel(): Promise<void> {- try {- await disconnectTelegramBot();- console.log(`${LOG_PREFIX} disconnectTelegramChannel: done`);- } catch (err) {- console.warn(`${LOG_PREFIX} disconnectTelegramChannel: best-effort failed — ${err}`);- }-}--/**- * Wrapper around the shared `waitForTelegramReply` that returns `undefined`- * instead of throwing on timeout — keeps scenarios non-fatal when- * WS-A/WS-B infrastructure is not yet merged.- */-async function tryWaitForTelegramReply(- chatId: number,- contains: string,- timeoutMs = 20_000-): Promise<Record<string, unknown> | undefined> {- try {- return (await waitForTelegramReply({ chatId, contains, timeoutMs })) as Record<string, unknown>;- } catch (err) {- console.warn(`${LOG_PREFIX} tryWaitForTelegramReply: ${err}`);- return undefined;- }-}--// ----------------------------------------------------------------------------// Navigation helper-// -----------------------------------------------------------------------------async function navigateChatAndSend(prompt: string): Promise<void> {- await navigateViaHash('/chat');- await browser.waitUntil(async () => await chatMounted(), {- timeout: 15_000,- timeoutMsg: 'Conversations panel did not mount',- });- expect(await clickByTitle('New thread', 8_000)).toBe(true);- await browser.waitUntil(async () => await getSelectedThreadId(), {- timeout: 8_000,- timeoutMsg: 'thread.selectedThreadId never populated',- });-- await typeIntoComposer(prompt);- const socketReady = await waitForSocketConnected(30_000);- if (!socketReady) {- console.warn(`${LOG_PREFIX} socket did not connect within 30s — send may fail`);- }- expect(- await browser.waitUntil(async () => await clickSend(), {- timeout: 15_000,- timeoutMsg: 'Send button never enabled',- })- ).toBe(true);- console.log(`${LOG_PREFIX} Web chat: sent "${prompt.slice(0, 80)}"`);-}--// ----------------------------------------------------------------------------// Suite-// -----------------------------------------------------------------------------describe('Harness - Cross-channel bridge flow', () => {- before(function () {- this.skip(); // https://github.com/senamakel/openhuman/issues/233 — this Telegram-owned spec is scheduled for the channel test-ownership cleanup.- });- // Track whether Telegram connect succeeded so we can skip Telegram-dependent- // assertions gracefully when WS-A/WS-B infra is not yet in place.- let telegramConnected = false;-- before(async function beforeSuite() {- this.timeout(120_000);- console.log(`${LOG_PREFIX} Suite setup: starting mock server`);- await startMockServer();- await waitForApp();- await resetApp(USER_ID);- // Configure Telegram mock defaults.- setMockBehavior('telegramBotUsername', TEST_BOT_USERNAME);- setMockBehavior('telegramPollDelayMs', '0');-- // Reset any leftover Telegram mock state.- try {- await tgReset();- } catch {- console.warn(- `${LOG_PREFIX} resetTelegramMock failed — WS-A Telegram mock routes may not be merged yet`- );- }-- // Connect Telegram channel. If WS-A/WS-B infrastructure is missing, this- // will fail gracefully and telegramConnected stays false, allowing CB4 (web- // chat only) to still run.- telegramConnected = await connectTelegramChannel();- if (!telegramConnected) {- console.warn(- `${LOG_PREFIX} Telegram channel not connected. Scenarios CB1-CB3 and CB5 will ` +- `assert Telegram-independent checks only. ` +- `TODO(channels): merge WS-A (mock Telegram routes) and WS-B (API base URL override).`- );- }-- console.log(`${LOG_PREFIX} Suite setup complete (telegramConnected=${telegramConnected})`);- });-- afterEach(async function afterEachScenario() {- // Reset Telegram mock and request log between scenarios.- clearRequestLog();- resetMockBehavior();- try {- await tgReset();- } catch {- // best-effort- }- // Re-apply Telegram defaults after resetMockBehavior clears them.- setMockBehavior('telegramBotUsername', TEST_BOT_USERNAME);- setMockBehavior('telegramPollDelayMs', '0');- setMockBehavior('llmStreamChunkDelayMs', '10');- });-- after(async function afterSuite() {- console.log(`${LOG_PREFIX} Suite teardown`);- await disconnectTelegramChannel();- resetMockBehavior();- await stopMockServer();- console.log(`${LOG_PREFIX} Suite teardown complete`);- });-- // ── CB1 — Telegram message creates a cron job ─────────────────────────────-- it('CB1 — Telegram message "set up a daily standup reminder at 9am" triggers scheduling and bot replies', async function () {- this.timeout(120_000);- console.log(`${LOG_PREFIX} CB1: begin`);-- const CANARY_CRON = 'canary-cb1-cron-standup';-- // Two-turn forced response: first turn schedules through the supported- // scheduling skill, second turn confirms.- const FORCED = [- {- content: '',- toolCalls: [- {- id: 'call_use_skill_cron_add_cb1',- name: 'use_skill',- arguments: JSON.stringify({- skill: 'scheduling',- tool: 'cron',- args: {- action: 'add',- name: 'daily_standup_reminder',- schedule: { kind: 'cron', expr: '0 9 * * *' },- prompt: 'standup reminder',- enabled: true,- },- }),- },- ],- },- { content: `I created a daily 9am standup reminder for you. ${CANARY_CRON}` },- ];- setMockBehavior('llmForcedResponses', JSON.stringify(FORCED));- setMockBehavior('llmStreamChunkDelayMs', '10');-- // Snapshot cron state before.- const beforeJobs = await listCronJobs();- console.log(- `${LOG_PREFIX} CB1: pre-inject cron jobs: ${beforeJobs.map(j => j.name ?? j.id).join(', ') || '(none)'}`- );-- if (telegramConnected) {- // (a) Inject the Telegram update.- const update = buildTelegramUpdate({- updateId: 1001,- chatId: TEST_CHAT_ID,- userId: TEST_USER_ID,- username: 'e2e_test_user',- text: 'set up a daily standup reminder at 9am',- });- console.log(`${LOG_PREFIX} CB1: injecting Telegram update`);- try {- await tgInject(update);- } catch (err) {- console.warn(- `${LOG_PREFIX} CB1: tgInject failed — ${err}. TODO(channels): WS-A not merged.`- );- }-- // (b) Wait for the outbound Telegram reply containing the confirmation.- // The Telegram provider polls getUpdates, feeds the harness, and sends- // the reply via sendMessage. Allow generous timeout for the poll cycle.- const tgReply = await tryWaitForTelegramReply(TEST_CHAT_ID, 'standup reminder', 20_000);- if (tgReply) {- console.log(`${LOG_PREFIX} CB1: Telegram reply confirmed — ${JSON.stringify(tgReply)}`);- expect(typeof tgReply.text === 'string' || typeof tgReply.body === 'string').toBe(true);- } else {- console.warn(- `${LOG_PREFIX} CB1: Telegram reply not found in sent messages — ` +- `the core may not have processed the injected update yet. ` +- `TODO(channels): verify getUpdates poll + agent dispatch pipeline.`- );- }- } else {- // Telegram not connected — skip inbound/outbound assertions and exercise- // only the LLM forced-response queue via the web chat path.- console.warn(- `${LOG_PREFIX} CB1: skipping Telegram injection (not connected). Running web-chat fallback.`- );- await navigateChatAndSend('set up a daily standup reminder at 9am');- expect(await approvePendingToolCall()).toBe(true);- await browser.waitUntil(async () => await textExists(CANARY_CRON), {- timeout: 60_000,- timeoutMsg: `CB1: cron-confirmation canary "${CANARY_CRON}" never appeared`,- });- }-- // (c) Oracle: check whether cron_add persisted the job in the in-process core.- let oracleConfirmed = false;- const oracleDeadline = Date.now() + 10_000;- while (Date.now() < oracleDeadline) {- const afterJobs = await listCronJobs();- const hasStandup = afterJobs.some(- j => j.name === 'daily_standup_reminder' || String(j.name ?? '').includes('standup')- );- if (hasStandup) {- oracleConfirmed = true;- console.log(`${LOG_PREFIX} CB1: oracle confirmed — cron_add persisted the job`);- break;- }- if (afterJobs.length > beforeJobs.length) {- oracleConfirmed = true;- console.log(- `${LOG_PREFIX} CB1: oracle confirmed by job count increase ` +- `(before=${beforeJobs.length}, after=${afterJobs.length})`- );- break;- }- await browser.pause(500);- }-- if (!oracleConfirmed) {- console.warn(- `${LOG_PREFIX} CB1: cron_add tool call issued but oracle did not see a new job. ` +- `TODO(channels): verify cron tool dispatch from Telegram inbound path.`- );- }-- // LLM request log: at least 2 completions turns (tool-call turn + final answer).- const log = getRequestLog() as Array<{ method: string; url: string }>;- const llmHits = log.filter(r => r.method === 'POST' && r.url.includes('/chat/completions'));- console.log(`${LOG_PREFIX} CB1: ${llmHits.length} LLM completion request(s) in mock log`);- // Best-effort — only assert when the LLM was actually called (web-chat fallback path).- if (llmHits.length > 0) {- expect(llmHits.length).toBeGreaterThanOrEqual(2);- }-- console.log(`${LOG_PREFIX} CB1: PASSED`);- });-- // ── CB2 — Telegram message triggers a composio action ─────────────────────-- it('CB2 — Telegram "check my gmail inbox" triggers GMAIL_GET_MAIL composio action and bot replies with subject lines', async function () {- this.timeout(120_000);- console.log(`${LOG_PREFIX} CB2: begin`);-- if (!telegramConnected) {- console.warn(- `${LOG_PREFIX} CB2: skipping Telegram/composio bridge assertion because the live ` +- `Telegram listener requires a core restart after channels_connect. The web-chat ` +- `Composio path is covered by harness-composio-tool-flow in this shard.`- );- this.skip(); // https://github.com/senamakel/tinychannels/issues/42 — Telegram listener restart remains upstream-owned.- }-- // Canned Gmail messages the mock Composio execute will return.- const GMAIL_MESSAGES = [- { id: 'msg-cb2-1', subject: 'Quarterly OKR Review', from: '[email protected]' },- { id: 'msg-cb2-2', subject: 'Deploy approval required', from: '[email protected]' },- ];- setMockBehavior(- 'composioExecuteResponse_GMAIL_GET_MAIL',- JSON.stringify({ messages: GMAIL_MESSAGES })- );-- const CANARY_GMAIL = 'canary-cb2-gmail-inbox';-- // Two-turn forced response: first emits GMAIL_GET_MAIL tool call, second- // relays the email subjects.- const FORCED = [- {- content: '',- toolCalls: [- {- id: 'call_gmail_get_mail_cb2',- name: 'GMAIL_GET_MAIL',- arguments: JSON.stringify({ max_results: 5 }),- },- ],- },- {- content: `You have 2 emails: "Quarterly OKR Review" from [email protected], "Deploy approval required" from [email protected]. ${CANARY_GMAIL}`,- },- ];- setMockBehavior('llmForcedResponses', JSON.stringify(FORCED));- setMockBehavior('llmStreamChunkDelayMs', '10');-- const update = buildTelegramUpdate({- updateId: 1002,- chatId: TEST_CHAT_ID,- userId: TEST_USER_ID,- username: 'e2e_test_user',- text: 'check my gmail inbox',- });- console.log(`${LOG_PREFIX} CB2: injecting Telegram update`);- try {- await tgInject(update);- } catch (err) {- console.warn(`${LOG_PREFIX} CB2: tgInject failed — ${err}. TODO(channels): WS-A not merged.`);- }-- // Wait for outbound Telegram reply containing a subject line.- const tgReply = await tryWaitForTelegramReply(TEST_CHAT_ID, 'OKR Review', 20_000);- if (tgReply) {- console.log(`${LOG_PREFIX} CB2: Telegram reply confirmed with subject line`);- } else {- const tgReply2 = await tryWaitForTelegramReply(TEST_CHAT_ID, 'Deploy approval', 5_000);- if (tgReply2) {- console.log(`${LOG_PREFIX} CB2: Telegram reply confirmed with second subject line`);- } else {- console.warn(- `${LOG_PREFIX} CB2: Telegram reply not found. ` +- `TODO(channels): verify Telegram channel → harness → Composio → reply pipeline.`- );- }- }-- // Composio execute: best-effort — assert if the log captured it.- const log = getRequestLog() as Array<{ method: string; url: string; body?: string }>;- const composioHit = log.find(- r => r.method === 'POST' && r.url.includes('/agent-integrations/composio/execute')- );- if (composioHit) {- console.log(`${LOG_PREFIX} CB2: composio execute confirmed in mock log`);- } else {- console.warn(- `${LOG_PREFIX} CB2: composio execute not in mock log — ` +- `core may route to real Composio API. ` +- `TODO(channels): verify composio mock routing from Telegram inbound path.`- );- }-- // LLM turns.- const llmHits = log.filter(r => r.method === 'POST' && r.url.includes('/chat/completions'));- console.log(`${LOG_PREFIX} CB2: ${llmHits.length} LLM completion request(s)`);- if (llmHits.length > 0) {- expect(llmHits.length).toBeGreaterThanOrEqual(2);- }-- console.log(`${LOG_PREFIX} CB2: PASSED`);- });-- // ── CB3 — Telegram-driven memory recall ───────────────────────────────────-- it('CB3 — Telegram "remember what we discussed about Atlas" triggers memory_recall and bot replies with canned content', async function () {- this.timeout(120_000);- console.log(`${LOG_PREFIX} CB3: begin`);-- // The memory store is not easily mockable from outside the core, so we- // use llmForcedResponses to drive both the tool call emission AND the- // final reply content regardless of what memory_recall actually returns.- const ATLAS_CANARY = 'canary-cb3-atlas-memory';- const ATLAS_TOKEN = 'Atlas Q4 infrastructure migration';-- const FORCED = [- {- content: '',- toolCalls: [- {- id: 'call_memory_recall_cb3',- name: 'memory_recall',- arguments: JSON.stringify({ namespace: 'global', query: 'Atlas' }),- },- ],- },- {- // Second turn: LLM synthesises a reply regardless of what memory_recall- // returned (could be real memories or an empty/error result).- content: `Based on my recall, we discussed ${ATLAS_TOKEN} and the team's migration plan for it. ${ATLAS_CANARY}`,- },- ];- setMockBehavior('llmForcedResponses', JSON.stringify(FORCED));- setMockBehavior('llmStreamChunkDelayMs', '10');-- if (telegramConnected) {- const update = buildTelegramUpdate({- updateId: 1003,- chatId: TEST_CHAT_ID,- userId: TEST_USER_ID,- username: 'e2e_test_user',- text: 'remember what we discussed about Atlas?',- });- console.log(`${LOG_PREFIX} CB3: injecting Telegram update`);- try {- await tgInject(update);- } catch (err) {- console.warn(- `${LOG_PREFIX} CB3: tgInject failed — ${err}. TODO(channels): WS-A not merged.`- );- }-- // Wait for outbound Telegram reply containing the Atlas token.- const tgReply = await tryWaitForTelegramReply(TEST_CHAT_ID, 'Atlas', 20_000);- if (tgReply) {- const replyText = String(tgReply.text ?? tgReply.body ?? '');- console.log(`${LOG_PREFIX} CB3: Telegram reply: "${replyText.slice(0, 120)}"`);- expect(replyText.includes('Atlas') || replyText.length > 0).toBe(true);- } else {- console.warn(- `${LOG_PREFIX} CB3: Telegram reply not found. ` +- `TODO(channels): verify memory_recall dispatch from Telegram inbound path.`- );- }- } else {- // Fallback: web chat.- console.warn(- `${LOG_PREFIX} CB3: skipping Telegram injection (not connected). Running web-chat fallback.`- );- await navigateChatAndSend('remember what we discussed about Atlas?');- await browser.waitUntil(async () => await textExists(ATLAS_CANARY), {- timeout: 60_000,- timeoutMsg: `CB3: memory-recall canary "${ATLAS_CANARY}" never appeared`,- });- expect(await waitForAssistantReplyContaining(ATLAS_TOKEN, { logPrefix: LOG_PREFIX })).toBe(- true- );- }-- // LLM log: memory_recall tool name should appear in one of the LLM requests- // (the tool-result message in turn 2 includes the function name).- const log = getRequestLog() as Array<{ method: string; url: string; body?: string }>;- const llmHits = log.filter(r => r.method === 'POST' && r.url.includes('/chat/completions'));- console.log(`${LOG_PREFIX} CB3: ${llmHits.length} LLM completion request(s)`);- if (llmHits.length > 0) {- expect(llmHits.length).toBeGreaterThanOrEqual(2);- }-- const memoryToolInLog = log.some(- r =>- r.method === 'POST' &&- r.url.includes('/chat/completions') &&- typeof r.body === 'string' &&- r.body.includes('"memory_recall"')- );- if (memoryToolInLog) {- console.log(`${LOG_PREFIX} CB3: "memory_recall" confirmed in LLM request log`);- } else {- console.warn(- `${LOG_PREFIX} CB3: "memory_recall" not found in LLM request bodies. ` +- `The tool call was emitted (forced response) but the tool-result message ` +- `format may not embed the function name. ` +- `TODO(channels): verify memory_recall tool-result message format.`- );- }-- console.log(`${LOG_PREFIX} CB3: PASSED`);- });-- // ── CB4 — Web chat references Telegram state ──────────────────────────────-- it('CB4 — Web chat "what messages came in on Telegram today" returns canned channel summary', async function () {- this.timeout(120_000);- console.log(`${LOG_PREFIX} CB4: begin`);-- // Lightweight scenario: no real cross-channel inspection required.- // Configure a keyword rule so the LLM returns a canned summary whenever- // the prompt contains "Telegram today".- const CHANNEL_SUMMARY = 'You received 3 messages on Telegram today: 2 from John, 1 from Alice.';- const CANARY_CHANNEL = 'canary-cb4-channel-summary';-- const KEYWORD_RULES = [- { keyword: 'Telegram today', content: `${CHANNEL_SUMMARY} ${CANARY_CHANNEL}` },- ];- setMockBehavior('llmKeywordRules', JSON.stringify(KEYWORD_RULES));- setMockBehavior('llmStreamChunkDelayMs', '10');-- // Send from the web chat (Telegram connect state is irrelevant here).- await navigateChatAndSend('what messages came in on Telegram today');-- // Wait for the canned summary to appear in the UI.- await browser.waitUntil(async () => await textExists(CANARY_CHANNEL), {- timeout: 60_000,- timeoutMsg: `CB4: channel-summary canary "${CANARY_CHANNEL}" never appeared`,- });- console.log(`${LOG_PREFIX} CB4: canary visible`);-- // Assert the full summary phrase is in the UI reply.- expect(await waitForAssistantReplyContaining('Telegram today', { logPrefix: LOG_PREFIX })).toBe(- true- );-- // LLM log: at least 1 completions request.- const log = getRequestLog() as Array<{ method: string; url: string }>;- const llmHits = log.filter(r => r.method === 'POST' && r.url.includes('/chat/completions'));- console.log(`${LOG_PREFIX} CB4: ${llmHits.length} LLM completion request(s)`);- expect(llmHits.length).toBeGreaterThanOrEqual(1);-- console.log(`${LOG_PREFIX} CB4: PASSED`);- });-- // ── CB5 — Channel inbound during a running chat ────────────────────────────-- it('CB5 — Telegram inbound while web chat is streaming completes both independently', async function () {- this.timeout(180_000);- console.log(`${LOG_PREFIX} CB5: begin`);-- // Web chat stream: configure a slow multi-chunk stream so the Telegram- // injection can happen while the web chat turn is still in progress.- const WEB_CANARY = 'canary-cb5-web-reply';- const WEB_REPLY_PIECES = [- 'Starting the web reply… ',- 'still streaming… ',- `${WEB_CANARY}`,- ' — end of web reply.',- ];- const WEB_STREAM_SCRIPT = WEB_REPLY_PIECES.map(piece => ({ text: piece, delayMs: 300 })).concat(- [{ finish: 'stop' }]- );- setMockBehavior('llmStreamScript', JSON.stringify(WEB_STREAM_SCRIPT));- setMockBehavior('llmStreamChunkDelayMs', '10');-- // Telegram turn: configure a forced response for the injected update.- // Because the mock LLM handles one request queue, we must interleave:- // after the stream script is consumed, the forced response kicks in.- //- // NOTE: The mock LLM serves llmStreamScript first (for the web chat turn)- // and llmForcedResponses for any subsequent calls. The Telegram inbound- // creates a NEW thread so it results in a fresh LLM call — the forced- // response will be consumed for that call.- const TG_CANARY = 'canary-cb5-telegram-reply';- const TELEGRAM_FORCED = [{ content: `Telegram ping received — pong! ${TG_CANARY}` }];-- // We set up the Telegram forced response AFTER kicking off the web chat- // stream, to avoid consuming it before the web chat turn starts.-- // Step 1: navigate to web chat and start sending (does NOT await reply yet).- await navigateViaHash('/chat');- await browser.waitUntil(async () => await chatMounted(), {- timeout: 15_000,- timeoutMsg: 'Conversations panel did not mount',- });- expect(await clickByTitle('New thread', 8_000)).toBe(true);- await browser.waitUntil(async () => await getSelectedThreadId(), {- timeout: 8_000,- timeoutMsg: 'thread.selectedThreadId never populated',- });-- await typeIntoComposer('start a long web reply for concurrency test');- const socketReady = await waitForSocketConnected(30_000);- if (!socketReady) {- console.warn(`${LOG_PREFIX} CB5: socket did not connect within 30s`);- }- const sent = await browser.waitUntil(async () => await clickSend(), {- timeout: 15_000,- timeoutMsg: 'Send button never enabled',- });- expect(sent).toBe(true);- console.log(`${LOG_PREFIX} CB5: web chat message sent — stream started`);-- // Step 2: While streaming, set up the Telegram forced response and inject- // a Telegram update. The web chat stream is ongoing (300ms per chunk × 4- // = ~1.2s total) so there is a short window to inject before it finishes.- setMockBehavior('llmForcedResponses', JSON.stringify(TELEGRAM_FORCED));-- if (telegramConnected) {- const update = buildTelegramUpdate({- updateId: 1005,- chatId: TEST_CHAT_ID,- userId: TEST_USER_ID,- username: 'e2e_test_user',- text: 'ping from Telegram during web chat',- });- console.log(`${LOG_PREFIX} CB5: injecting Telegram update while web chat is streaming`);- try {- await tgInject(update);- console.log(`${LOG_PREFIX} CB5: Telegram update injected`);- } catch (err) {- console.warn(- `${LOG_PREFIX} CB5: tgInject failed — ${err}. ` +- `TODO(channels): merge WS-A mock Telegram routes.`- );- }- } else {- console.warn(- `${LOG_PREFIX} CB5: Telegram not connected — skipping concurrent injection. ` +- `TODO(channels): merge WS-A + WS-B for full concurrency test. ` +- `Asserting web chat completion only.`- );- }-- // Step 3: Wait for the web chat reply to complete (stream all chunks).- await browser.waitUntil(async () => await textExists(WEB_CANARY), {- timeout: 90_000,- timeoutMsg: `CB5: web-reply canary "${WEB_CANARY}" never appeared`,- });- console.log(`${LOG_PREFIX} CB5: web chat reply completed`);-- // (a) Web chat assertion: the full streaming reply arrived intact.- expect(- await waitForAssistantReplyContaining('web reply', {- logPrefix: LOG_PREFIX,- timeoutMs: 5_000,- })- ).toBe(true);-- // (b) Telegram reply assertion (only when connected).- if (telegramConnected) {- // Allow extra time — the Telegram turn may have been queued behind the- // web chat stream or running concurrently depending on core scheduling.- const tgReply = await tryWaitForTelegramReply(TEST_CHAT_ID, 'pong', 20_000);- if (tgReply) {- console.log(`${LOG_PREFIX} CB5: Telegram reply confirmed — concurrent processing works`);- } else {- // TODO(channels): If the core serialises agent runs globally (not per-thread),- // the Telegram turn may be queued until the web chat stream finishes.- // In that case the reply still arrives but with an extra delay — the 20s- // timeout above should cover it. If it consistently doesn't, the core may- // need to be verified that Telegram messages start a separate thread.- console.warn(- `${LOG_PREFIX} CB5: Telegram reply did not appear within 20s of web-chat completion. ` +- `TODO(channels): verify concurrent agent run scheduling — ` +- `Telegram inbound creates a new thread, so it should run independently of the ` +- `web chat thread's in-flight run.`- );- // Non-fatal: the web chat assertion already passed, documenting the concurrency gap.- }- }-- // LLM log summary.- const log = getRequestLog() as Array<{ method: string; url: string }>;- const llmHits = log.filter(r => r.method === 'POST' && r.url.includes('/chat/completions'));- console.log(- `${LOG_PREFIX} CB5: ${llmHits.length} LLM completion request(s) total ` +- `(expected ≥1 for web chat${telegramConnected ? ' + ≥1 for Telegram' : ''})`- );- expect(llmHits.length).toBeGreaterThanOrEqual(1);-- console.log(`${LOG_PREFIX} CB5: PASSED`);- });-});diff --git a/app/test/playwright/specs/chat-harness-subagent.spec.ts b/app/test/playwright/specs/chat-harness-subagent.spec.tsdeleted file mode 100644index 999c2a77f3..0000000000--- a/app/test/playwright/specs/chat-harness-subagent.spec.ts+++ /dev/null@@ -1,406 +0,0 @@-import { expect, type Page, test } from '@playwright/test';--import { agentMessageText } from '../helpers/chat-locators';-import {- bootAuthenticatedPage,- callCoreRpc,- dismissWalkthroughIfPresent,- waitForAppReady,-} from '../helpers/core-rpc';--const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'}`;-const USER_ID = 'pw-chat-subagent';-const PROMPT = 'Research the answer to life and tell me a marker phrase.';-const CANARY_FINAL = 'subagent-canary-final-7afe2';-const RESEARCHER_REPLY = 'The researcher answer is 42.';-const PARENT_THINKING = 'Parent trace: delegate the factual lookup before synthesizing.';-const PARENT_NARRATION = 'I am delegating the factual lookup now.';-const CHILD_THINKING = 'Child trace: isolate the requested marker before replying.';-const KEYWORD_RESPONSES = [- { keyword: "Search the user's memory tree", content: 'No relevant memory.' },- {- keyword: PROMPT,- streamScript: [- { thinking: PARENT_THINKING },- { text: PARENT_NARRATION },- {- toolCall: {- id: 'call_research_1',- name: 'spawn_async_subagent',- arguments: JSON.stringify({ agent_id: 'researcher', prompt: 'Tell me a marker phrase' }),- },- },- { finish: 'tool_calls' },- ],- },- {- // `spawn_async_subagent` wraps the requested task in its background-run- // contract, so the latest child user message is the rendered handoff, not- // the raw tool argument.- keyword: 'Run this task without requiring attention from the parent or user',- streamScript: [{ thinking: CHILD_THINKING }, { text: RESEARCHER_REPLY }, { finish: 'stop' }],- },- {- // Detached completion is delivered to the parent as a fresh background- // notification turn; match that stable framing rather than depending on- // exactly how the result body is quoted inside it.- keyword: 'background sub-agent finished while you were busy',- streamScript: [- { thinking: 'Parent trace: verify the delegated finding and answer.' },- { text: `Done. The result is: ${CANARY_FINAL}` },- { finish: 'stop' },- ],- },-];--interface MockRequest {- body?: string;- method: string;- url: string;-}--async function resetMock(): Promise<void> {- await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({}),- });-}--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 }),- });-}--async function requests(): Promise<MockRequest[]> {- const response = await fetch(`${MOCK_ADMIN_BASE}/__admin/requests`);- const payload = (await response.json()) as { data?: MockRequest[] };- return Array.isArray(payload.data) ? payload.data : [];-}--async function openChat(page: Page): Promise<void> {- await bootAuthenticatedPage(page, USER_ID, '/chat');- await page.goto('/#/chat');- await waitForAppReady(page);- await dismissWalkthroughIfPresent(page);- await expect(page.getByTestId('chat-message-input')).toBeVisible();-}--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;- });-}--async function createNewThread(page: Page): Promise<string> {- const before = await selectedThreadId(page);- await dismissWalkthroughIfPresent(page);- const sidebarButton = page.getByTestId('new-thread-sidebar-button');- if (await sidebarButton.isVisible().catch(() => false)) {- await sidebarButton.click({ force: true });- } else {- await page.getByTestId('new-thread-button').click({ force: true });- }- const changed = await expect- .poll(- async () => {- const current = await selectedThreadId(page);- return current && current !== before ? current : null;- },- { timeout: 10_000 }- )- .not.toBeNull()- .then(- () => true,- () => false- );- const id = await selectedThreadId(page);- if (changed && id) return id;- if (id) return id;- if (before) return before;- throw new Error('selectedThreadId was not populated');-}--async function waitForSocketConnected(page: Page): Promise<void> {- await expect- .poll(- async () =>- page.evaluate(() => {- const store = (- window as unknown as {- __OPENHUMAN_STORE__?: {- getState?: () => { socket?: { byUser?: Record<string, { status?: string }> } };- };- }- ).__OPENHUMAN_STORE__;- const byUser = store?.getState?.().socket?.byUser ?? {};- return Object.values(byUser).some(entry => entry?.status === 'connected');- }),- { timeout: 30_000 }- )- .toBe(true);-}--async function sendMessage(page: Page, prompt: string): Promise<void> {- await waitForSocketConnected(page);- await dismissWalkthroughIfPresent(page);- await page.getByTestId('chat-message-input').fill(prompt);- await dismissWalkthroughIfPresent(page);- await expect(page.getByTestId('send-message-button')).toBeEnabled();- await page.getByTestId('send-message-button').click();-}--async function llmCompletionRequests(): Promise<MockRequest[]> {- const log = await requests();- return log.filter(- entry => entry.method === 'POST' && entry.url.includes('/openai/v1/chat/completions')- );-}--async function completionRequestCount(): Promise<number> {- return (await llmCompletionRequests()).length;-}--interface DiagnosticsSnapshot {- completionRequests: Array<{ probe: string; index: number }>;- matchedKeywords: string[];- selectedThreadId: string | null;- runtime: {- phase: string | null;- toolTimelineNames: string[];- toolTimelineIds: string[];- turnTranscriptTexts: Record<string, string[]>;- messageCount: number;- lastAssistantText: string | null;- };-}--// Captures the harness state the moment a strong assertion is about to time-// out so future CI failures expose request counts, consumed keyword matches,-// the active thread, and the chat runtime — instead of just "element not-// found." Required by issue #3469's RCA acceptance criteria.-async function diagnosticsSnapshot(page: Page): Promise<DiagnosticsSnapshot> {- const llmRequests = await llmCompletionRequests();- const completionRequests = llmRequests.map((entry, index) => {- let probe = '';- try {- const parsed = JSON.parse(entry.body ?? '{}') as {- messages?: Array<{ role?: string; content?: unknown }>;- };- const messages = Array.isArray(parsed.messages) ? parsed.messages : [];- for (let i = messages.length - 1; i >= 0; i -= 1) {- const m = messages[i];- if (!m || (m.role !== 'user' && m.role !== 'tool')) continue;- if (typeof m.content === 'string') {- probe = m.content;- break;- }- if (Array.isArray(m.content)) {- probe = m.content- .filter(- (c): c is { type: 'text'; text: string } =>- !!c &&- typeof c === 'object' &&- (c as { type?: string }).type === 'text' &&- typeof (c as { text?: unknown }).text === 'string'- )- .map(c => c.text)- .join(' ');- break;- }- }- } catch {- probe = '';- }- return { probe: probe.slice(0, 240), index };- });-- const matchedKeywords = completionRequests- .map(({ probe }) =>- KEYWORD_RESPONSES.find(rule => probe.toLowerCase().includes(rule.keyword.toLowerCase()))- )- .map(rule => (rule ? rule.keyword : '<no-match>'));-- const threadId = await selectedThreadId(page);-- const runtime = await page.evaluate(currentThreadId => {- const store = (- window as unknown as {- __OPENHUMAN_STORE__?: {- getState?: () => {- chatRuntime?: {- inferenceStatusByThread?: Record<string, { phase?: string }>;- toolTimelineByThread?: Record<string, Array<{ id?: string; name?: string }>>;- turnTranscriptsByThread?: Record<string, Record<string, Array<{ text?: string }>>>;- };- thread?: {- messagesByThread?: Record<string, Array<{ role?: string; content?: string }>>;- };- };- };- }- ).__OPENHUMAN_STORE__;- const state = store?.getState?.();- const phase =- currentThreadId && state?.chatRuntime?.inferenceStatusByThread?.[currentThreadId]?.phase- ? (state.chatRuntime.inferenceStatusByThread[currentThreadId].phase ?? null)- : null;- const timeline =- currentThreadId && state?.chatRuntime?.toolTimelineByThread?.[currentThreadId]- ? state.chatRuntime.toolTimelineByThread[currentThreadId]- : [];- const turnTranscripts =- currentThreadId && state?.chatRuntime?.turnTranscriptsByThread?.[currentThreadId]- ? state.chatRuntime.turnTranscriptsByThread[currentThreadId]- : {};- const messages =- currentThreadId && state?.thread?.messagesByThread?.[currentThreadId]- ? state.thread.messagesByThread[currentThreadId]- : [];- const lastAssistant = [...messages].reverse().find(m => m?.role === 'assistant');- return {- phase,- toolTimelineNames: timeline.map(entry => entry?.name ?? ''),- toolTimelineIds: timeline.map(entry => entry?.id ?? ''),- turnTranscriptTexts: Object.fromEntries(- Object.entries(turnTranscripts).map(([requestId, items]) => [- requestId,- items.map(item => item.text ?? ''),- ])- ),- messageCount: messages.length,- lastAssistantText:- typeof lastAssistant?.content === 'string' ? lastAssistant.content.slice(0, 240) : null,- };- }, threadId);-- return { completionRequests, matchedKeywords, selectedThreadId: threadId, runtime };-}--function formatDiagnostics(snapshot: DiagnosticsSnapshot): string {- return [- `selectedThreadId=${snapshot.selectedThreadId ?? '<null>'}`,- `completionRequestCount=${snapshot.completionRequests.length}`,- `matchedKeywords=${JSON.stringify(snapshot.matchedKeywords)}`,- `runtime.phase=${snapshot.runtime.phase ?? '<null>'}`,- `runtime.toolTimelineNames=${JSON.stringify(snapshot.runtime.toolTimelineNames)}`,- `runtime.turnTranscriptTexts=${JSON.stringify(snapshot.runtime.turnTranscriptTexts)}`,- `runtime.messageCount=${snapshot.runtime.messageCount}`,- `runtime.lastAssistantText=${JSON.stringify(snapshot.runtime.lastAssistantText)}`,- `completionProbes=${JSON.stringify(- snapshot.completionRequests.map(r => ({ i: r.index, probe: r.probe }))- )}`,- ].join('\n ');-}--test.describe('Chat Harness - Subagent', () => {- // Background delivery is system-authored and cannot be deterministically- // keyword-scripted; #6389 tracks the unresolved desktop final-synthesis case.- test.skip(true, 'https://github.com/tinyhumansai/openhuman/issues/6389');-- // On any test failure, attach the harness state (mock request log, matched- // keywords, selected thread, chat-runtime phase + tool timeline + last- // assistant text) as a Playwright artifact. Keeps the original Playwright- // assertion error intact while satisfying issue #3469's RCA requirement- // that future failures expose request counts, consumed forced/keyword- // responses, active thread id, and final chat-runtime state.- test.afterEach(async ({ page }, testInfo) => {- if (testInfo.status === 'passed' || testInfo.status === 'skipped') return;- if (page.isClosed()) return;- try {- const snapshot = await diagnosticsSnapshot(page);- await testInfo.attach('subagent-harness-diagnostics.txt', {- contentType: 'text/plain',- body: formatDiagnostics(snapshot),- });- await testInfo.attach('subagent-harness-diagnostics.json', {- contentType: 'application/json',- body: JSON.stringify(snapshot, null, 2),- });- } catch {- // Diagnostics are best-effort — never mask the real failure if the- // page/mock is already torn down (e.g. core crash mid-test).- }- });-- test('renders and rehydrates the full delegated-turn trace', async ({ page }) => {- test.setTimeout(150_000);-- await resetMock();- await setMockBehavior('llmForcedResponses', '');- await setMockBehavior('llmKeywordRules', JSON.stringify(KEYWORD_RESPONSES));- await setMockBehavior('llmStreamChunkDelayMs', '10');-- await openChat(page);- const threadId = await createNewThread(page);- await sendMessage(page, PROMPT);-- // Three LLM hits are expected: orchestrator-1 (delegates), researcher- // (returns RESEARCHER_REPLY), orchestrator-2 (returns CANARY_FINAL).- // The orchestrator no longer eagerly invokes the memory agent (PR #3521),- // so this is the full sequence — no extra calls should consume keyword- // rules out from under the next-expected matcher.- await expect.poll(completionRequestCount, { timeout: 90_000 }).toBeGreaterThanOrEqual(3);- await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 30_000 });-- // Re-assert after completion so the persisted message survives the- // turn-settlement transition rather than only being visible mid-stream.- await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 15_000 });-- // The trace belongs to assistant-ui's message parts—there is no parallel- // legacy timeline surface.- const finalMessage = page.getByTestId('agent-message').filter({ hasText: CANARY_FINAL }).last();- await expect(finalMessage).toBeVisible({ timeout: 15_000 });- // The final assistant part may contain only the synthesized answer; the- // delegated reasoning belongs to its preceding trace parts. The durable- // parent and child trails are asserted below after a reload, which is the- // stable contract regardless of whether the provider emits final-round- // reasoning as a separate disclosure.-- // Reloading removes the live socket and Redux stream. The same visual- // trace must rehydrate from persisted transcript/turn-state data.- await page.reload();- await waitForAppReady(page);- await page.goto('/#/chat');- const restoredThread = page.getByTestId(`thread-row-${threadId}`);- await expect(restoredThread).toBeVisible({ timeout: 15_000 });- await restoredThread.click({ force: true });- await expect.poll(() => selectedThreadId(page), { timeout: 15_000 }).toBe(threadId);- const derived = await callCoreRpc<unknown>('openhuman.threads_transcript_get', {- thread_id: threadId,- limit: 500,- });- expect(JSON.stringify(derived)).toContain(PARENT_THINKING);- // The parent's reasoning rehydrates into the static reasoning panel,- // settled to a "Thought…" label (never the old hard-coded "Reasoning").- const reasoningPanel = page.getByTestId('reasoning-panel').first();- await expect(reasoningPanel).toBeVisible({ timeout: 20_000 });- await expect(reasoningPanel.locator('[data-slot="reasoning-panel-resting-label"]')).toHaveText(- /^Thought( for \d|( briefly)?$)/- );- const restoredMessage = page- .getByTestId('agent-message')- .filter({ has: page.getByTestId('assistant-ui-subagent-call') })- .last();- await expect(restoredMessage).toBeVisible({ timeout: 20_000 });- const subagentCall = page.getByTestId('assistant-ui-subagent-call').first();- await expect(subagentCall).toBeVisible();- const subagentTrigger = subagentCall.getByRole('button').first();- await expect(subagentTrigger).toHaveAttribute('aria-expanded', 'false');- await expect(subagentCall.getByTestId('subagent-activity')).toHaveCount(0);- await subagentTrigger.click();- await expect(subagentTrigger).toHaveAttribute('aria-expanded', 'true');- await expect(subagentCall.getByTestId('subagent-activity')).toContainText(CHILD_THINKING);- await expect(subagentCall.getByTestId('subagent-activity')).toContainText(RESEARCHER_REPLY);- });-});diff --git a/app/test/playwright/specs/harness-channel-bridge-flow.spec.ts b/app/test/playwright/specs/harness-channel-bridge-flow.spec.tsdeleted file mode 100644index 59a4f2d25d..0000000000--- a/app/test/playwright/specs/harness-channel-bridge-flow.spec.ts+++ /dev/null@@ -1,151 +0,0 @@-import { expect, type Page, test } from '@playwright/test';--import { agentMessageText } from '../helpers/chat-locators';-import {- bootAuthenticatedPage,- dismissWalkthroughIfPresent,- waitForAppReady,-} from '../helpers/core-rpc';--const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'}`;-const USER_ID = 'pw-harness-channel-bridge';-const CANARY = 'canary-cb1-cron-standup';--async function resetMock(): Promise<void> {- await fetch(`${MOCK_ADMIN_BASE}/__admin/reset`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({}),- });-}--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 }),- });-}--async function openChat(page: Page): Promise<void> {- await bootAuthenticatedPage(page, USER_ID, '/chat');- await page.goto('/#/chat');- await waitForAppReady(page);- await dismissWalkthroughIfPresent(page);- await expect(page.getByTestId('chat-message-input')).toBeVisible();-}--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;- });-}--async function createNewThread(page: Page): Promise<string> {- const before = await selectedThreadId(page);- await dismissWalkthroughIfPresent(page);- const sidebarButton = page.getByTestId('new-thread-sidebar-button');- if (await sidebarButton.isVisible().catch(() => false)) {- await sidebarButton.click({ force: true });- } else {- await page.getByTestId('new-thread-button').click({ force: true });- }- const changed = await expect- .poll(- async () => {- const current = await selectedThreadId(page);- return current && current !== before ? current : null;- },- { timeout: 10_000 }- )- .not.toBeNull()- .then(- () => true,- () => false- );- const id = await selectedThreadId(page);- if (changed && id) return id;- if (id) return id;- if (before) return before;- throw new Error('selectedThreadId was not populated');-}--async function waitForSocketConnected(page: Page): Promise<void> {- await expect- .poll(- async () =>- page.evaluate(() => {- const store = (- window as unknown as {- __OPENHUMAN_STORE__?: {- getState?: () => { socket?: { byUser?: Record<string, { status?: string }> } };- };- }- ).__OPENHUMAN_STORE__;- const byUser = store?.getState?.().socket?.byUser ?? {};- return Object.values(byUser).some(entry => entry?.status === 'connected');- }),- { timeout: 30_000 }- )- .toBe(true);-}--async function sendMessage(page: Page, prompt: string): Promise<void> {- await waitForSocketConnected(page);- await dismissWalkthroughIfPresent(page);- await page.getByTestId('chat-message-input').fill(prompt);- await dismissWalkthroughIfPresent(page);- await expect(page.getByTestId('send-message-button')).toBeEnabled();- await page.getByTestId('send-message-button').click();-}--test.describe('Harness - Cross-channel bridge flow', () => {- test('web chat fallback path completes a channel-style two-turn sequence', async ({ page }) => {- await resetMock();- await setMockBehavior(- 'llmForcedResponses',- JSON.stringify([- {- content: '',- toolCalls: [- {- // Scheduling is the orchestrator's `scheduling` skill pack now- // (the scheduler_agent / schedule_task delegate is retired).- id: 'call_cron_add_cb1',- name: 'use_skill',- arguments: JSON.stringify({- skill: 'scheduling',- tool: 'cron',- args: {- action: 'add',- name: 'daily_standup_reminder',- schedule: { kind: 'cron', expr: '0 9 * * *' },- prompt: 'standup reminder',- enabled: true,- },- }),- },- ],- },- { content: `I created a daily 9am standup reminder for you. ${CANARY}` },- ])- );- await setMockBehavior('llmStreamChunkDelayMs', '10');-- await openChat(page);- await createNewThread(page);- await sendMessage(page, 'set up a daily standup reminder at 9am');-- await expect(agentMessageText(page, CANARY)).toBeVisible({ timeout: 60_000 });- await expect(- agentMessageText(page, /I created a daily 9am standup reminder for you\./i)- ).toBeVisible();- });-});diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 41c68062c3..9febfa15ed 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -110,8 +110,8 @@ pub(crate) async fn run_subagent_direct_with_native_context(// state) onto tokio's 2 MiB worker stack and abort with "thread// 'tokio-rt-worker' has overflowed its stack, fatal runtime error:// stack overflow" — observed at `[subagent_host] dispatching- // agent_id=<worker> ...` in the `chat-harness-subagent` Playwright- // lane crash. The inner `Box::pin`s around `run_typed_mode` and the+ // agent_id=<worker> ...` in the historical chat-harness subagent lane+ // crash (the browser spec is now skipped under #6389). The inner `Box::pin`s around `run_typed_mode` and the// child's tinyagents drive future further chunk the child's state so// a single sub-agent run can't blow the stack either.Box::pin(async move {diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rsindex a665d6c8ab..e3dcc53ece 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs@@ -572,15 +572,12 @@ fn unsigned_in_user_fails_probe() {/// `thread 'tokio-rt-worker' has overflowed its stack, fatal runtime/// error: stack overflow`.///-/// The deep ground-truth regression catcher for this is the-/// `chat-harness-subagent.spec.ts` Playwright spec, which exercises the-/// real orchestrator → researcher dispatch end-to-end (real provider-/// stream, real config load, real tool registry). The scripted unit-/// path here has much smaller per-frame state than production, so a-/// single stack size doesn't cleanly bracket boxed-vs-unboxed — we use-/// the loose 1 MiB worker stack as a smoke check that the dispatch-/// path remains poll-bounded after refactors. See `subagent_host/-/// ops.rs` `Box::pin` callsites for the structural fix.+/// The former desktop end-to-end regression flow is currently skipped under+/// #6389, so it is not current pass evidence. The scripted path here has much+/// smaller per-frame state than production, and a single stack size doesn't+/// cleanly bracket boxed-vs-unboxed — we use the loose 1 MiB worker stack as a+/// smoke check that the dispatch path remains poll-bounded after refactors.+/// See `subagent_host/ops.rs` `Box::pin` callsites for the structural fix.#[test]fn nested_subagent_dispatch_runs_on_a_constrained_worker_stack() {use async_trait::async_trait;diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 8c72fdcdce..1db1617de8 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -218,8 +218,8 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an| ID | Feature | Layer | Test path(s) | Status | Notes || ------ | --------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------- |-| 4.4.1 | Subagent Delegation | RI+WD | `tests/agent_harness_e2e.rs`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts` | ✅ | Orchestrator→agent_memory (`retrieve_memory`) delegation asserts ≥3 upstream calls, distinct subagent persona, no "Unknown tool:" |-| 4.4.2 | Subagent Clarification (input-required) | RI+WD | `tests/agent_harness_e2e.rs`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts`, `chat-harness-subagent-continue.spec.ts` | ✅ | Subagent question surfaced + reply completes turn; full `continue_subagent` resume covered by the continue spec |+| 4.4.1 | Subagent Delegation | RI+WD | `tests/agent_harness_e2e.rs::subagent_delegation_happy_path`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts::{transitions through subagent inference phases and clears to idle,records a complete tool timeline for a subagent turn}` | 🟡 | The active RPC test verifies `vision_agent` dispatch, a distinct child context, and final synthesis; the active browser tests verify the subagent phase and timeline. The former desktop final-synthesis flow is skipped under #6389, so its UI behavior remains unresolved. |+| 4.4.2 | Subagent Clarification (input-required) | RI+WD | `tests/agent_harness_e2e.rs::delegated_clarification_flow`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts::surfaces a subagent clarification question and accepts the user reply`, `crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs::continue_subagent_resumes_idle_durable_session_e2e`, `app/test/e2e/specs/chat-harness-subagent-continue.spec.ts` | ✅ | The active RPC and browser tests cover the surfaced question and user reply; the Rust tool test covers durable resume. The separate browser continuation spec is retained but skipped under #6389 and is not pass evidence. || 4.4.3 | Approval Gate — Approve | RI+WD | `tests/agent_harness_e2e.rs`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts` | ✅ | `approval_request` event → approve → tool executes (timeline `success`, file written) || 4.4.4 | Approval Gate — Deny | RI+WD | `tests/agent_harness_e2e.rs`, `app/test/e2e/specs/agent-harness-behaviors.spec.ts` | ✅ | Deny → tool not executed (timeline `error`, file unchanged), agent explains gracefully || 4.4.5 | Approval Gate — TTL Timeout | RI | `tests/agent_harness_e2e.rs` | ✅ | `OPENHUMAN_APPROVAL_TTL_SECS` (debug-only) → no decision → auto-deny |