Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Keep public interaction and runtime regression fixtures aligned
wyt39fd90ce9816
diff --git a/test/e2e/chat_e2e_attachment_order.spec.ts b/test/e2e/chat_e2e_attachment_order.spec.tsindex 84352f13..59259e04 100644--- a/test/e2e/chat_e2e_attachment_order.spec.ts+++ b/test/e2e/chat_e2e_attachment_order.spec.ts@@ -21,7 +21,11 @@ test('keeps image selection, bubble, persisted history and model pixels in orderconst bubbles = page.locator('#chat-history .chat-message.user');await expect(bubbles).toHaveCount(turn + 1);await expect(bubbles.nth(turn).locator('.chat-msg-attach .chat-attach-label')).toHaveText(names);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toHaveCount(turn + 1);+ // Completed history uses the regular message body after hydration, while+ // live replies use a streaming final slot. Count the visible replies in both.+ await expect(page.locator('#chat-history .chat-message.assistant', {+ hasText: 'Hello from the local E2E model.',+ })).toHaveCount(turn + 1);await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);await expect.poll(() => modelOrkas.modelRequests.length).toBe(turn + 1);const request = modelOrkas.modelRequests[turn] as any;diff --git a/test/e2e/chat_e2e_cli_recovery.spec.ts b/test/e2e/chat_e2e_cli_recovery.spec.tsindex 9b9ff07f..e5adc1e1 100644--- a/test/e2e/chat_e2e_cli_recovery.spec.ts+++ b/test/e2e/chat_e2e_cli_recovery.spec.ts@@ -120,7 +120,11 @@ test.describe('CLI Agent runtime settings', () => {const reply = page.locator('#chat-history .chat-message.assistant', {hasText: 'E2E_CLI_DEFAULT_OK',});- await expect(reply.locator('[data-role="final"]')).toBeVisible({ timeout: 30_000 });+ await expect(reply.locator('.chat-bubble > :is(.markdown-body, [data-role="final"])')).toBeVisible({ timeout: 30_000 });+ // This scenario inspects a completed task's persisted process output.+ // A streamed answer can be visible before canonical settlement replaces+ // the live process rail; wait for the real terminal UI before opening it.+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);const processRail = reply.locator('.stream-process');await expect(processRail).toBeVisible();@@ -306,7 +310,7 @@ test.describe('CLI Agent runtime settings', () => {relaunchedPage,`@${agentName} E2E_CODEX_RUNTIME_SETTINGS`,);- await expect(relaunchedPage.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toBeVisible({ timeout: 30_000 });const agentReplies = relaunchedPage.locator(@@ -367,7 +371,7 @@ test.describe('CLI Agent runtime settings', () => {await defaultPage.locator('#new-chat-btn').click();await sendNewChat(defaultPage, `@${agentName} E2E_CODEX_RUNTIME_DEFAULTS`);- await expect(defaultPage.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(defaultPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toBeVisible({ timeout: 30_000 });const defaultInvocation = cliOrkas.readCliState().invocations.at(-1);@@ -384,7 +388,7 @@ test.describe('CLI Agent runtime settings', () => {const gate = cliOrkas.cliStatePath + '.claude-stream-stage';writeFileSync(gate, '0');const cid = await sendNewChat(page, `@${name} E2E_CLAUDE_STREAM_BODY`);- const body = page.locator('#chat-history .chat-message.assistant [data-role="final"]');+ const body = page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body');// The CLI withholds both the full text record and result. A renderer// that paints only on completion cannot satisfy either prefix assertion.await expect(body).toContainText('First paragraph.', { timeout: 30_000 });@@ -399,8 +403,10 @@ test.describe('CLI Agent runtime settings', () => {await page.screenshot({ path: testInfo.outputPath('claude-streaming-body.png') });writeFileSync(gate, '2');await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);- await expect(body.locator('h2')).toHaveText('Report');- await expect(body.locator('p')).toHaveText(['First paragraph.', 'Second paragraph.']);+ const settledBody = page.locator('#chat-history .chat-message.assistant .chat-bubble')+ .locator(':scope > .markdown-body, :scope > [data-role="final"] > .markdown-body');+ await expect(settledBody.locator('h2')).toHaveText('Report');+ await expect(settledBody.locator('p')).toHaveText(['First paragraph.', 'Second paragraph.']);const saved = await cliOrkas.invoke<any>('conversations.history', { cid });expect(saved.history.filter((row: any) => row.from === agentId).map((row: any) => row.text)).toEqual(['## Report\n\nFirst paragraph.\n\nSecond paragraph.']);@@ -433,7 +439,7 @@ test.describe('CLI Agent runtime settings', () => {await page.locator('#new-chat-btn').click();await sendNewChat(page, `@${agentName} E2E_CLAUDE_MODEL_ALIAS`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLAUDE_MODEL_RESOLVED',})).toBeVisible({ timeout: 30_000 });expect(cliOrkas.readCliState().invocations.at(-1)).toMatchObject({@@ -512,7 +518,7 @@ test.describe('CLI failed-turn recovery', () => {const retry = reopened.locator('#chat-history .bubble-retry-btn').last();await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();await retry.click();- await expect(reopened.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(reopened.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_HERMES_FIRST_OK',})).toHaveCount(1, { timeout: 30_000 });await expect(reopened.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);@@ -562,7 +568,7 @@ test.describe('CLI failed-turn recovery', () => {await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();await retry.click();- await expect(relaunchedPage.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(relaunchedPage.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_RESUMED_WITHOUT_DUPLICATE_TOOL',})).toBeVisible({ timeout: 30_000 });const recovered = cliOrkas.readCliState();@@ -575,7 +581,7 @@ test.describe('CLI failed-turn recovery', () => {test('drops a stale binding and starts fresh when the failed attempt never established a session', async ({ cliOrkas }) => {const { page } = await createCliAgent(cliOrkas, 'OpenCodeRestartE2E', 'opencode');const conversationId = await sendNewChat(page, '@OpenCodeRestartE2E E2E_CLI_ESTABLISH_SESSION');- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_SESSION_ESTABLISHED',})).toBeVisible({ timeout: 30_000 });@@ -588,7 +594,7 @@ test.describe('CLI failed-turn recovery', () => {await retry.locator('xpath=ancestor::*[contains(@class, "chat-message")]').hover();await retry.click();- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_FRESH_RESTART_OK',})).toBeVisible({ timeout: 30_000 });@@ -606,17 +612,46 @@ test.describe('CLI failed-turn recovery', () => {});});- test('Hermes always creates a fresh ACP session and receives bridged visible history', async ({ cliOrkas }) => {+ test('Hermes always creates a fresh ACP session and receives bridged visible history', async ({ cliOrkas }, testInfo) => {const { page } = await createCliAgent(cliOrkas, 'HermesHistoryE2E', 'hermes');const conversationId = await sendNewChat(page, '@HermesHistoryE2E Remember E2E_HERMES_PRIOR_FACT=blue-orbit');- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {hasText: 'E2E_HERMES_FIRST_OK',})).toBeVisible({ timeout: 30_000 });+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);await sendFollowUp(page, '@HermesHistoryE2E E2E_HERMES_CONTINUE and use the prior fact');- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {- hasText: 'E2E_HERMES_HISTORY_BRIDGED',- })).toBeVisible({ timeout: 30_000 });+ await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);+ try {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble .markdown-body', {+ hasText: 'E2E_HERMES_HISTORY_BRIDGED',+ })).toBeVisible({ timeout: 30_000 });+ } finally {+ await testInfo.attach('hermes-display-state', {+ contentType: 'application/json',+ body: Buffer.from(JSON.stringify(await page.evaluate(`({+ pending: pendingConvs.has(currentCid), polling: pollTimers.has(currentCid),+ runtimeBusy: isGroupConversationBusy(currentCid),+ primaryBusy: _convChatCtrls.get(currentCid)?.isBusy?.() || false,+ liveFinals: document.querySelectorAll('#chat-history [data-role="final"]').length,+ assistantRows: document.querySelectorAll('#chat-history .chat-message.assistant').length+ })`))),+ });+ // Observe persistence only after the display assertion, so diagnostics+ // cannot trigger a history reconciliation that masks the original race.+ const persisted = await cliOrkas.invoke<{ history: Array<Record<string, any>> }>(+ 'conversations.history', { cid: conversationId, limit: 20 },+ );+ await testInfo.attach('hermes-history-state', {+ contentType: 'application/json',+ body: Buffer.from(JSON.stringify(persisted.history.map(row => ({+ user: row.from === 'user', textChars: String(row.text || '').length,+ expectedReply: row.text === 'E2E_HERMES_HISTORY_BRIDGED',+ systemKind: row.system_kind || '', turnEnd: row.turn_end,+ hasSourceMessageId: !!row.source_message_id, segment: row.seg,+ })))),+ });+ }const state = cliOrkas.readCliState();const hermesRuns = state.invocations.filter((item) => item.cli === 'hermes');@@ -636,7 +671,7 @@ test.describe('CLI failed-turn recovery', () => {page,`@${agentName} E2E_HERMES_LIMITS_BOOTSTRAP`,);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_HERMES_FIRST_OK',})).toBeVisible({ timeout: 30_000 });@@ -666,7 +701,7 @@ test.describe('CLI failed-turn recovery', () => {appendCanonicalMessages(cliOrkas, conversationId, rows);await sendFollowUp(page, `@${agentName} E2E_HERMES_LIMITS_CURRENT_TASK`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_HERMES_LIMITS_OK',})).toBeVisible({ timeout: 30_000 });@@ -695,7 +730,7 @@ test.describe('CLI failed-turn recovery', () => {page,`@${agentName} E2E_CODEX_CONTEXT_FIRST_TASK`,);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toBeVisible({ timeout: 30_000 });@@ -736,7 +771,7 @@ test.describe('CLI failed-turn recovery', () => {}).toContain('E2E_CODEX_INTERPOSED_COMMANDER_FACT=blue-river');await sendFollowUp(page, `@${agentName} E2E_CODEX_CONTEXT_SECOND_TASK`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toHaveCount(2, { timeout: 30_000 });@@ -755,7 +790,7 @@ test.describe('CLI failed-turn recovery', () => {const agentName = 'CodexBootstrapRecoveryE2E';const { page, agentId } = await createCliAgent(cliOrkas, agentName, 'codex');const cid = await sendNewChat(page, `@${agentName} Earlier requirement: use amber-field.`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toHaveCount(1, { timeout: 30_000 });await expect.poll(() => {@@ -765,7 +800,7 @@ test.describe('CLI failed-turn recovery', () => {writeFileSync(cliOrkas.cliStatePath, JSON.stringify({ ...cliOrkas.readCliState(), codexResumeHangs: 1 }));await cliOrkas.electronApp!.evaluate(() => { process.env.ORKAS_CODEX_BOOTSTRAP_TIMEOUT_MS = '1500'; });await sendFollowUp(page, `@${agentName} Continue the earlier requirement.`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toHaveCount(2, { timeout: 30_000 });await expect(page.locator('#chat-history .bubble-retry-btn')).toHaveCount(0);@@ -784,7 +819,7 @@ test.describe('CLI failed-turn recovery', () => {.toContain('cli-bootstrap-timeout');await page.screenshot({ path: testInfo.outputPath('codex-bootstrap-recovered.png'), fullPage: true });await sendFollowUp(page, `@${agentName} Check the saved requirement.`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toHaveCount(3, { timeout: 30_000 });expect(cliOrkas.readCliState().invocations[2].resumeSessionId).toBe(runs[1].sessionId);@@ -813,7 +848,7 @@ test.describe('CLI failed-turn recovery', () => {await expect(page.locator('#chat-history .chat-message.user', {hasText: 'E2E_CODEX_SEND_NOW_UPDATE',})).toBeVisible();- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_STEER_APPLIED',})).toBeVisible({ timeout: 30_000 });@@ -863,7 +898,7 @@ test.describe('CLI failed-turn recovery', () => {await expect(question).toBeHidden();await expect(stop).not.toHaveClass(/\b(streaming|aborting)\b/);await sendFollowUp(page, `@${name} E2E_CODEX_AFTER_STOP`);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CODEX_DEFAULT_OK',})).toBeVisible({ timeout: 30_000 });expect(cliOrkas.readCliState().invocations).toHaveLength(2);@@ -885,7 +920,7 @@ test.describe('CLI failed-turn recovery', () => {const answer = page.locator('#chat-history .chat-message.user', { hasText: 'Which scope?' });await expect(answer).toHaveCount(1);await expect(answer).toContainText('Current');- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_QUESTION_CONTINUED',})).toBeVisible({ timeout: 30_000 });const history = await cliOrkas.invoke<{ history: Array<{ from: string; text: string }> }>('conversations.history', { cid, limit: 20 });@@ -967,10 +1002,10 @@ test.describe('CLI failed-turn recovery', () => {// Same-agent serial: no second CLI child starts while the first runs.expect(cliOrkas.readCliState().invocations).toHaveLength(1);- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_SEND_NOW_ACTIVE_OK',})).toBeVisible({ timeout: 30_000 });- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])', {hasText: 'E2E_CLI_SEND_NOW_FOLLOWUP_OK',})).toBeVisible({ timeout: 30_000 });diff --git a/test/e2e/chat_e2e_saved_tasks.spec.ts b/test/e2e/chat_e2e_saved_tasks.spec.tsindex c4631d38..11b8d48e 100644--- a/test/e2e/chat_e2e_saved_tasks.spec.ts+++ b/test/e2e/chat_e2e_saved_tasks.spec.ts@@ -50,7 +50,7 @@ test('keeps saved automation and todo shortcuts usable live and after restart',await expect(page.locator('#project-detail-title')).toHaveText('Release review');await page.locator('#project-chat-input').fill('Schedule a nightly review and add a release-note todo.');await page.locator('#project-chat-send-btn').click();- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]'))+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText('The tasks have been saved.', { timeout: 30_000 });await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);const { conversations } = await app.invoke<{diff --git a/test/e2e/chat_e2e_send_responsiveness.spec.ts b/test/e2e/chat_e2e_send_responsiveness.spec.tsindex bbf8d6de..b51c48c5 100644--- a/test/e2e/chat_e2e_send_responsiveness.spec.ts+++ b/test/e2e/chat_e2e_send_responsiveness.spec.ts@@ -1,11 +1,11 @@import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';import { expect, test } from './fixtures/orkas';-import { checkLatencyBudget } from '../helpers/latency-budget';+import { checkLatencyBudget, LATENCY_LIMIT_MS } from '../helpers/latency-budget';// Real renderer -> IPC -> main -> SDK, using the existing isolated local model.// The second case proves a main-process stall cannot hide behind a fast cached paint.-for (const injectedStallMs of [0, 600]) {+for (const injectedStallMs of [0, LATENCY_LIMIT_MS + 100]) {test(`switches from sending A to B with a responsive main process (injected stall ${injectedStallMs} ms)`, async ({ modelOrkas }) => {const page = modelOrkas.page!;const app = modelOrkas.electronApp!;@@ -13,7 +13,7 @@ for (const injectedStallMs of [0, 600]) {await page.locator('#new-chat-input').fill(marker);await page.locator('#new-chat-send-btn').click();await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]'))- // Cold-start setup is outside the 500 ms send/switch measurement below.+ // Cold-start setup is outside the platform send/switch measurement below..toContainText('Hello from the local E2E model.', { timeout: 30_000 });await expect(page.locator('#chat-send-btn')).not.toHaveClass(/\bstreaming\b/);const cidB = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');@@ -125,7 +125,7 @@ for (const injectedStallMs of [0, 600]) {if (injectedStallMs) {expect(pulse.injected).toBe(true);expect(() => checkLatencyBudget('main loop response negative control', { elapsedMs: pulse.maxGapMs }))- .toThrow('budget 500 ms');+ .toThrow(`budget ${LATENCY_LIMIT_MS} ms`);} else {checkLatencyBudget('send A then open B', { elapsedMs: switchMs, phases: [{ phase: 'scheduled_click', ms: timing.clickDelayMs },diff --git a/test/e2e/composer_e2e_interactions.spec.ts b/test/e2e/composer_e2e_interactions.spec.tsindex d215e65f..7f3e1d77 100644--- a/test/e2e/composer_e2e_interactions.spec.ts+++ b/test/e2e/composer_e2e_interactions.spec.ts@@ -88,6 +88,7 @@ test.describe('new chat composer', () => {await editor.fill('');await editor.press('@');await page.locator('#agent-picker [data-id="__commander__"]').click();+ await expect(editor).toBeFocused();await editor.pressSequentially('continue');await editor.press('Enter');await expect(page.locator('#chat-history .chat-message.user .markdown-body').last()).toHaveText('@Commander continue');@@ -658,6 +659,7 @@ test.describe('new chat composer', () => {await page.locator(`.skill-picker-item[data-id="${recipients[1].agent_id}"]`).click();await expectComposerText(input, '@ComposerAlpha 你好, Xcheck the request @ComposerBeta ');await page.locator(`.skill-picker-item[data-id="${recipients[1].agent_id}"]`).press('Escape');+ await expect(editor).toBeFocused();await editor.pressSequentially('verify the result');await expect(page.locator('#new-chat-recipient-name')).toHaveText('ComposerAlpha, ComposerBeta');await page.locator('#panel-new-chat .new-chat-input-wrapper').screenshot({ path: testInfo.outputPath('recipient-caret.png') });@@ -1201,7 +1203,7 @@ test.describe('new chat composer', () => {await expect(page.locator('#new-chat-attachments .chat-attach-chip')).toHaveCount(3);await page.locator('#new-chat-input').fill('Use all deterministic E2E attachments.');await page.locator('#new-chat-send-btn').click();- await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]')).toContainText(+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText('Hello from the local E2E model.',{ timeout: 20_000 },);@@ -1273,3 +1275,80 @@ test('keeps all four recipient tabs on one row, including Library', async ({ appawait tabs.filter({ hasText: 'Library' }).click();await expect(appPage.locator('[data-agent-picker-tab="library"]')).toHaveClass(/\bactive\b/);});++test.describe('attachment adoption recovery', () => {+ for (const entry of ['Commander', 'Project'] as const) for (const locale of ['en', 'zh'] as const) {+ test(`keeps the ${entry} draft private and retryable after an adoption error (${locale})`, async ({ modelOrkas: orkas }, info) => {+ const page = orkas.page!;+ await page.evaluate(async (language) => (window as any).setLang(language), locale);+ let projectId = '';+ if (entry === 'Project') {+ const created = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Attachment recovery project' });+ projectId = created.project.project_id;+ await page.evaluate(async (pid) => {+ await (window as any).loadProjects(true);+ (window as any).setView('project', pid);+ }, projectId);+ }+ const prefix = entry === 'Project' ? 'project-chat' : 'new-chat';+ const draftCid = projectId ? `projchat-${projectId}` : 'main_chat';+ const input = page.locator(`#${prefix}-input`);+ const send = page.locator(`#${prefix}-send-btn`);+ const fileName = 'Long attachment brief covering the complete recovery journey and retained draft.md';+ const source = orkas.createFixtureFile(fileName, '# Retained attachment\nThe complete original bytes.\n');+ await orkas.selectFilesOnNextDialog([source]);+ await page.locator(`#${prefix}-attach-btn`).click();+ const chip = page.locator(`#${prefix}-attachments .chat-attach-chip`, { hasText: fileName });+ await expect(chip).toBeVisible();+ await expect(chip).not.toHaveClass(/\bis-uploading\b/);+ const draft = 'Review the complete long attachment and preserve this draft for retry.';+ await input.fill(draft);+ const before = await orkas.invoke<{ conversations: unknown[] }>('conversations.list');+ // One explicit IPC failure models a locked filesystem. Everything after+ // this response, including empty-task discard and retry, uses real IPC.+ await orkas.electronApp!.evaluate(({ ipcMain }) => {+ const original = (ipcMain as any)._invokeHandlers.get('orkas.invoke');+ ipcMain.removeHandler('orkas.invoke');+ ipcMain.handle('orkas.invoke', async (event, request) => {+ if (request.channel === 'conversations.attachments.adopt') {+ ipcMain.removeHandler('orkas.invoke');+ ipcMain.handle('orkas.invoke', original);+ return { ok: false, error: 'EPERM: rename C:\\PRIVATE_ATTACHMENT_PATH\\draft to conversation' };+ }+ return original(event, request);+ });+ });+ await send.click();+ const dialog = page.locator('.ui-dialog-overlay:visible .ui-dialog');+ const copy = locale === 'zh' ? '无法确认附件状态,消息和文件均已保留,请重试。'+ : 'Could not confirm the attachments. Your message and files are still here; try again.';+ await expect(dialog).toContainText(copy);+ await expect(dialog).not.toContainText(/PRIVATE_ATTACHMENT_PATH|EPERM|attachment_adopt/);+ for (const width of [1280, 620]) {+ await page.setViewportSize({ width, height: width === 1280 ? 800 : 780 });+ expect(await dialog.evaluate((el) => {+ const rect = el.getBoundingClientRect();+ return rect.left >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight && el.scrollWidth <= el.clientWidth;+ })).toBe(true);+ await page.screenshot({ path: info.outputPath(`adoption-error-${entry}-${locale}-${width}.png`) });+ }+ await expect(dialog.locator('[data-act="ok"]')).toBeFocused();+ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+ await expectComposerText(input, draft);+ await expect(chip).toBeVisible();+ await expect(send).toBeEnabled();+ expect(orkas.modelRequests).toHaveLength(0);+ expect((await orkas.invoke<{ conversations: unknown[] }>('conversations.list')).conversations).toHaveLength(before.conversations.length);+ expect((await orkas.invoke<{ items: Array<{ name: string }> }>('conversations.attachments.list', { cid: draftCid })).items.map((item) => item.name)).toEqual([fileName]);+ const reply = `RECOVERY_ACK_${entry}_${locale}`;+ orkas.setModelTextReplies([reply]);+ await send.click();+ await expect(page.locator('#chat-history .chat-message.assistant .chat-bubble > :is(.markdown-body, [data-role="final"])')).toContainText(reply, { timeout: 20_000 });+ await expect(page.locator('#chat-history .chat-message.user')).toContainText(fileName);+ expect(orkas.modelRequests).toHaveLength(1);+ expect((await orkas.invoke<{ conversations: unknown[] }>('conversations.list')).conversations).toHaveLength(before.conversations.length + 1);+ expect((await orkas.invoke<{ items: unknown[] }>('conversations.attachments.list', { cid: draftCid })).items).toEqual([]);+ });+ }+});diff --git a/test/e2e/search_e2e_rebuild.spec.ts b/test/e2e/search_e2e_rebuild.spec.tsindex 94a257d9..18d1ae28 100644--- a/test/e2e/search_e2e_rebuild.spec.ts+++ b/test/e2e/search_e2e_rebuild.spec.ts@@ -1,3 +1,4 @@+import { finished } from 'node:stream/promises';import path from 'node:path';import { cpSync, mkdirSync, readFileSync, existsSync } from 'node:fs';import { createPackageWithOptions } from '@electron/asar';@@ -177,7 +178,7 @@ test('runs rebuild, live indexing and snippet workers from an ASAR with the ship// Use the actual packaging rules, not a test-only unpack-all workaround.// asar matches absolute filenames; electron-builder's patterns are relative.const unpack = pkg.build.asarUnpack.map((pattern: string) => path.join(source, pattern).replaceAll('\\', '/'));- await createPackageWithOptions(source, archive, { unpack: `{${unpack.join(',')}}` });+ await finished(await createPackageWithOptions(source, archive, { unpack: `{${unpack.join(',')}}` }));const esbuild = path.join(`${archive}.unpacked`, 'node_modules', '@esbuild',`${process.platform}-${process.arch}`, ...(process.platform === 'win32' ? ['esbuild.exe'] : ['bin', 'esbuild']));expect(existsSync(esbuild)).toBe(true);diff --git a/test/e2e/shared_renderer_e2e_primitives.spec.ts b/test/e2e/shared_renderer_e2e_primitives.spec.tsindex f43b5477..278a6549 100644--- a/test/e2e/shared_renderer_e2e_primitives.spec.ts+++ b/test/e2e/shared_renderer_e2e_primitives.spec.ts@@ -1,3 +1,4 @@+import type { Request } from '@playwright/test';import { expect, test } from './fixtures/orkas';test.describe('shared Renderer primitives', () => {@@ -145,79 +146,111 @@ test.describe('shared Renderer primitives', () => {expect(math).toEqual({ rendered: true, runtimes: 1 });});- test('rejects an XSS attack matrix after prototype pollution', async ({ appPage }) => {- const result = await appPage.evaluate(async () => {- const root = window as any;- const prototype = Object.prototype as Record<string, unknown>;- const pollution: Record<string, unknown> = {- CUSTOM_ELEMENT_HANDLING: {- tagNameCheck: /.*/,- attributeNameCheck: /.*/,- allowCustomizedBuiltInElements: true,- },- ALLOWED_TAGS: ['x-unsafe', 'script', 'img', 'svg', 'a', 'button'],- ALLOWED_ATTR: ['onfocus', 'onerror', 'onload', 'href', 'is'],- ADD_TAGS: ['x-unsafe', 'script'],- ADD_ATTR: ['onfocus', 'onerror', 'onload', 'is'],- FORBID_TAGS: [],- };- const previous = new Map(- Object.keys(pollution).map((key) => [- key,- Object.getOwnPropertyDescriptor(prototype, key),- ]),- );- try {- for (const [key, value] of Object.entries(pollution)) {- Object.defineProperty(prototype, key, {- value,- configurable: true,- writable: true,- });- }- const safe = [- '<x-unsafe tabindex="0" onfocus="window.__domPurifyBypass=1">focus me</x-unsafe>',- '<button is="x-unsafe" tabindex="0" onfocus="window.__domPurifyBypass=2">button</button>',- '<img src="x-invalid" onerror="window.__domPurifyBypass=3">',- '<svg onload="window.__domPurifyBypass=4"><script>window.__domPurifyBypass=5</script></svg>',- '<a href="javascript:window.__domPurifyBypass=6">link</a>',- ].map((payload) => root.sanitizeHtml(payload));- const host = document.createElement('div');- host.innerHTML = safe.join('\n');- document.body.appendChild(host);- host.querySelectorAll<HTMLElement>('[tabindex]').forEach((node) => node.focus());- host.querySelectorAll('img').forEach((node) => node.dispatchEvent(new Event('error')));- host.querySelectorAll('svg').forEach((node) => node.dispatchEvent(new Event('load')));- await new Promise((resolve) => setTimeout(resolve, 0));- const state = {- safe,- customElements: host.querySelectorAll('x-unsafe').length,- scripts: host.querySelectorAll('script').length,- eventAttributes: host.querySelectorAll('[onfocus], [onerror], [onload]').length,- dangerousUrls: Array.from(host.querySelectorAll('[href]')).filter((node) => (- /^\s*javascript:/i.test(node.getAttribute('href') || '')- )).length,- executed: !!root.__domPurifyBypass,+ test('rejects an XSS attack matrix after prototype pollution', async ({ appPage }, testInfo) => {+ const expectedMissingImageUrl = new URL('x-invalid', appPage.url()).href;+ const resourceFailures: Array<{+ matchesInjectedImage: boolean;+ resourceKind: string;+ errorCode: 'net::ERR_FILE_NOT_FOUND' | 'unexpected';+ }> = [];+ const onRequestFailed = (request: Request) => {+ const errorText = request.failure()?.errorText;+ resourceFailures.push({+ matchesInjectedImage: request.url() === expectedMissingImageUrl,+ resourceKind: request.resourceType(),+ errorCode: errorText === 'net::ERR_FILE_NOT_FOUND' ? errorText : 'unexpected',+ });+ };+ appPage.on('requestfailed', onRequestFailed);+ try {+ const result = await appPage.evaluate(async () => {+ const root = window as any;+ const prototype = Object.prototype as Record<string, unknown>;+ const pollution: Record<string, unknown> = {+ CUSTOM_ELEMENT_HANDLING: {+ tagNameCheck: /.*/,+ attributeNameCheck: /.*/,+ allowCustomizedBuiltInElements: true,+ },+ ALLOWED_TAGS: ['x-unsafe', 'script', 'img', 'svg', 'a', 'button'],+ ALLOWED_ATTR: ['onfocus', 'onerror', 'onload', 'href', 'is'],+ ADD_TAGS: ['x-unsafe', 'script'],+ ADD_ATTR: ['onfocus', 'onerror', 'onload', 'is'],+ FORBID_TAGS: [],};- host.remove();- delete root.__domPurifyBypass;- return state;- } finally {- for (const [key, descriptor] of previous) {- if (descriptor) Object.defineProperty(prototype, key, descriptor);- else delete prototype[key];+ const previous = new Map(+ Object.keys(pollution).map((key) => [+ key,+ Object.getOwnPropertyDescriptor(prototype, key),+ ]),+ );+ try {+ for (const [key, value] of Object.entries(pollution)) {+ Object.defineProperty(prototype, key, {+ value,+ configurable: true,+ writable: true,+ });+ }+ const safe = [+ '<x-unsafe tabindex="0" onfocus="window.__domPurifyBypass=1">focus me</x-unsafe>',+ '<button is="x-unsafe" tabindex="0" onfocus="window.__domPurifyBypass=2">button</button>',+ '<img src="x-invalid" onerror="window.__domPurifyBypass=3">',+ '<svg onload="window.__domPurifyBypass=4"><script>window.__domPurifyBypass=5</script></svg>',+ '<a href="javascript:window.__domPurifyBypass=6">link</a>',+ ].map((payload) => root.sanitizeHtml(payload));+ const host = document.createElement('div');+ host.innerHTML = safe.join('\n');+ document.body.appendChild(host);+ host.querySelectorAll<HTMLElement>('[tabindex]').forEach((node) => node.focus());+ host.querySelectorAll('img').forEach((node) => node.dispatchEvent(new Event('error')));+ host.querySelectorAll('svg').forEach((node) => node.dispatchEvent(new Event('load')));+ await new Promise((resolve) => setTimeout(resolve, 0));+ const state = {+ safe,+ customElements: host.querySelectorAll('x-unsafe').length,+ scripts: host.querySelectorAll('script').length,+ eventAttributes: host.querySelectorAll('[onfocus], [onerror], [onload]').length,+ dangerousUrls: Array.from(host.querySelectorAll('[href]')).filter((node) => (+ /^\s*javascript:/i.test(node.getAttribute('href') || '')+ )).length,+ executed: !!root.__domPurifyBypass,+ };+ host.remove();+ delete root.__domPurifyBypass;+ return state;+ } finally {+ for (const [key, descriptor] of previous) {+ if (descriptor) Object.defineProperty(prototype, key, descriptor);+ else delete prototype[key];+ }}- }- });+ });- expect(result).toMatchObject({- customElements: 0,- scripts: 0,- eventAttributes: 0,- dangerousUrls: 0,- executed: false,- });- expect(result.safe.join('')).not.toMatch(/onfocus|onerror|onload|javascript:/i);+ expect(result).toMatchObject({+ customElements: 0,+ scripts: 0,+ eventAttributes: 0,+ dangerousUrls: 0,+ executed: false,+ });+ expect(result.safe.join('')).not.toMatch(/onfocus|onerror|onload|javascript:/i);+ await expect.poll(() => resourceFailures.length).toBe(1);+ expect(resourceFailures).toEqual([{+ matchesInjectedImage: true,+ resourceKind: 'image',+ errorCode: 'net::ERR_FILE_NOT_FOUND',+ }]);+ await appPage.evaluate((evidence) => {+ console.info('[e2e:xss-resource-failure] ' + JSON.stringify(evidence));+ }, resourceFailures);+ } finally {+ appPage.off('requestfailed', onRequestFailed);+ await testInfo.attach('xss-resource-failure', {+ body: Buffer.from(JSON.stringify(resourceFailures)),+ contentType: 'application/json',+ });+ }});test('exposes the shared dropdown state and supports keyboard-only selection', async ({ appPage }) => {diff --git a/test/main/core-regression.test.ts b/test/main/core-regression.test.tsindex 11376dfe..6ae947ae 100644--- a/test/main/core-regression.test.ts+++ b/test/main/core-regression.test.ts@@ -59,7 +59,7 @@ vi.mock('../../src/main/features/file_indexer', () => ({}));vi.mock('../../src/main/util/image-transform', () => ({- toCompressedGrayJpeg: vi.fn(async () => Buffer.from('jpeg')),+ toCompressedJpeg: vi.fn(async () => Buffer.from('jpeg')),}));beforeEach(async () => {diff --git a/test/main/features/group_chat/send-latency.test.ts b/test/main/features/group_chat/send-latency.test.tsindex 75068c8b..51e36d01 100644--- a/test/main/features/group_chat/send-latency.test.ts+++ b/test/main/features/group_chat/send-latency.test.ts@@ -53,6 +53,7 @@ let storage: typeof import('../../../../src/main/storage');const cids: string[] = [];let onRequest: ((body: Record<string, any>) => void) | undefined;const unexpectedRequests: string[] = [];+let nativeEsmHooks: { deregister(): void } | null = null;function completeCliDispatch(opts: any): void {// External CLI startup/network timing belongs to that executable. The host budget@@ -79,6 +80,10 @@ function modelResponse(): Response {beforeAll(async () => {// Vitest's source transformation is harness startup, outside the loaded-app send budget.+ const require = createRequire(import.meta.url);+ // Match bootstrap.cjs: native SDK leaves use the production resolver, while+ // TypeScript stays with the test loader. This does not preload an API.+ nativeEsmHooks = require('../../../../src/main/util/native-esm-loader.js').registerNativeEsmLoader();const { installSdkTimeoutPatch } = await import('../../../../src/main/model/core-agent/sdk-timeout-patch');installSdkTimeoutPatch();// SDK 1.2 loads this transport lazily. Compile its module graph alongside@@ -93,9 +98,13 @@ beforeAll(async () => {// separate ESM graph would otherwise recompile the bus on the first send.// No send is warmed up. Fixtures are written after module loading, so their// first reads and all request preparation remain inside the budget.- const require = createRequire(import.meta.url);require('../../../../src/main/features/packages');require('../../../../src/main/features/group_chat/bus');+ // main/index.ts imports these features before the window is ready. Their+ // cycle-breaking CJS reads must not compile a second graph inside the send+ // timer. Keep provider APIs lazy: their real first-use cost stays measured.+ require('../../../../src/main/features/skills');+ require('../../../../src/main/features/auto_tasks');[chats, groupChat, bus, state, paths, storage] = await Promise.all([import('../../../../src/main/features/chats'),import('../../../../src/main/features/group_chat'),@@ -137,6 +146,7 @@ afterEach(async () => {afterAll(async () => {await drainMainRuntimeForTest();+ nativeEsmHooks?.deregister();vi.unstubAllGlobals();vi.unstubAllEnvs();});diff --git a/test/main/model/runner.test.ts b/test/main/model/runner.test.tsindex c50bfb1b..0eb563af 100644--- a/test/main/model/runner.test.ts+++ b/test/main/model/runner.test.ts@@ -47,6 +47,7 @@ beforeEach(async () => {});afterEach(async () => {+ await (await import('../../../src/main/features/search/indexer')).flushAll();await closeLogWorkers();vi.doUnmock('@earendil-works/pi-ai/oauth');vi.doUnmock('#core-agent');@@ -136,6 +137,13 @@ describe('runner › buildRunner auth gate', () => {);});+ it('requires a configured candidate for image understanding even when a development key exists', async () => {+ process.env.ANTHROPIC_API_KEY = 'sk-ant-test-placeholder';+ const { buildRunner } = await loadRunner();+ await expect(buildRunner({ sessionId: 'extract-img-empty-list', requireImageInput: true }))+ .rejects.toThrow(/credential is not currently usable/);+ });+it('skips the auth gate when ANTHROPIC_API_KEY is set (dev fallback)', async () => {// With the env var set, the gate passes through to core-agent init.// We only need to verify the gate's error is NOT raised — any later@@ -559,6 +567,32 @@ describe('runner › buildRunner auth gate', () => {}));});+ it.each([false, true])('routes public native candidates through the registry with required image input %s', async requireImageInput => {+ const createPiProvider = vi.fn(() => ({id:'anthropic',name:'Image requirement fixture',+ async *stream() {yield {type:'text_delta' as const,text:'ok'};},+ complete:vi.fn(),validateAuth:async () => true,+ }));+ vi.doMock('#core-agent',async () => ({...(await vi.importActual<any>('#core-agent')),createPiProvider}));+ const uid='runner-image-requirement';+ const users=await import('../../../src/main/features/users'); users.activateUser(uid);+ const auth=await import('../../../src/main/features/auth');+ const catalog=await import('../../../src/main/model/provider_catalog');+ const limit=vi.spyOn(catalog,'modelInputImageLimit').mockImplementation((_provider,model) => model==='claude-sonnet-5'?0:12);+ const choices=[{provider:'anthropic',model:'claude-opus-5',entryId:'vision',profileId:'vision',apiKey:'fixture-vision-key'}];+ if(requireImageInput) choices.unshift({provider:'anthropic',model:'claude-sonnet-5',entryId:'text',profileId:'text',apiKey:'fixture-text-key'});+ const pick=vi.spyOn(auth,'pickChatEntryGroup').mockResolvedValue(choices);+ try {+ const {buildRunner}=await loadRunner();+ const built=await buildRunner({sessionId:'gconv-image-requirement',userId:uid,requireImageInput});+ const provider=(built.runner as any).providers.get('anthropic');+ const iterator=provider.stream({model:built.modelId,messages:[{role:'user',content:[{type:'image',data:'pixels',mediaType:'image/png'}]}]})[Symbol.asyncIterator]();+ await iterator.next(); await iterator.return?.();+ expect(built.modelId).toBe(requireImageInput?'claude-sonnet-5':'claude-opus-5');+ expect(createPiProvider).toHaveBeenCalledTimes(1);+ expect(createPiProvider).toHaveBeenCalledWith(expect.objectContaining({provider:'anthropic',apiKey:'fixture-vision-key',+ customModel:expect.objectContaining({id:'claude-opus-5',input:['text','image']})}));+ } finally {pick.mockRestore();limit.mockRestore();}+ });});describe('runner › metacognition closed loop', () => {@@ -971,10 +1005,22 @@ describe('runner › scoped tool loading', () => {]);});+ it('retains the automatic output grammar in the real Commander prompt', async () => {+ const chats = await import('../../../src/main/features/chats');+ await chats.createConversation(RUNNER_TEST_UID, { conversationId: 'rich-output-commander', title: 'Output grammar' });+ const { _buildCommanderSystemPromptForTest } = await import('../../../src/main/features/group_chat/bus');+ const prompt = await _buildCommanderSystemPromptForTest(RUNNER_TEST_UID, 'rich-output-commander', undefined, 'en');+ expect(prompt).toContain('Automatic layout');+ expect(prompt.match(/\{"schema_version":1,"root":\{"type":"Stack"/g)).toHaveLength(1);+ expect(prompt).toContain('**`create_artifact`** is a sandboxed app');+ expect(prompt.indexOf('**`:::dashboard`**')).toBeLessThan(prompt.indexOf('## Runtime injection'));+ });+it.each([- { agentId: CONTENT_WRITER_AGENT_ID, maximal: false },- { agentId: VIDEO_STUDIO_AGENT_ID, maximal: true },- ])('keeps progress guidance in the assembled Agent surface ($agentId, maximal=$maximal)', async ({ agentId, maximal }) => {+ { agentId: CONTENT_WRITER_AGENT_ID, maximal: false, outputFormat: undefined },+ { agentId: VIDEO_STUDIO_AGENT_ID, maximal: true, outputFormat: undefined },+ { agentId: CONTENT_WRITER_AGENT_ID, maximal: false, outputFormat: 'text' },+ ])('keeps progress guidance in the assembled Agent surface ($agentId, maximal=$maximal, output=$outputFormat)', async ({ agentId, maximal, outputFormat }) => {const uid = `runner-progress-surface-${agentId}`;await configureUser(uid);const paths = await import('../../../src/main/paths');@@ -994,7 +1040,7 @@ describe('runner › scoped tool loading', () => {fs.mkdirSync(dest, { recursive: true });fs.copyFileSync(manifest, path.join(dest, 'SKILL.md'));}- const base = await _buildAgentInGroupSystemPromptForTest(agent, tmpDir, 'en');+ const base = await _buildAgentInGroupSystemPromptForTest({ ...agent, output_format: outputFormat ?? agent.output_format }, tmpDir, 'en');const { buildRunner } = await loadRunner();const built = await buildRunner({sessionId: `gmember-progress-surface-${agentId}`, userId: uid, agentId,@@ -1003,6 +1049,8 @@ describe('runner › scoped tool loading', () => {toolList: maximal ? [...AGENT_FALLBACK_TOOL_GROUP_IDS] : agent.tool_list,});const prompt = built.resolvedSystemPrompt;+ expect(prompt.includes('**`:::dashboard`**')).toBe(outputFormat !== 'text');+ expect(prompt.includes('**`create_artifact`** is a sandboxed app')).toBe(outputFormat !== 'text');expect(prompt.match(/These updates are not final replies/g)).toHaveLength(1);expect(prompt).not.toContain('before the first tool call');expect(prompt).not.toContain('Once you output, your turn is done.');@@ -1014,7 +1062,7 @@ describe('runner › scoped tool loading', () => {expect(prompt).not.toMatch(/\$(?:workflow|inputs_schema|input_channel_protocol|plan_interaction_hint)/);const toolChars = JSON.stringify(built.toolDefs).length;const combined = prompt.length + built.turnEphemeral.length + toolChars;- console.log(`[agent-effective-progress-surface] ${agent.name}: system=${prompt.length}, ephemeral=${built.turnEphemeral.length}, tools=${toolChars}, combined=${combined}`);+ console.log(`[agent-effective-progress-surface] ${agent.name} output=${outputFormat ?? agent.output_format ?? 'auto'}: system=${prompt.length}, ephemeral=${built.turnEphemeral.length}, tools=${toolChars}, combined=${combined}`);// The merged action-specific tool contracts add 5,539 / 6,995 schema// chars, while removing the active-group tail saves 162 / 382 chars.// With the same OfficeCLI fixture, resident prompts remain unchanged:@@ -1065,108 +1113,100 @@ describe('runner › scoped tool loading', () => {expect(JSON.parse(listed.content).tasks).toContainEqual(expect.objectContaining({ content: 'BACKLOG_NOT_IN_PROMPT' }));});- it('loads tasks outside a project and writes only to an explicitly resolved project or global scope', async () => {+ it('stamps an automation handoff note the turn shows whole as already read, and only then', async () => {+ const uid = 'runner-automation-note-seed';+ await configureUser(uid);+ const { buildRunner } = await loadRunner();+ const chats = await import('../../../src/main/features/chats');+ const autoTasks = await import('../../../src/main/features/auto_tasks');+ const created = await autoTasks.createTask(uid, {+ content: 'Compare this week with last week', schedule: { type: 'daily', hour: 9, minute: 0 },+ });+ if (!created.ok) throw new Error(created.error);+ const notePath = autoTasks.handoffNotePath(uid, created.task);+ fs.mkdirSync(path.dirname(notePath), { recursive: true });+ fs.writeFileSync(notePath, '# Week 41\nTotal 1,280 orders\n');+ const run = await chats.createConversation(uid, { title: 'Weekly digest', originAutoTaskId: created.task.id });+ await autoTasks.recordRunStart(uid, created.task.id, run.conversation_id, '2026-10-21T09:00:00.000Z');++ const built = await buildRunner({ sessionId: 'gconv-automation-note-seed', userId: uid, cid: run.conversation_id });+ expect(built.turnEphemeral).toContain('## This automation run');+ // The stamp carries the digest edit_file computes, so a note rewritten by+ // a command before the edit is still rejected as stale.+ const digest = `sha256:${createHash('sha256').update(fs.readFileSync(notePath, 'utf8'), 'utf8').digest('hex')}`;+ expect(built.initialReadFileState?.get(notePath)).toEqual({+ mtimeMs: fs.statSync(notePath).mtimeMs, size: fs.statSync(notePath).size, hash: digest,+ });+ expect([...built.initialReadFileState!.keys()]).toEqual([notePath]);++ // A note the turn had to cut is not stamped: its tail was never shown.+ fs.writeFileSync(notePath, 'detail '.repeat(400));+ const cut = await buildRunner({ sessionId: 'gconv-automation-note-seed-cut', userId: uid, cid: run.conversation_id });+ expect(cut.turnEphemeral).toContain('[cut; read the file for the rest]');+ expect(cut.initialReadFileState).toBeUndefined();+ // An ordinary conversation seeds nothing.+ const plain = await buildRunner({ sessionId: 'gconv-automation-note-seed-plain', userId: uid, cid: 'plain-conversation' });+ expect(plain.initialReadFileState).toBeUndefined();+ });++ it('keeps non-project Commander to-dos global through loading, CRUD and denied project requests', async () => {process.env.ORKAS_TOOL_LOADING_MODE = 'scoped';const uid = 'runner-unbound-project-tasks';await configureUser(uid);const projects = await import('../../../src/main/features/projects');const tasks = await import('../../../src/main/features/project_tasks');- const target = await projects.createProject(uid, '测试项目');- const other = await projects.createProject(uid, 'Other');- const foreign = await projects.createProject('different-account', 'Foreign');- if (!target.ok || !other.ok || !foreign.ok) throw new Error('project fixture failed');+ const project = await projects.createProject(uid, 'PRIVATE_PROJECT');+ if (!project.ok) throw new Error('project fixture failed');+ const privateTask = await tasks.createTask(uid, project.project.project_id, { content: 'PRIVATE_PROJECT_TASK' });+ if (!privateTask.ok) throw new Error('task fixture failed');+ const chats = await import('../../../src/main/features/chats');+ await chats.createConversation(uid, { conversationId: 'outside-project', title: 'Direct work' });+ const before = await tasks.listTasks(uid, project.project.project_id);const names = vi.spyOn(projects, 'listProjectNameRows');const { buildRunner } = await loadRunner();const built = await buildRunner({ sessionId: 'gconv-unbound-project-tasks', userId: uid, cid: 'outside-project' });- const runner = built.runner as any;- const initialPrompt = built.resolvedSystemPrompt;- const initialTail = built.turnEphemeral;- expect(names).not.toHaveBeenCalled();- expect(built.runner.getActiveToolDefinitions().map((tool) => tool.name)).not.toContain('todo_tasks');+ const tools = (built.runner as any).tools;+ expect(built.runner.getActiveToolDefinitions().map(tool => tool.name)).not.toContain('todo_tasks');+ expect(built.turnEphemeral).not.toContain('## Global open work');+ expect(built.turnEphemeral).toMatch(/explain that this non-project conversation cannot access them/);+ expect(built.turnEphemeral.match(/## Global to-do scope/g)).toHaveLength(1);const context = { workingDir: tmpDir, state: {} };- const load = await runner.tools.get('tool_load').execute({ groups: ['management.projects'] }, context);- // The same group carries the project-creation tool for Commander; both are- // dormant until this load, and neither is resident.- expect(JSON.parse(load.content))- .toMatchObject({ ok: true, newly_activated_tools: ['todo_tasks', 'project_setup'] });+ expect((await tools.get('tool_load').execute({ groups: ['management.projects'] }, context)).isError).toBeFalsy();+ const tool = tools.get('todo_tasks');+ expect(tool.inputSchema.properties.project.enum).toEqual(['__global__']);+ expect(tool.inputSchema.properties.action.enum).not.toContain('list_projects');+ expect(tool.description).toContain('Project to-dos are unavailable');+ expect(tool.description).not.toContain('When asked about them, explain');+ const created = JSON.parse((await tool.execute({ action: 'create', project: '__global__', content: 'Global work' }, context)).content);+ expect(created).toMatchObject({ ok: true, outcome: 'task_created' });+ const id = created.task.id;+ expect(await tasks.getTask(uid, '', id)).toMatchObject({ content: 'Global work', status: 'todo', origin_cid: 'outside-project' });+ expect((await tool.execute({ action: 'update', task_id: id, status: 'review' }, context)).isError).toBeFalsy();+ expect((await tool.execute({ action: 'complete', task_id: id }, context)).isError).toBeFalsy();+ expect(await tasks.getTask(uid, '', id)).toMatchObject({ status: 'done' });+ for (const request of [+ { action: 'list_projects' },+ { action: 'list', project: 'PRIVATE_PROJECT' },+ { action: 'get', project: project.project.project_id, task_id: privateTask.task.id },+ { action: 'get', task_id: privateTask.task.id },+ { action: 'complete', task_id: privateTask.task.id },+ { action: 'create', project: project.project.project_id, content: 'Forbidden' },+ { action: 'create', project: 'missing-project', content: 'Forbidden' },+ ]) expect((await tool.execute(request, context)).isError).toBe(true);+ const program = tools.get('run_program');+ expect(program).toBeDefined();+ const denied = await program.execute({ code: 'const result = await tools.todo_tasks({action:"get",project:"PRIVATE_PROJECT",task_id:"' + privateTask.task.id + '"}); console.log(result);' }, context);+ expect(denied.content).toContain('project_scope_mismatch');+ expect(denied.content).not.toContain('PRIVATE_PROJECT_TASK');+ expect(await tasks.listTasks(uid, project.project.project_id)).toEqual(before);expect(names).not.toHaveBeenCalled();- expect(built.runner.getActiveToolDefinitions().map((tool) => tool.name)).toContain('todo_tasks');- const tool = runner.tools.get('todo_tasks');- const discovery = JSON.parse((await tool.execute({ action: 'list_projects' }, context)).content);- expect(discovery.projects.map((project: any) => project.project_id).sort())- .toEqual(['__global__', target.project.project_id, other.project.project_id].sort());- const globalCreated = await tool.execute({ action: 'create', project: '__global__', content: '全局待办' }, context);- expect(JSON.parse(globalCreated.content)).toMatchObject({- ok: true,- outcome: 'task_created',- project: { project_id: '__global__', name: 'Global' },- });- expect(await tasks.listTasks(uid, '')).toEqual([- expect.objectContaining({ content: '全局待办', status: 'todo' }),- ]);- // A global to-do saved from a conversation links back to it, so opening or- // running it later returns there.- expect((await tasks.listTasks(uid, ''))[0]).toHaveProperty('origin_cid', 'outside-project');- const request = { action: 'create', project: '测试项目', content: '这是一条测试待办' };- const created = await tool.execute(request, context);- expect(JSON.parse(created.content)).toMatchObject({- ok: true, outcome: 'task_created', project: { project_id: target.project.project_id },- });- const repeated = await tool.execute(request, context);- expect(JSON.parse(repeated.content)).toMatchObject({ ok: true, outcome: 'existing_task_reused' });- const persisted = await tasks.listTasks(uid, target.project.project_id);- expect(persisted).toHaveLength(1);- expect(persisted[0]).toMatchObject({ content: request.content, status: 'todo' });- expect(persisted[0]).not.toHaveProperty('origin_cid');- const userCreated = await tasks.createTask(uid, target.project.project_id, { content: 'Status-only task' });- if (!userCreated.ok) throw new Error('user-created task fixture failed');- const statusUpdate = await tool.execute({- action: 'update',- project: target.project.project_id,- task_id: userCreated.task.id,- status: 'progress',- }, context);- expect(statusUpdate.isError).not.toBe(true);- expect(await tasks.getTask(uid, target.project.project_id, userCreated.task.id)).toMatchObject({- status: 'progress',- });- expect(await tasks.getTask(uid, target.project.project_id, userCreated.task.id)).not.toHaveProperty('origin_cid');- const completedByConversation = await tasks.createTask(uid, target.project.project_id, { content: 'Completion-only task' });- if (!completedByConversation.ok) throw new Error('complete-linked task fixture failed');- const completed = await tool.execute({- action: 'complete',- project: target.project.project_id,- task_id: completedByConversation.task.id,- }, context);- expect(completed.isError).not.toBe(true);- expect(await tasks.getTask(uid, target.project.project_id, completedByConversation.task.id)).toMatchObject({- status: 'done',- });- expect(await tasks.getTask(uid, target.project.project_id, completedByConversation.task.id)).not.toHaveProperty('origin_cid');- const titleOnly = await tasks.createTask(uid, target.project.project_id, { content: 'Title-only task' });- if (!titleOnly.ok) throw new Error('content-only task fixture failed');- await tool.execute({- action: 'update',- project: target.project.project_id,- task_id: titleOnly.task.id,- content: 'Title-only edit',- }, context);- expect((await tasks.getTask(uid, target.project.project_id, titleOnly.task.id))?.origin_cid).toBeUndefined();- expect(await tasks.listTasks(uid, other.project.project_id)).toEqual([]);- for (const project of ['missing', '../different-account', foreign.project.project_id]) {- const rejected = await tool.execute({ ...request, project }, context);- expect(rejected.isError).toBe(true);- expect(JSON.parse(rejected.content).error).toContain('project_not_found');- }- expect(await tasks.listTasks('different-account', foreign.project.project_id)).toEqual([]);- expect(built.resolvedSystemPrompt).toBe(initialPrompt);- expect(built.turnEphemeral).toBe(initialTail);+ expect(built.resolvedSystemPrompt + built.turnEphemeral).not.toContain('PRIVATE_PROJECT_TASK');const next = await buildRunner({ sessionId: 'gconv-unbound-project-tasks', userId: uid, cid: 'outside-project' });- expect(next.runner.getActiveToolDefinitions().map((entry) => entry.name)).not.toContain('todo_tasks');+ expect(next.runner.getActiveToolDefinitions().map(tool => tool.name)).not.toContain('todo_tasks');names.mockRestore();});- it('rejects ambiguous or stale unbound project targets and preserves bound Agent isolation', async () => {+ it('preserves bound Agent backlog access and rejects other scopes', async () => {process.env.ORKAS_TOOL_LOADING_MODE = 'scoped';const uid = 'runner-project-target-boundaries';await configureUser(uid);@@ -1176,24 +1216,7 @@ describe('runner › scoped tool loading', () => {const second = await projects.createProject(uid, 'B');if (!first.ok || !second.ok) throw new Error('project fixture failed');const { buildRunner } = await loadRunner();- // Synced/legacy duplicate names are possible even though create rejects them.- const duplicateNames = vi.spyOn(projects, 'listProjectNameRows').mockResolvedValue([- { project_id: first.project.project_id, name: 'Same' },- { project_id: second.project.project_id, name: 'Same' },- ]);- const built = await buildRunner({ sessionId: 'gconv-project-target-boundaries', userId: uid });- const runner = built.runner as any;const context = { state: {} };- await runner.tools.get('tool_load').execute({ groups: ['management.projects'] }, context);- const rejected = await runner.tools.get('todo_tasks').execute({ action: 'create', project: 'Same', content: 'Do it' }, context);- expect(rejected.isError).toBe(true);- expect(JSON.parse(rejected.content).candidates).toHaveLength(2);- expect(await tasks.listTasks(uid, first.project.project_id)).toEqual([]);- expect(await tasks.listTasks(uid, second.project.project_id)).toEqual([]);- duplicateNames.mockResolvedValue([{ project_id: first.project.project_id, name: 'A' }]);- await projects.deleteProject(uid, second.project.project_id);- expect((await runner.tools.get('todo_tasks').execute({ action: 'list', project: second.project.project_id }, context)).isError).toBe(true);-const agentTask = await tasks.createTask(uid, first.project.project_id, { content: 'AGENT_BACKLOG_ON_DEMAND' });if (!agentTask.ok) throw new Error('agent task fixture failed');const agent = await buildRunner({@@ -1243,6 +1266,23 @@ describe('runner › scoped tool loading', () => {expect(await tasks.getTask(uid, '', createdGlobal.task.id)).toMatchObject({ content: 'Global work' });expect((await globalTodo.execute({ action: 'complete', task_id: createdGlobal.task.id, project: '__global__' }, context)).isError).toBeFalsy();expect((await tasks.getTask(uid, '', createdGlobal.task.id))?.status).toBe('done');+ const foreign = await tasks.createTask(uid, second.project.project_id, { content: 'OTHER_PROJECT_TASK' });+ if (!foreign.ok) throw new Error('foreign task fixture failed');+ const projectCommander = await buildRunner({+ sessionId: 'gconv-project-target-boundaries', userId: uid, projectId: first.project.project_id,+ });+ for (const tool of [bound, (projectCommander.runner as any).tools.get('todo_tasks')]) {+ const listed = JSON.parse((await tool.execute({ action: 'list' }, context)).content).tasks;+ expect(listed).not.toContainEqual(expect.objectContaining({ id: createdGlobal.task.id }));+ expect(listed).not.toContainEqual(expect.objectContaining({ id: foreign.task.id }));+ for (const task_id of [createdGlobal.task.id, foreign.task.id]) {+ expect((await tool.execute({ action: 'get', task_id }, context)).isError).toBe(true);+ expect((await tool.execute({ action: 'complete', task_id }, context)).isError).toBe(true);+ }+ expect((await tool.execute({ action: 'list', project: '__global__' }, context)).isError).toBe(true);+ }+ expect(await tasks.getTask(uid, second.project.project_id, foreign.task.id)).toMatchObject({ status: 'todo' });+ expect(await tasks.getTask(uid, '', createdGlobal.task.id)).toMatchObject({ status: 'done' });for (const input of [{ action: 'get', task_id: agentTask.task.id },{ action: 'complete', task_id: agentTask.task.id },@@ -1254,7 +1294,6 @@ describe('runner › scoped tool loading', () => {const autoStore = await import('../../../src/main/features/auto_tasks');expect(await autoStore.getTask(uid, auto.taskId)).not.toHaveProperty('project_id');- duplicateNames.mockRestore();});it('keeps reflection on its fixed tools and skips ordinary Skills even under legacy rollback', async () => {@@ -1710,6 +1749,38 @@ describe('runner › scoped tool loading', () => {expect(after.content).toContain('Use this exact Skill.');});+ it('gives project follow-up guidance to final deliverers, never workers or intermediate Agents', async () => {+ const uid = 'runner-project-followup';+ await configureUser(uid);+ const chats = await import('../../../src/main/features/chats');+ const projects = await import('../../../src/main/features/projects');+ const created = await projects.createProject(uid, 'Recurring reports');+ if (!created.ok) throw new Error('project fixture failed');+ const conv = await chats.createConversation(uid, { title: 'Weekly report' });+ const cid = conv.conversation_id;+ expect((await chats.moveConversationToProject(uid, cid, created.project.project_id)).ok).toBe(true);+ const { buildRunner } = await loadRunner();+ for (const kind of ['gconv', 'gmember', 'gworker']) {+ const built = await buildRunner({+ sessionId: `${kind}-${cid}-${CONTENT_WRITER_AGENT_ID}`, userId: uid, cid,+ projectId: created.project.project_id,+ ...(kind === 'gmember' ? { agentId: CONTENT_WRITER_AGENT_ID, toolList: ['workspace.read'] } : {}),+ });+ expect(built.turnEphemeral.includes('schedule it in this reply')).toBe(kind !== 'gworker');+ expect(built.turnEphemeral).not.toContain('sentence offering a project for it');+ expect(built.turnEphemeral).not.toContain('this conversation belongs to no project');+ expect(built.resolvedSystemPrompt).not.toContain('## Keeping work going');+ expect(built.resolvedSystemPrompt).not.toContain('## Giving work a project');+ }+ const intermediate = await buildRunner({+ sessionId: `gmember-${cid}-${CONTENT_WRITER_AGENT_ID}`, userId: uid, cid,+ agentId: CONTENT_WRITER_AGENT_ID, outputDelivery: 'process',+ toolList: ['workspace.read'], projectId: created.project.project_id,+ });+ expect(intermediate.turnEphemeral).not.toContain('## Keeping work going');+ expect(intermediate.toolDefs.map(tool => tool.name)).not.toContain('create_project');+ });+it('preloads Commander command, web, Skill search, and app navigation while mutation tools stay dormant', async () => {process.env.ORKAS_TOOL_LOADING_MODE = 'scoped';const uid = 'runner-scoped-global-skill-discovery';diff --git a/test/main/util/proxy-dispatcher.test.ts b/test/main/util/proxy-dispatcher.test.tsindex 506ce901..be34a1ef 100644--- a/test/main/util/proxy-dispatcher.test.ts+++ b/test/main/util/proxy-dispatcher.test.ts@@ -3,6 +3,8 @@ import * as fs from 'node:fs';import { createServer } from 'node:http';import { EventEmitter } from 'node:events';import { connect } from 'node:net';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';import {_resetProxyRoutingForTests,activeProxy,@@ -24,6 +26,7 @@ import {} from '../../../src/main/util/proxy-dispatcher';import { classifyTransientNetworkError } from '../../../src/core-agent/src/shared/errors';+const hostFetch = globalThis.fetch;const proxyEnvKeys = ['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy',@@ -58,6 +61,41 @@ afterEach(() => {});describe('Electron system-proxy transport failures', () => {+ it('survives a truncated response with excessive content encodings and can download again', async () => {+ // GHSA-xjj6-f33q-929c kills the process even when fetch rejection is caught.+ // Exercise the real address-checked download route in an isolated process.+ const script = String.raw`+ require('tsx/cjs');+ const { createServer } = require('node:net');+ const { downloadBinaryWithProxyPolicy } = require('./src/main/util/proxy-dispatcher.ts');+ let requests = 0;+ const server = createServer(socket => socket.once('data', () => {+ requests++;+ socket.end(requests === 1+ ? 'HTTP/1.1 200 OK\r\nContent-Encoding: gzip,gzip,gzip,gzip,gzip,gzip\r\nContent-Length: 100\r\nConnection: close\r\n\r\n'+ : 'HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok');+ }));+ server.listen(0, '127.0.0.1', async () => {+ const url = 'http://127.0.0.1:' + server.address().port;+ const options = { label: 'encoding-regression', isAllowedDirectAddress: ip => ip === '127.0.0.1', signal: AbortSignal.timeout(3000), retries: 0 };+ try {+ let rejected = false;+ try { await downloadBinaryWithProxyPolicy(url, options); } catch { rejected = true; }+ if (!rejected) throw new Error('Malformed response was accepted');+ const result = await downloadBinaryWithProxyPolicy(url, options);+ if (result.body.toString() !== 'ok' || requests !== 2) throw new Error('Recovery failed');+ process.stdout.write('rejected-and-recovered');+ } catch (error) { process.stderr.write(String(error)); process.exitCode = 1; }+ finally { server.close(); }+ });+ `;+ const result = await promisify(execFile)(process.execPath, ['-e', script], {+ cwd: process.cwd(), env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, timeout: 10000,+ });+ expect(result.stderr).toBe('');+ expect(result.stdout).toBe('rejected-and-recovered');+ });+it('uploads through the configured environment proxy with byte progress and no system-route lookup', async () => {const {getGlobalDispatcher, setGlobalDispatcher} = await import('undici');const original = getGlobalDispatcher();@@ -389,6 +427,60 @@ describe('util/proxy-dispatcher child fetch bridge', () => {}});+ it('keeps native bridge response bodies readable across settled garbage collection', async () => {+ const script = String.raw`+ const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict');+ const {createRequire}=require('node:module');+ const root=fs.mkdtempSync(path.join(os.tmpdir(),'orkas-proxy-body-review-'));+ process.env.ORKAS_WORKSPACE_ROOT=root;+ const req=createRequire(path.resolve('package.json'));+ req('tsx/cjs');+ const logger=path.resolve('src/main/logger.ts');+ require.cache[logger]={exports:{createLogger:()=>({debug(){},info(){},warn(){},error(){}})}};+ const {startChildFetchBridge}=require(path.resolve('src/main/util/proxy-dispatcher.ts'));+ const {createBridgeFetch}=req('./bin/proxy-bootstrap.cjs');+ (async()=>{+ const bridge=await startChildFetchBridge(async(input,init)=>new Response(String(input)+'|'+(init?.body?await new Response(init.body).text():'')));+ try{+ const fetchChild=createBridgeFetch(globalThis.fetch,bridge.url,bridge.token);+ for(let i=0;i<20;i++){+ const direct=await fetchChild('https://direct.example/path');+ await new Promise(resolve=>setImmediate(resolve));if(global.gc)global.gc();await new Promise(resolve=>setImmediate(resolve));+ const proxied=await fetchChild('https://proxy.example/upload',{method:'POST',body:'stream-me'});+ await new Promise(resolve=>setImmediate(resolve));if(global.gc)global.gc();await new Promise(resolve=>setImmediate(resolve));+ assert.equal(await direct.text(),'https://direct.example/path|');+ assert.equal(await proxied.text(),'https://proxy.example/upload|stream-me');+ }+ console.log(JSON.stringify({iterations:20,requests:40,forced_gc:!!global.gc,body_reuse_failure:false}));+ }finally{await bridge.close();fs.rmSync(root,{recursive:true,force:true});}+ })().catch(error=>{console.error(error);process.exitCode=1;});+ `;+ const result = await promisify(execFile)(process.execPath, ['--expose-gc', '-e', script], {+ cwd: process.cwd(), env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },+ timeout: 15000, maxBuffer: 16 * 1024,+ });+ expect(result.stderr).toBe('');+ expect(JSON.parse(result.stdout)).toEqual({ iterations: 20, requests: 40, forced_gc: true, body_reuse_failure: false });+ });++ it('preserves a bodyless bridge response and propagates a source stream failure', async () => {+ const { createBridgeFetch } = require('../../../bin/proxy-bootstrap.cjs');+ const meta = (status: number) => ({ 'x-orkas-fetch-meta': Buffer.from(JSON.stringify({+ status, statusText: '', headers: [['x-upstream', 'fixture']],+ })).toString('base64url') });+ const emptyFetch = createBridgeFetch(async () => new Response(null, { headers: meta(204) }), 'http://localhost/bridge', 'fixture');+ const empty = await emptyFetch('https://upstream.example');+ expect(empty.status).toBe(204);+ expect(empty.body).toBeNull();+ expect(empty.headers.get('x-upstream')).toBe('fixture');+ const failure = new Error('controlled upstream stream failure');+ const failedFetch = createBridgeFetch(async () => new Response(new ReadableStream({+ start(controller) { controller.error(failure); },+ }), { headers: meta(200) }), 'http://localhost/bridge', 'fixture');+ const failed = await failedFetch('https://upstream.example');+ await expect(failed.text()).rejects.toBe(failure);+ });+it('cancels the Electron response stream when the child stops reading', async () => {let upstreamCancelled = false;const system = vi.fn(async () => new Response(new ReadableStream<Uint8Array>({