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
Preserve native HTML preview verification and artifacts
wyt922dbde0cf76
diff --git a/src/main/features/html_preview.ts b/src/main/features/html_preview.tsindex 74e126e9..4d22e927 100644--- a/src/main/features/html_preview.ts+++ b/src/main/features/html_preview.ts@@ -8,7 +8,7 @@ import type { BrowserWindow as ElectronBrowserWindow, Session } from 'electron';import { createPreviewSdk, previewBundle, previewPreload, type PreviewSdkEvidence } from './web_apps/preview';import type { Bundle } from './web_apps/runtime';-import { ARTIFACT_FRAME } from './chat_artifacts';+import { ARTIFACT_FRAME, mimeFor as artifactMimeFor } from './chat_artifacts';import * as chatAttachments from './chat_attachments';import { chatMediaLocalPathFromUrl, chatMediaLocalUrl } from '../util/chat-media-url';import { serveFileRange } from '../util/http-range';@@ -18,6 +18,7 @@ import { hardenedWebPreferences, withHtmlPreviewAssetPolicy, withHtmlPreviewPoliconst HTML_PREVIEW_TIMEOUT_MS = 20_000;const HTML_PREVIEW_MAX_BLOCKED_RESOURCE_SAMPLES = 8;const HTML_PREVIEW_MAX_DIAGNOSTICS = 12;+const HTML_PREVIEW_MAX_INLINE_DOWNLOAD_URL_CHARS = 2 * 1024 * 1024;const HTML_PREVIEW_MAX_INTERACTION_SAMPLES = 10;const HTML_PREVIEW_MAX_DIAGNOSTIC_CHARS = 400;const HTML_PREVIEW_DESIGN_MAX_ELEMENTS = 4_000;@@ -149,6 +150,8 @@ export interface HtmlPreviewInteractionEvidence {export interface HtmlPreviewEvidence {sdk?: PreviewSdkEvidence;+ /** Per-viewport observations, not a functional verdict or delivery gate. */+ sdkByViewport?: Array<PreviewSdkEvidence & { viewport: HtmlPreviewViewportName }>;ok: boolean;entryPath: string;blockedResourceCount: number;@@ -183,6 +186,8 @@ export interface HtmlPreviewRuntimeDeps {export interface HtmlPreviewRenderOptions {interactions?: boolean;+ /** Host-owned chat artifact bridge, served without changing the artifact files. */+ bridgeJavaScript?: string;/** Check a plain page the way the chat file viewer shows it: through* `chat-media://local` with the viewer's sandbox (no storage, CORS-gated* assets). Generated artifacts render in `chat-app://` and keep the default. */@@ -763,6 +768,12 @@ const INTERACTION_SCRIPT = `(async () => {|| element.tagName|| 'control').replace(/\\s+/g, ' ').trim().slice(0, 120);+ // SVG role controls have no HTMLElement.click(), but receive DOM click+ // events. Keep native activation for HTML controls (forms and downloads).+ const activateControl = (control) => {+ if (typeof control.click === 'function') control.click();+ else control.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));+ };const failures = [];const warnings = [];const reportedTransforms = new Set();@@ -906,7 +917,7 @@ const INTERACTION_SCRIPT = `(async () => {const downloadCandidates = downloadControls.map(label);for (const control of downloadControls) {try {- control.click();+ activateControl(control);controlsExercised += 1;await sleep(120);} catch (error) {@@ -1041,7 +1052,7 @@ const INTERACTION_SCRIPT = `(async () => {control.hasAttribute?.('aria-current')&& control.getAttribute?.('aria-current') !== 'false');- control.click();+ activateControl(control);exercisedStateControls.add(control);controlsExercised += 1;stateControlsExercised += 1;@@ -1285,9 +1296,15 @@ function registerNetworkIsolation(entryRootReal: string,blocked: { count: number; samples: string[] },sdkOrigin: { current?: string },+ bridgeJavaScript?: string,): void {+ const bridgeUrl = pathToFileURL(path.join(entryRootReal, '__orkas', 'bridge.js')).href;ses.webRequest.onBeforeRequest((details, callback) => {const raw = String(details.url || '');+ if (bridgeJavaScript && raw === bridgeUrl) {+ callback({ cancel: false });+ return;+ }const allowed = sdkOrigin.current? /^(?:https?|wss?|data|blob|about):/i.test(raw) || raw.startsWith(sdkOrigin.current + '/'): allowedPreviewRequest(raw, entryRootReal);@@ -1305,6 +1322,25 @@ function registerNetworkIsolation(});}+/** Serve the reserved host bridge without copying or modifying an app bundle. */+function registerArtifactPreviewProtocol(ses: Session, entryRootReal: string, bridgeJavaScript: string): void {+ const bridgePath = path.join(entryRootReal, '__orkas', 'bridge.js');+ ses.protocol.handle('file', (request) => {+ try {+ const requested = fileURLToPath(request.url);+ if (requested === bridgePath) {+ return new Response(bridgeJavaScript, { headers: { 'Content-Type': 'text/javascript; charset=utf-8' } });+ }+ if (!isPathAllowed(requested, [entryRootReal])) return new Response('', { status: 403 });+ const st = fs.statSync(requested);+ if (!st.isFile()) return new Response('', { status: 404 });+ return serveFileRange(request, requested, artifactMimeFor(requested), st.size, st.mtimeMs);+ } catch {+ return new Response('', { status: 404 });+ }+ });+}+function previewFailureStatus(code: string | undefined): number {if (code === 'bad_input') return 400;if (code === 'forbidden') return 403;@@ -1381,6 +1417,7 @@ function registerPermissionIsolation(ses: Session): void {async function clearPreviewSession(ses: Session): Promise<void> {try { ses.webRequest.onBeforeRequest(null); } catch { /* best effort */ }try { if (ses.protocol?.isProtocolHandled('chat-media')) ses.protocol.unhandle('chat-media'); } catch { /* best effort */ }+ try { if (ses.protocol?.isProtocolHandled('file')) ses.protocol.unhandle('file'); } catch { /* best effort */ }try { ses.removeAllListeners('will-download'); } catch { /* best effort */ }try { ses.setPermissionCheckHandler(null); } catch { /* best effort */ }try { ses.setPermissionRequestHandler(null); } catch { /* best effort */ }@@ -1556,11 +1593,13 @@ export async function renderResponsiveHtmlPreview(const ses = electronSession.fromPartition(partition);registerPermissionIsolation(ses);try {- registerNetworkIsolation(ses, entryRootReal, blocked, sdkOrigin);+ registerNetworkIsolation(ses, entryRootReal, blocked, sdkOrigin, options.bridgeJavaScript);// SDK app bundles keep their own shell (see createPreviewSdk).const fileViewer = !bundle && options.fileViewer === true;if (fileViewer) registerLocalPreviewProtocol(ses, entryRootReal);+ else if (!bundle && options.bridgeJavaScript) registerArtifactPreviewProtocol(ses, entryRootReal, options.bridgeJavaScript);const downloads: HtmlPreviewDownloadEvidence[] = [];+ const inlineDownloadMeasurements: Promise<void>[] = [];ses.on('will-download', (event, item) => {const rawUrl = String(item.getURL?.() || '');const urlKind = rawUrl.startsWith('data:')@@ -1571,12 +1610,25 @@ export async function renderResponsiveHtmlPreview(? 'file': 'other';if (downloads.length < HTML_PREVIEW_MAX_DIAGNOSTICS) {- downloads.push({+ const download: HtmlPreviewDownloadEvidence = {filename: boundedDiagnostic(item.getFilename?.()),mimeType: boundedDiagnostic(item.getMimeType?.()),totalBytes: Math.max(0, Number(item.getTotalBytes?.()) || 0),urlKind,- });+ };+ downloads.push(download);+ // Electron can report an unknown zero length for data: downloads at+ // will-download. Decode only bounded inline data, without network I/O+ // or saving a file; empty or invalid payloads still fail the same check.+ if (urlKind === 'data' && download.totalBytes === 0+ && rawUrl.length <= HTML_PREVIEW_MAX_INLINE_DOWNLOAD_URL_CHARS) {+ inlineDownloadMeasurements.push(+ fetch(rawUrl, { signal: AbortSignal.timeout(1000) })+ .then(response => response.arrayBuffer())+ .then(bytes => { download.totalBytes = bytes.byteLength; })+ .catch(() => { /* retain the unavailable length */ }),+ );+ }}event.preventDefault();});@@ -1604,6 +1656,7 @@ export async function renderResponsiveHtmlPreview());}+ await Promise.all(inlineDownloadMeasurements);const blockers: string[] = [];const warnings: string[] = [];for (const item of rendered) {@@ -1709,6 +1762,8 @@ export async function renderResponsiveHtmlPreview(ok: blockers.length === 0,entryPath: entryAbs,...(rendered[0]?.sdk ? { sdk: rendered[0].sdk } : {}),+ ...(rendered.some(item => item.sdk) ? { sdkByViewport: rendered.flatMap(item =>+ item.sdk ? [{ ...item.sdk, viewport: item.evidence.name }] : []) } : {}),blockedResourceCount: blocked.count,blockedResourceSamples: blocked.samples,blockers,diff --git a/test/e2e/html_preview_e2e_artifact.spec.ts b/test/e2e/html_preview_e2e_artifact.spec.tsnew file mode 100644index 00000000..c0b6798a--- /dev/null+++ b/test/e2e/html_preview_e2e_artifact.spec.ts@@ -0,0 +1,62 @@+import { writeFileSync } from 'node:fs';+import path from 'node:path';+import { test } from './fixtures/web-app-eval';+import { expect } from './fixtures/orkas';++test('creates an app and previews its ID with a working host bridge and no workspace copy', async ({ sdkOrkas: orkas }, info) => {+ const workspaceEntry = orkas.createWorkspaceFile('preview-artifact/placeholder.txt', 'Workspace remains separate.');+ const result = await orkas.electronApp!.evaluate(async (_, args) => {+ const req = (process as any).mainModule.require.bind((process as any).mainModule);+ const { createLocalTools } = req(`${args.pcRoot}/src/main/model/core-agent/local-tools.ts`);+ const { getActiveUserId } = req(`${args.pcRoot}/src/main/features/users.ts`);+ const artifacts = req(`${args.pcRoot}/src/main/features/chat_artifacts.ts`);+ const fs = req('node:fs');+ const path = req('node:path');+ const uid = getActiveUserId();+ const cid = 'artifact-preview-e2e';+ let artifactId = '';+ const tools = createLocalTools({ userId: uid, cid,+ onArtifactCreated: (artifact: { id: string }) => { artifactId = artifact.id; } });+ const context = { workingDir: path.dirname(args.workspaceEntry), state: {} };+ const created = await tools.find((t: any) => t.name === 'create_artifact').execute({+ files: [{ path: 'index.html', content: `<!doctype html>+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <style>body{font:18px sans-serif;padding:24px;color:#173453;background:#f2f6fc}+ button{font:inherit;padding:12px;background:#173453;color:white}+ button:focus-visible{outline:3px solid #d24f00;outline-offset:3px}</style>+ <h1>Artifact preview</h1><p id="status">Ready</p><button id="send">Send update</button>+ <script src="__orkas/bridge.js"></script><script>+ document.getElementById('send').onclick=()=>{+ window.orkasArtifact.send('Preview checked');+ document.getElementById('status').textContent='Bridge worked';+ };</script>` }],+ }, context);+ const entry = artifacts.resolveArtifactFilePath(uid, cid, artifactId, 'index.html');+ const before = entry.ok ? fs.readFileSync(entry.absPath, 'utf8') : '';+ const preview = await tools.find((t: any) => t.name === 'html_preview').execute({+ artifact_id: artifactId, target: 'responsive', screenshots: true,+ }, context);+ const other = createLocalTools({ userId: uid, cid: 'other-conversation' });+ const rejected = await other.find((t: any) => t.name === 'html_preview').execute({ artifact_id: artifactId }, context);+ return { createdError: created.isError, artifactId, preview, rejected,+ sourceUnchanged: entry.ok && fs.readFileSync(entry.absPath, 'utf8') === before,+ workspaceCopy: fs.existsSync(path.join(context.workingDir, 'index.html')),+ bridgeOnDisk: entry.ok && fs.existsSync(path.join(path.dirname(entry.absPath), '__orkas', 'bridge.js')) };+ }, { pcRoot: path.resolve(__dirname, '../..'), workspaceEntry });+ writeFileSync(info.outputPath('artifact-preview.json'), JSON.stringify({ ...result,+ preview: { ...result.preview, images: undefined } }, null, 2));+ expect(result.createdError).toBeUndefined();+ expect(result.preview.isError, result.preview.content).toBeUndefined();+ const evidence = JSON.parse(result.preview.content);+ expect(evidence).toMatchObject({ ok: true, artifact_id: result.artifactId, blockedResourceCount: 0 });+ expect(evidence).not.toHaveProperty('entryPath');+ expect(evidence.interactions.artifactMessagesObserved).toBeGreaterThan(0);+ expect(evidence.interactions.stateChangesObserved).toBeGreaterThan(0);+ expect(result.preview.images).toHaveLength(2);+ result.preview.images.forEach((image: { data: string }, index: number) =>+ writeFileSync(info.outputPath(`artifact-${index}.webp`), Buffer.from(image.data, 'base64')));+ expect(result.rejected.isError).toBe(true);+ expect(result.sourceUnchanged).toBe(true);+ expect(result.workspaceCopy).toBe(false);+ expect(result.bridgeOnDisk).toBe(false);+});diff --git a/test/e2e/html_preview_e2e_generated_controls.spec.ts b/test/e2e/html_preview_e2e_generated_controls.spec.tsindex 2c3a72f2..80dc95de 100644--- a/test/e2e/html_preview_e2e_generated_controls.spec.ts+++ b/test/e2e/html_preview_e2e_generated_controls.spec.ts@@ -4,6 +4,66 @@ import { test } from './fixtures/web-app-eval';import { expect } from './fixtures/orkas';import type { HtmlPreviewDesignEvidence } from '../../src/main/features/html_preview';+test('exercises SVG diagram controls and downloads without losing native controls or disabled exclusions', async ({ sdkOrkas: orkas }, info) => {+ const entry = orkas.createWorkspaceFile('svg-controls/index.html', `<!doctype html>+ <style>button:focus-visible,[tabindex]:focus-visible{outline:2px solid blue}</style>+ <button onclick="document.getElementById('detail').textContent='Native selected'">Native control</button>+ <svg viewBox="0 0 420 180" width="420" style="max-width:100%;height:auto" aria-label="Architecture">+ <g role="button" tabindex="0" aria-label="Diagram detail" onclick="document.getElementById('detail').textContent='Diagram selected'">+ <rect width="120" height="40" fill="blue"/><text y="20" fill="white">Diagram</text>+ </g>+ <g role="tab" tabindex="0" aria-label="Unwired detail" transform="translate(140 0)">+ <rect width="120" height="40" fill="gray"/>+ </g>+ <g role="button" tabindex="0" aria-label="Download diagram" transform="translate(0 60)"+ onclick="const a=document.createElement('a');a.download='diagram.txt';a.href='data:text/plain,Diagram';a.click()">+ <rect width="120" height="40" fill="green"/>+ </g>+ <g role="button" aria-disabled="true" aria-label="Disabled detail" transform="translate(140 60)"+ onclick="console.error('Disabled control was activated')"><rect width="120" height="40"/></g>+ <g role="button" aria-label="Hidden detail" style="display:none"+ onclick="console.error('Hidden control was activated')"><rect width="120" height="40"/></g>+ </svg><p id="detail">Choose a component</p>`);+ for (const artifact of [false, true]) {+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {+ const preview = (process as any).mainModule.require(args.modulePath);+ return (await (args.artifact ? preview.renderInteractiveHtmlSmoke(args.entry)+ : preview.renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 1280, height: 800 }]))).evidence;+ }, { entry, artifact, modulePath: path.resolve(__dirname, '../../src/main/features/html_preview.ts') });+ writeFileSync(info.outputPath(`svg-controls-${artifact}.json`), JSON.stringify({ ...evidence, entryPath: undefined }, null, 2));+ expect(evidence.ok).toBe(true);+ expect(evidence.blockers).toEqual([]);+ expect(evidence.viewports.every(view => view.consoleErrors.length === 0)).toBe(true);+ expect(evidence.interactions).toMatchObject({ controlsExercised: 4, stateControlsExercised: 3,+ stateTransitionsObserved: 2, failures: [], warnings: ['enabled control produced no observable outcome: Unwired detail'] });+ expect(evidence.interactions.downloads).toEqual([{+ filename: 'diagram.txt', mimeType: 'text/plain', totalBytes: 7, urlKind: 'data',+ }]);+ }+});++for (const empty of [false, true]) {+ test(`measures an inline resume download (${empty ? 'empty' : 'nonempty'})`, async ({ sdkOrkas: orkas }, info) => {+ const content = empty ? '' : '简历\nProduct designer\nExperience and contact details.';+ const entry = orkas.createWorkspaceFile('inline-resume/index.html', `<!doctype html>+ <style>a:focus-visible{outline:2px solid blue}</style>+ <a download="resume.txt" href="data:text/plain;charset=utf-8,${encodeURIComponent(content)}">Download resume</a>`);+ for (const artifact of [false, true]) {+ const evidence = await orkas.electronApp!.evaluate(async (_, args) => {+ const preview = (process as any).mainModule.require(args.modulePath);+ return (await (args.artifact ? preview.renderInteractiveHtmlSmoke(args.entry)+ : preview.renderResponsiveHtmlPreview(args.entry, [{ name: 'desktop', width: 1280, height: 800 }], {},+ { fileViewer: true }))).evidence;+ }, { entry, artifact, modulePath: path.resolve(__dirname, '../../src/main/features/html_preview.ts') });+ writeFileSync(info.outputPath(`inline-resume-${artifact}.json`), JSON.stringify({ ...evidence, entryPath: undefined }, null, 2));+ expect(evidence.interactions.downloads).toEqual([{+ filename: 'resume.txt', mimeType: 'text/plain', totalBytes: Buffer.byteLength(content), urlKind: 'data',+ }]);+ expect(evidence.ok).toBe(!empty);+ }+ });+}+for (const broken of [false, true]) {test(`fills an editor before download and retains empty-payload rejection (${broken ? 'broken' : 'working'})`, async ({ sdkOrkas: orkas }, info) => {const entry = orkas.createWorkspaceFile('editor/index.html', `<!doctype html>diff --git a/test/main/features/html_preview.test.ts b/test/main/features/html_preview.test.tsindex 24d824a5..8fcac08c 100644--- a/test/main/features/html_preview.test.ts+++ b/test/main/features/html_preview.test.ts@@ -3,7 +3,7 @@ import * as os from 'node:os';import * as path from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ARTIFACT_FRAME } from '../../../src/main/features/chat_artifacts';import { chatMediaLocalPathFromUrl, chatMediaLocalUrl } from '../../../src/main/util/chat-media-url';@@ -54,6 +54,7 @@ function fakeRuntime(options: {downloadCandidate?: boolean;downloadObserved?: boolean;downloadBytes?: number;+ downloadUrl?: string;keyboardFocusIndicator?: boolean;controlsExercised?: number;stateChangesObserved?: number;@@ -75,7 +76,7 @@ function fakeRuntime(options: {deps: HtmlPreviewRuntimeDeps;evidenceScripts: string[];windows: Array<{ options: Record<string, any>; destroyed: boolean }>;- requestDecisions: Array<{ url: string; cancel: boolean }>;+ requestDecisions: Array<{ url: string; cancel: boolean; redirectURL?: string }>;permissionDecisions: {check: boolean[];request: boolean[];@@ -90,7 +91,7 @@ function fakeRuntime(options: {registeredProtocolHandlers: Array<(request: Request) => Response | Promise<Response>>;} {const windows: Array<{ options: Record<string, any>; destroyed: boolean }> = [];- const requestDecisions: Array<{ url: string; cancel: boolean }> = [];+ const requestDecisions: Array<{ url: string; cancel: boolean; redirectURL?: string }> = [];const permissionDecisions = {check: [] as boolean[],request: [] as boolean[],@@ -104,7 +105,7 @@ function fakeRuntime(options: {const evidenceScripts: string[] = [];const protocolHandlers = new Map<string, (request: Request) => Response | Promise<Response>>();const registeredProtocolHandlers: Array<(request: Request) => Response | Promise<Response>> = [];- let requestHandler: ((details: { url: string }, callback: (decision: { cancel: boolean }) => void) => void) | undefined;+ let requestHandler: ((details: { url: string }, callback: (decision: { cancel: boolean; redirectURL?: string }) => void) => void) | undefined;const sessionListeners = new Map<string, Function>();let tabKeyDowns = 0;@@ -142,7 +143,7 @@ function fakeRuntime(options: {sessionListeners.get('will-download')?.({ preventDefault: () => undefined },{- getURL: () => 'blob:file-preview',+ getURL: () => options.downloadUrl ?? 'blob:file-preview',getFilename: () => 'resume.txt',getMimeType: () => 'text/plain',getTotalBytes: () => options.downloadBytes ?? 128,@@ -199,7 +200,7 @@ function fakeRuntime(options: {requestHandler?.({ url }, (decision) => requestDecisions.push({ url, cancel: decision.cancel }));if (options.loadFailure) throw new Error('synthetic preview load failure');for (const extra of options.extraRequests ?? []) {- requestHandler?.({ url: extra }, (decision) => requestDecisions.push({ url: extra, cancel: decision.cancel }));+ requestHandler?.({ url: extra }, (decision) => requestDecisions.push({ url: extra, ...decision }));}if (options.externalRequest) {const external = 'https://example.invalid/tracker.png';@@ -479,6 +480,28 @@ describe('responsive HTML preview renderer', () => {]);});+ it('serves only the host artifact bridge virtually while retaining local containment', async () => {+ const bridgeUrl = pathToFileURL(path.join(fs.realpathSync(root), '__orkas', 'bridge.js')).href;+ const outside = pathToFileURL(path.join(root, '..', 'private.html')).href;+ const runtime = fakeRuntime({ extraRequests: [bridgeUrl, outside] });+ await renderResponsiveHtmlPreview(path.join(root, 'index.html'), viewports, runtime.deps,+ { bridgeJavaScript: 'window.orkasArtifact = { send() {} };' });+ const bridge = runtime.requestDecisions.find(item => item.url === bridgeUrl)!;+ expect(bridge.cancel).toBe(false);+ const handler = runtime.registeredProtocolHandlers[0];+ const response = await handler(new Request(bridgeUrl));+ expect(response.headers.get('Content-Type')).toBe('text/javascript; charset=utf-8');+ expect(await response.text()).toBe('window.orkasArtifact = { send() {} };');+ expect((await handler(new Request(outside))).status).toBe(403);+ const entry = await handler(new Request(pathToFileURL(path.join(root, 'index.html')).href));+ expect(entry.headers.get('Content-Type')).toBe('text/html; charset=utf-8');+ expect(await entry.text()).toContain('<main>Preview</main>');+ expect(runtime.protocolHandlers.has('file')).toBe(false);+ expect(runtime.requestDecisions.find(item => item.url === outside)).toMatchObject({ cancel: true });+ expect(fs.existsSync(path.join(root, '__orkas'))).toBe(false);+ expect(runtime.sessionCleanup).toEqual({ cache: true, storage: true });+ });+it('records observed download metadata and rejects a download control that produces nothing', async () => {const observed = fakeRuntime({ downloadCandidate: true, downloadObserved: true });const passed = await renderResponsiveHtmlPreview(@@ -524,6 +547,37 @@ describe('responsive HTML preview renderer', () => {);});+ it.each([+ ['data:text/plain;charset=utf-8,%E7%AE%80%E5%8E%86%0AResume', 13],+ ['data:application/octet-stream,%00%FF%01', 3],+ ['data:text/plain;base64,UmVzdW1l', 6],+ ['data:text/plain,', 0],+ ['data:text/plain;base64,', 0],+ ['data:text/plain;base64,%%%%', 0],+ ])('measures inline download bytes when Electron has not reported a length: %s', async (downloadUrl, expectedBytes) => {+ const runtime = fakeRuntime({ downloadCandidate: true, downloadObserved: true, downloadBytes: 0, downloadUrl });+ const result = await renderResponsiveHtmlPreview(path.join(root, 'index.html'), viewports, runtime.deps);+ expect(result.evidence.interactions.downloads[0]).toMatchObject({ totalBytes: expectedBytes, urlKind: 'data' });+ expect(result.evidence.ok).toBe(expectedBytes > 0);+ });++ it('does not fetch remote downloads or decode oversized inline payloads to infer an unknown length', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ try {+ for (const downloadUrl of [+ 'https://example.invalid/private-download',+ 'data:text/plain,' + 'x'.repeat(2 * 1024 * 1024),+ ]) {+ const runtime = fakeRuntime({ downloadCandidate: true, downloadObserved: true, downloadBytes: 0, downloadUrl });+ const result = await renderResponsiveHtmlPreview(path.join(root, 'index.html'), viewports, runtime.deps);+ expect(result.evidence.interactions.downloads[0].totalBytes).toBe(0);+ expect(fetchSpy).not.toHaveBeenCalled();+ }+ } finally {+ fetchSpy.mockRestore();+ }+ });+it('rejects keyboard traversal when focused controls have no visible indicator', async () => {const runtime = fakeRuntime({ keyboardFocusIndicator: false });const result = await renderResponsiveHtmlPreview(diff --git a/test/main/model/core-agent/html-preview-tool.test.ts b/test/main/model/core-agent/html-preview-tool.test.tsindex 4d234f25..4427d7f5 100644--- a/test/main/model/core-agent/html-preview-tool.test.ts+++ b/test/main/model/core-agent/html-preview-tool.test.ts@@ -216,7 +216,7 @@ describe('html_preview tool', () => {const { tool } = await buildTool();expect(tool.inputSchema).toMatchObject({- required: ['path'],+ required: [],properties: {target: {default: 'desktop',@@ -233,7 +233,8 @@ describe('html_preview tool', () => {},});const properties = tool.inputSchema.properties as any;- expect(tool.description).toContain('isolated, network-blocked browser');+ expect(tool.description).toContain('isolated browser');+ expect(properties.artifact_id.description).toContain('current conversation');expect(properties.target.description).toContain('Defaults to desktop');expect(properties.target.description).toContain('responsive only when viewport-dependent reflow is explicitly requested');expect(properties.screenshots.description).toContain('Defaults to false');@@ -241,6 +242,126 @@ describe('html_preview tool', () => {expect(properties.interactions.description).toContain('Set false for visual-only UI review');});+ it('previews a newly created conversation app by its durable ID without a workspace copy', async () => {+ const { render, workspace, context, screenshots } = await buildTool();+ const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');+ let artifactId = '';+ const create = createLocalTools({+ userId: UID, cid: CID,+ artifactInteractionSmoke: async () => ({ ok: true, blockers: [], warnings: [] }),+ onArtifactCreated: (artifact) => { artifactId = artifact.id; },+ }).find(tool => tool.name === 'create_artifact')!;+ const created = await create.execute({+ files: [{ path: 'index.html', content: '<!doctype html><button>Preview</button><script src="__orkas/bridge.js"></script>' }],+ }, context);+ expect(created.isError).toBeUndefined();+ expect(artifactId).not.toBe('');+ expect(fs.existsSync(path.join(workspace, 'index.html'))).toBe(false);+ const preview = createLocalTools({ userId: UID, cid: CID }).find(tool => tool.name === 'html_preview')!;+ const result = await preview.execute({ artifact_id: artifactId, target: 'responsive', screenshots: true }, context);+ expect(result.isError).toBeUndefined();+ expect(JSON.parse(result.content)).toMatchObject({ ok: true, artifact_id: artifactId });+ expect(JSON.parse(result.content)).not.toHaveProperty('entryPath');+ const artifacts = await import('../../../../src/main/features/chat_artifacts');+ const entry = artifacts.resolveArtifactFilePath(UID, CID, artifactId, 'index.html');+ expect(entry.ok).toBe(true);+ expect(render).toHaveBeenCalledWith((entry as { absPath: string }).absPath,+ expect.arrayContaining([expect.objectContaining({ name: 'desktop' }), expect.objectContaining({ name: 'mobile' })]),+ {}, expect.objectContaining({ bridgeJavaScript: expect.any(String) }));+ expect(render.mock.calls[0][3]?.fileViewer).not.toBe(true);+ expect(fs.existsSync(path.join(path.dirname((entry as { absPath: string }).absPath), '__orkas', 'bridge.js'))).toBe(false);+ expect(result.content).not.toContain(root);+ await expectLosslessImageMatch(result.images![0], screenshots[0]);+ });++ it.each([+ {}, { artifact_id: '' }, { artifact_id: 123 }, { artifact_id: null },+ { artifact_id: 'app', path: 'index.html' }, { artifact_id: 'app', path: '' },+ { artifact_id: 'app', path: null },+ ])('rejects missing or ambiguous preview sources before rendering: %j', async (input) => {+ const { tool, render, context } = await buildTool();+ const result = await tool.execute(input, context);+ expect(result.isError).toBe(true);+ expect(result.content).toContain('E_BAD_INPUT');+ expect(render).not.toHaveBeenCalled();+ });++ it.each(['other-conversation', 'other-user', 'missing', '../index.html', 'symlink-entry', 'symlink-directory'])(+ 'does not render an inaccessible artifact (%s), even with broad local access', async (scenario) => {+ const { tool, render, context } = await buildTool();+ const permissions = await import('../../../../src/main/features/permissions');+ permissions.setLocalExecMode('all_files_auto');+ const artifacts = await import('../../../../src/main/features/chat_artifacts');+ const uid = scenario === 'other-user' ? 'another-user' : UID;+ const cid = scenario === 'other-conversation' ? 'another-conversation' : CID;+ const created = await artifacts.createArtifact(uid, cid, '', {+ files: [{ path: 'index.html', content: '<!doctype html><button>Private app</button>' }],+ });+ if (!created.ok) throw new Error('fixture creation failed');+ const resolved = artifacts.resolveArtifactDir(uid, cid, created.artifactId);+ if (!resolved.ok) throw new Error('fixture resolution failed');+ if (scenario.startsWith('symlink')) {+ const outside = path.join(root, 'outside-app');+ fs.mkdirSync(outside);+ fs.writeFileSync(path.join(outside, 'index.html'), '<button>Private</button>');+ const target = scenario === 'symlink-entry' ? path.join(resolved.dirPath, 'index.html') : resolved.dirPath;+ fs.rmSync(target, { recursive: true });+ fs.symlinkSync(scenario === 'symlink-entry' ? path.join(outside, 'index.html') : outside, target);+ }+ const artifactId = scenario === 'missing' ? 'unknown-app' : scenario === '../index.html' ? scenario : created.artifactId;+ const result = await tool.execute({ artifact_id: artifactId }, context);+ expect(result.isError).toBe(true);+ expect(result.content).not.toContain(root);+ expect(render).not.toHaveBeenCalled();+ },+ );++ it('requires a conversation binding for artifact IDs', async () => {+ const { context, render } = await buildTool();+ const { createLocalTools } = await import('../../../../src/main/model/core-agent/local-tools');+ const tool = createLocalTools({ userId: UID }).find(tool => tool.name === 'html_preview')!;+ const result = await tool.execute({ artifact_id: 'app' }, context);+ expect(result.isError).toBe(true);+ expect(result.content).toContain('E_NO_CONVERSATION');+ expect(render).not.toHaveBeenCalled();+ });++ it('rejects an app after the active account changes', async () => {+ const { context, render, tool } = await buildTool();+ const artifacts = await import('../../../../src/main/features/chat_artifacts');+ const created = await artifacts.createArtifact(UID, CID, '', {+ files: [{ path: 'index.html', content: '<button>Private app</button>' }],+ });+ if (!created.ok) throw new Error('fixture creation failed');+ const users = await import('../../../../src/main/features/users');+ users.activateUser('different-account');+ const result = await tool.execute({ artifact_id: created.artifactId }, context);+ expect(result.isError).toBe(true);+ expect(result.content).toContain('E_NO_CONVERSATION');+ expect(render).not.toHaveBeenCalled();+ });++ it('retains app layout failures and withholds screenshots without exposing its storage path', async () => {+ const { context, render, tool } = await buildTool({ ok: false, blockers: ['mobile: horizontal overflow is 28px'] });+ const artifacts = await import('../../../../src/main/features/chat_artifacts');+ const created = await artifacts.createArtifact(UID, CID, '', {+ files: [{ path: 'index.html', content: '<button>App with overflow</button>' }],+ });+ if (!created.ok) throw new Error('fixture creation failed');+ const result = await tool.execute({ artifact_id: created.artifactId, screenshots: true }, context);+ expect(result.isError).toBe(true);+ expect(result.images).toBeUndefined();+ expect(JSON.parse(result.content)).toMatchObject({+ artifact_id: created.artifactId, blockers: ['mobile: horizontal overflow is 28px'],+ visual_evidence: { attached: false, reason: 'deterministic_checks_failed' },+ });+ expect(result.content).not.toContain(root);+ render.mockRejectedValueOnce(new Error(`cannot load ${root}/private-artifact/index.html`));+ const failed = await tool.execute({ artifact_id: created.artifactId }, context);+ expect(failed.content).toContain('E_HTML_PREVIEW_FAILED');+ expect(failed.content).not.toContain(root);+ });+it('returns deterministic evidence without model images by default', async () => {const { render, tool, workspace, context } = await buildTool();fs.writeFileSync(path.join(workspace, 'index.html'), '<!doctype html><main>Audit only</main>');