diff --git a/docs/site/content/docs/editing/viewers.mdx b/docs/site/content/docs/editing/viewers.mdx index 2b16d969887..6d55ca37a3e 100644 --- a/docs/site/content/docs/editing/viewers.mdx +++ b/docs/site/content/docs/editing/viewers.mdx @@ -12,7 +12,7 @@ Open a local, SSH, or paired-runtime `.html` file with **Open in Orca Browser** The preview asks before reading additional folders, and grants only the folders you approve for that tab. External HTTP(S) links require confirmation and open in a normal Orca browser tab; downloads are disabled inside document previews. Use **Preview options** to reload from disk, open the source file, or copy its full or workspace-relative path. -On paired runtimes, the HTML file must be inside the worktree. Very old paired servers may render the document without binary assets; update the server if remote images do not load. +On paired runtimes, HTML links can also preview files outside registered workspaces. Orca uses the server's per-file access grants; no project registration or web server is needed. For these documents, the preview initially reads only the opened file and asks before loading other files from its directory. Update an older paired server if it cannot grant the file. Very old paired servers may render documents without binary assets; update the server if remote images do not load. ## Mermaid diff --git a/src/main/browser/doc-preview-file-reader.ts b/src/main/browser/doc-preview-file-reader.ts index 1e9ba54b306..8268111f17f 100644 --- a/src/main/browser/doc-preview-file-reader.ts +++ b/src/main/browser/doc-preview-file-reader.ts @@ -19,6 +19,7 @@ import { type DocPreviewGrant } from './doc-preview-grant-registry' import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { readDocPreviewTerminalFile } from './doc-preview-terminal-file-reader' const DOC_PREVIEW_READ_TIMEOUT_MS = 15_000 // Why: under files.readDocPreviewChunk's 512 KiB cap, and a multiple of 3 so its base64 has no padding. @@ -108,7 +109,7 @@ function toOutcome(source: PreviewFileBytes, contentType: string): DocPreviewRea : UNSUPPORTED_ASSET_OUTCOME } -type RuntimeDocPreviewReadParams = { +export type RuntimeDocPreviewReadParams = { worktree: string relativePath: string entryRelativePath: string @@ -212,6 +213,35 @@ function notFoundOutcome(message = 'Not found'): DocPreviewReadOutcome { return { ok: false, status: 404, reason: 'unreadable', message } } +function runtimeWorkspaceReadParams( + grant: DocPreviewGrant, + absolutePath: string +): RuntimeDocPreviewReadParams | null { + if (grant.owner.kind !== 'runtime') { + return null + } + const { worktreeRoot, worktreeSelector } = grant.owner + const worktreeRelativePath = toRuntimeWorktreeRelativePath(worktreeRoot, absolutePath) + const authority = resolveDocPreviewAuthorityPaths(grant) + const entryRelativePath = authority.entryPath + ? toRuntimeWorktreeRelativePath(worktreeRoot, authority.entryPath) + : null + if (!worktreeRelativePath || !entryRelativePath) { + return null + } + return { + worktree: worktreeSelector, + relativePath: worktreeRelativePath, + entryRelativePath, + implicitRootRelativePath: authority.implicitRootPath + ? toRuntimeWorktreeRelativeDirectoryPath(worktreeRoot, authority.implicitRootPath) + : null, + authorizedRootRelativePaths: authority.authorizedRootPaths + .map((root) => toRuntimeWorktreeRelativeDirectoryPath(worktreeRoot, root)) + .filter((root): root is string => root !== null) + } +} + export async function readDocPreviewFile( grant: DocPreviewGrant, relativePath: string @@ -235,34 +265,18 @@ export async function readDocPreviewFile( return notFoundOutcome(SSH_HOST_NOT_SERVED_MESSAGE) } const runtimeOwner = grant.owner - const worktreeRelativePath = toRuntimeWorktreeRelativePath( - runtimeOwner.worktreeRoot, - absolutePath - ) - const authority = resolveDocPreviewAuthorityPaths(grant) - const entryRelativePath = authority.entryPath - ? toRuntimeWorktreeRelativePath(runtimeOwner.worktreeRoot, authority.entryPath) - : null - const implicitRootRelativePath = authority.implicitRootPath - ? toRuntimeWorktreeRelativeDirectoryPath( - runtimeOwner.worktreeRoot, - authority.implicitRootPath - ) - : null - const authorizedRootRelativePaths = authority.authorizedRootPaths - .map((root) => toRuntimeWorktreeRelativeDirectoryPath(runtimeOwner.worktreeRoot, root)) - .filter((root): root is string => root !== null) - if (!worktreeRelativePath || !entryRelativePath) { + const terminalRead = + runtimeOwner.fileAccess === 'terminal-artifact' + ? await readDocPreviewTerminalFile(grant, absolutePath) + : null + if (terminalRead && 'preview' in terminalRead) { + return toOutcome(terminalRead.preview, contentType) + } + const params = terminalRead?.workspaceParams ?? runtimeWorkspaceReadParams(grant, absolutePath) + if (!params) { // Runtime file reads cannot address documents outside the worktree. return notFoundOutcome() } - const params: RuntimeDocPreviewReadParams = { - worktree: runtimeOwner.worktreeSelector, - relativePath: worktreeRelativePath, - entryRelativePath, - implicitRootRelativePath, - authorizedRootRelativePaths - } try { return toOutcome( await readRuntimeDocPreviewFile(runtimeOwner.environmentId, params), diff --git a/src/main/browser/doc-preview-grant-registry.ts b/src/main/browser/doc-preview-grant-registry.ts index c1cdface4c9..586e594a60a 100644 --- a/src/main/browser/doc-preview-grant-registry.ts +++ b/src/main/browser/doc-preview-grant-registry.ts @@ -10,6 +10,8 @@ export type DocPreviewOwner = worktreeSelector: string /** File reads are scoped to this root on the runtime host. */ worktreeRoot: string + /** Outside-workspace documents use the host's file grants instead of workspace reads. */ + fileAccess?: 'terminal-artifact' } export type DocPreviewGrant = { diff --git a/src/main/browser/doc-preview-terminal-file-reader.test.ts b/src/main/browser/doc-preview-terminal-file-reader.test.ts new file mode 100644 index 00000000000..d0a292e48e4 --- /dev/null +++ b/src/main/browser/doc-preview-terminal-file-reader.test.ts @@ -0,0 +1,278 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { readDocPreviewFile } from './doc-preview-file-reader' +import { + authorizeDocPreviewDirectory, + mintDocPreviewGrant, + revokeAllDocPreviewGrants +} from './doc-preview-grant-registry' + +const mocks = vi.hoisted(() => ({ call: vi.fn() })) +vi.mock('../ipc/runtime-environments/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: mocks.call +})) +vi.mock('../ipc/runtime-environments/runtime-environment-registry-root', () => ({ + getRuntimeEnvironmentRegistryRoot: () => '/user-data' +})) +vi.mock('../../shared/runtime-environment-store', () => ({ + resolveEnvironment: () => ({ id: 'vps', createdAt: 1, pairingRevision: 12 }) +})) + +function grant(root = '/tmp/reports'): ReturnType { + return mintDocPreviewGrant({ + owner: { + kind: 'runtime', + environmentId: 'vps', + worktreeSelector: 'id:source-workspace', + worktreeRoot: '/srv/repo', + fileAccess: 'terminal-artifact' + }, + requestBase: root, + root, + entryRelativePath: 'report.html', + browserPageId: 'page-1' + }) +} + +type HostEntry = { canonical?: string; openTarget?: Record } + +/** The paired host: resolveTerminalPath answers per path, reads answer with `read`. */ +function host(entries: Record, read?: unknown): void { + mocks.call.mockImplementation( + async (_root: string, _env: string, method: string, params: { pathText?: string }) => { + if (method !== 'files.resolveTerminalPath') { + return read + } + const path = params.pathText ?? '' + const entry = entries[path] ?? {} + const canonical = entry.canonical ?? path + return { + ok: true, + result: { + absolutePath: canonical, + openTarget: entry.openTarget ?? { + kind: 'absolute-file', + absolutePath: canonical, + grantId: 'host-grant' + } + } + } + } + ) +} + +function methodsCalled(): string[] { + return mocks.call.mock.calls.map((call) => String(call[2])) +} + +beforeEach(() => { + vi.resetAllMocks() + revokeAllDocPreviewGrants() +}) + +describe('outside-workspace HTML preview', () => { + it.each(['/tmp/reports', 'C:\\reports'])( + 'reads the full document on its owning host: %s', + async (root) => { + const filePath = root.startsWith('C:') ? `${root}\\report.html` : `${root}/report.html` + host({}, { ok: true, result: { content: '

remote

', isBinary: false } }) + + await expect(readDocPreviewFile(grant(root), 'report.html')).resolves.toEqual({ + ok: true, + bytes: Buffer.from('

remote

'), + contentType: 'text/html; charset=utf-8' + }) + expect(mocks.call).toHaveBeenCalledWith( + '/user-data', + 'vps', + 'files.resolveTerminalPath', + { worktree: 'id:source-workspace', pathText: filePath }, + 15_000, + 12 + ) + expect(mocks.call).toHaveBeenLastCalledWith( + '/user-data', + 'vps', + 'files.readTerminalArtifactPreview', + { worktree: 'id:source-workspace', grantId: 'host-grant', absolutePath: filePath }, + 15_000, + 12 + ) + } + ) + + it('does not resolve or read neighboring assets until their directory is approved', async () => { + const page = grant() + await expect(readDocPreviewFile(page, 'secret.json')).resolves.toMatchObject({ + ok: false, + status: 403, + reason: 'authorization-required' + }) + expect(mocks.call).not.toHaveBeenCalled() + + authorizeDocPreviewDirectory(page.id, 'assets/logo.png') + host( + {}, + { + ok: true, + result: { + content: Buffer.from([137, 80, 78, 71]).toString('base64'), + isBinary: true, + mimeType: 'image/png' + } + } + ) + await expect(readDocPreviewFile(page, 'assets/logo.png')).resolves.toMatchObject({ + ok: true, + bytes: Buffer.from([137, 80, 78, 71]), + contentType: 'image/png' + }) + }) + + // A macOS host spells /tmp as /private/tmp and returns a case-insensitive volume's stored name. + it('reads paths the host spells differently once canonicalized', async () => { + const page = grant() + authorizeDocPreviewDirectory(page.id, 'assets/styles.css') + host( + { + '/tmp/reports': { canonical: '/private/tmp/reports' }, + '/tmp/reports/report.html': { canonical: '/private/tmp/reports/report.html' }, + '/tmp/reports/assets': { canonical: '/private/tmp/reports/assets' }, + '/tmp/reports/assets/styles.css': { canonical: '/private/tmp/reports/assets/Styles.css' } + }, + { ok: true, result: { content: 'h1{}', isBinary: false } } + ) + + await expect(readDocPreviewFile(page, 'report.html')).resolves.toMatchObject({ ok: true }) + await expect(readDocPreviewFile(page, 'assets/styles.css')).resolves.toMatchObject({ + ok: true + }) + }) + + it('refuses symlink redirection outside an approved asset directory', async () => { + const page = grant() + authorizeDocPreviewDirectory(page.id, 'assets/data.json') + host({ '/tmp/reports/assets/data.json': { canonical: '/home/dev/.config/credentials.json' } }) + + await expect(readDocPreviewFile(page, 'assets/data.json')).resolves.toMatchObject({ + ok: false, + message: 'The preview file path changed on its host.' + }) + expect(methodsCalled()).not.toContain('files.readTerminalArtifactPreview') + }) + + it('pages a large approved asset inside the source workspace like a workspace preview', async () => { + const page = grant('/srv') + authorizeDocPreviewDirectory(page.id, 'repo/assets/app.js') + const workspaceParams = { + worktree: 'id:source-workspace', + relativePath: 'assets/app.js', + entryRelativePath: 'assets', + implicitRootRelativePath: null, + authorizedRootRelativePaths: ['assets'] + } + host({ + '/srv/repo/assets/app.js': { + openTarget: { + kind: 'worktree-file', + absolutePath: '/srv/repo/assets/app.js', + relativePath: 'assets/app.js' + } + } + }) + const bundle = Buffer.from('console.log(1)') + const resolveOnly = mocks.call.getMockImplementation() + mocks.call.mockImplementation(async (...args: [string, string, string, unknown]) => { + if (args[2] === 'files.readDocPreview') { + return { ok: false, error: { message: 'file_too_large' } } + } + if (args[2] === 'files.readDocPreviewChunk') { + return { + ok: true, + result: { + contentBase64: bundle.toString('base64'), + size: bundle.length, + mtimeMs: 1, + ctimeMs: 1 + } + } + } + return resolveOnly?.(...args) + }) + + await expect(readDocPreviewFile(page, 'repo/assets/app.js')).resolves.toMatchObject({ + ok: true, + bytes: bundle + }) + expect(mocks.call).toHaveBeenCalledWith( + '/user-data', + 'vps', + 'files.readDocPreview', + workspaceParams, + 15_000 + ) + }) + + // The host canonicalizes these roots, so a nested symlink cannot leave the approved folder. + it.each([ + ['repo/assets/app.js', 'assets', ['assets']], + ['app.js', 'assets/app.js', ['']] + ])( + 'asks the host to check approved folders, not the asset folder (approved %s)', + async (approvedAsset, entryRelativePath, authorizedRootRelativePaths) => { + const page = grant('/srv') + authorizeDocPreviewDirectory(page.id, approvedAsset) + host( + { + '/srv/repo/assets/app.js': { + openTarget: { + kind: 'worktree-file', + absolutePath: '/srv/repo/assets/app.js', + relativePath: 'assets/app.js' + } + } + }, + { ok: true, result: { content: 'console.log(1)', isBinary: false } } + ) + + await readDocPreviewFile(page, 'repo/assets/app.js') + expect(mocks.call).toHaveBeenLastCalledWith( + '/user-data', + 'vps', + 'files.readDocPreview', + { + worktree: 'id:source-workspace', + relativePath: 'assets/app.js', + entryRelativePath, + implicitRootRelativePath: null, + authorizedRootRelativePaths + }, + 15_000 + ) + } + ) + + it('rejects traversal before contacting the server', async () => { + await expect(readDocPreviewFile(grant(), '../private.html')).resolves.toMatchObject({ + ok: false, + status: 404 + }) + expect(mocks.call).not.toHaveBeenCalled() + }) + + it('shows an update requirement for a host without absolute-file grants', async () => { + mocks.call.mockResolvedValueOnce({ ok: true, result: { exists: false } }) + await expect(readDocPreviewFile(grant(), 'report.html')).resolves.toMatchObject({ + ok: false, + message: 'Update Orca on the paired machine to preview files outside its workspaces.' + }) + expect(mocks.call).toHaveBeenCalledOnce() + }) + + it('keeps expired-grant failures on the remote host', async () => { + host({}, { ok: false, error: { message: 'terminal_file_grant_expired' } }) + await expect(readDocPreviewFile(grant(), 'report.html')).resolves.toMatchObject({ + ok: false, + message: 'terminal_file_grant_expired' + }) + }) +}) diff --git a/src/main/browser/doc-preview-terminal-file-reader.ts b/src/main/browser/doc-preview-terminal-file-reader.ts new file mode 100644 index 00000000000..c405b7a8c1c --- /dev/null +++ b/src/main/browser/doc-preview-terminal-file-reader.ts @@ -0,0 +1,141 @@ +import type { RuntimeFilePreviewResult } from '../../shared/runtime-file-contracts' +import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' +import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' +import { + resolveCanonicalDocPreviewPath, + resolveDocPreviewAuthorityPaths, + toRuntimeWorktreeRelativeDirectoryPath, + toRuntimeWorktreeRelativePath, + type DocPreviewGrant +} from './doc-preview-grant-registry' +import type { RuntimeDocPreviewReadParams } from './doc-preview-file-reader' +import { resolveEnvironment } from '../../shared/runtime-environment-store' + +const TIMEOUT_MS = 15_000 +const UPDATE_REQUIRED_MESSAGE = + 'Update Orca on the paired machine to preview files outside its workspaces.' + +function isFilePreview(value: unknown): value is RuntimeFilePreviewResult { + return ( + typeof value === 'object' && + value !== null && + 'content' in value && + typeof value.content === 'string' && + 'isBinary' in value && + typeof value.isBinary === 'boolean' && + (!('mimeType' in value) || typeof value.mimeType === 'string') + ) +} + +export type DocPreviewTerminalRead = + | { preview: RuntimeFilePreviewResult } + | { workspaceParams: RuntimeDocPreviewReadParams } + +/** Called only after the page grant has authorized this path. The host still checks its file grant. */ +export async function readDocPreviewTerminalFile( + grant: DocPreviewGrant, + absolutePath: string +): Promise { + const owner = grant.owner + if (owner.kind !== 'runtime') { + throw new Error('Not found') + } + const root = getRuntimeEnvironmentRegistryRoot() + const environment = resolveEnvironment(root, owner.environmentId) + const revision = environment.pairingRevision ?? environment.createdAt + const call = async (method: string, params: unknown): Promise => { + const response = await callRuntimeEnvironment( + root, + owner.environmentId, + method, + params, + TIMEOUT_MS, + revision + ) + if (!response.ok) { + throw new Error(response.error.message) + } + return response.result + } + const resolve = (pathText: string): Promise => + call('files.resolveTerminalPath', { worktree: owner.worktreeSelector, pathText }) + + const resolution = await resolve(absolutePath) + const target = + typeof resolution === 'object' && resolution !== null && 'openTarget' in resolution + ? resolution.openTarget + : null + if ( + typeof target !== 'object' || + target === null || + !('kind' in target) || + !('absolutePath' in target) || + typeof target.absolutePath !== 'string' + ) { + throw new Error(UPDATE_REQUIRED_MESSAGE) + } + const targetPath = target.absolutePath + // Why: compare host-canonical paths, so /tmp vs /private/tmp or a case-folded name still match but a symlink out of the approved directories does not. + const canonicalPath = await resolveCanonicalDocPreviewPath(grant, absolutePath, async (path) => { + if (path === absolutePath) { + return targetPath + } + const resolved = await resolve(path) + if ( + typeof resolved !== 'object' || + resolved === null || + !('absolutePath' in resolved) || + typeof resolved.absolutePath !== 'string' + ) { + throw new Error(UPDATE_REQUIRED_MESSAGE) + } + return resolved.absolutePath + }) + if (canonicalPath !== targetPath) { + throw new Error('The preview file path changed on its host.') + } + if ( + target.kind === 'absolute-file' && + 'grantId' in target && + typeof target.grantId === 'string' + ) { + const preview = await call('files.readTerminalArtifactPreview', { + worktree: owner.worktreeSelector, + grantId: target.grantId, + absolutePath: targetPath + }) + if (!isFilePreview(preview)) { + throw new Error('The paired machine returned an unreadable file preview.') + } + return { preview } + } + if ( + target.kind === 'worktree-file' && + 'relativePath' in target && + typeof target.relativePath === 'string' + ) { + // Why: the host must check the user-approved folders, not the target's own folder, so a nested symlink cannot step outside them. + const approvedRoots = resolveDocPreviewAuthorityPaths(grant) + .authorizedRootPaths.filter((root) => toRuntimeWorktreeRelativePath(root, absolutePath)) + .map((root) => + toRuntimeWorktreeRelativePath(root, owner.worktreeRoot) + ? '' + : toRuntimeWorktreeRelativeDirectoryPath(owner.worktreeRoot, root) + ) + .filter((root): root is string => root !== null) + if (approvedRoots.length === 0) { + throw new Error('Not found') + } + return { + workspaceParams: { + worktree: owner.worktreeSelector, + relativePath: target.relativePath, + // A folder entry grants nothing itself; with only the workspace approved, its boundary already bounds the target. + entryRelativePath: approvedRoots.find((root) => root !== '') ?? target.relativePath, + implicitRootRelativePath: null, + authorizedRootRelativePaths: approvedRoots + } + } + } + throw new Error(UPDATE_REQUIRED_MESSAGE) +} diff --git a/src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts b/src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts index 83a021b192c..c9e312d5b03 100644 --- a/src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts +++ b/src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts @@ -367,6 +367,33 @@ describe('RuntimeFileCommands', () => { }) }) + it.each([ + ['woff', 'font/woff'], + ['woff2', 'font/woff2'], + ['ttf', 'font/ttf'], + ['otf', 'font/otf'] + ])('reads granted %s font bytes for document previews', async (extension, mimeType) => { + const content = 'font\0binary\0bytes' + const artifactPath = await tempFile(`report.${extension}`, content) + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + const target = absoluteFileTarget(await resolveTerminalArtifactPath(commands, artifactPath)) + + await expect( + commands.readTerminalArtifactPreview( + 'id:wt-1', + target.grantId, + target.absolutePath, + 'client-a' + ) + ).resolves.toMatchObject({ + content: Buffer.from(content).toString('base64'), + isBinary: true, + isImage: false, + mimeType + }) + }) + it('rejects binary-extension terminal artifacts from the editable text path', async () => { const artifactPath = await tempFile('report.pdf', '%PDF text-looking bytes') const { commands } = createRuntimeFileCommands({ path: '/repo' }) diff --git a/src/main/runtime/terminal/artifacts/local-artifact-read.ts b/src/main/runtime/terminal/artifacts/local-artifact-read.ts index ca7c24a947f..77fdc5ea148 100644 --- a/src/main/runtime/terminal/artifacts/local-artifact-read.ts +++ b/src/main/runtime/terminal/artifacts/local-artifact-read.ts @@ -15,6 +15,7 @@ import { } from './artifact-integrity' import { isBinaryBuffer } from '../../../../shared/binary-buffer' import type { RuntimeFilePreviewResult } from '../../../../shared/runtime-types' +import { FONT_FILE_MIME_TYPES } from '../../../../shared/font-file-extensions' const OPEN_NOFOLLOW = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0 @@ -48,7 +49,9 @@ export async function readLocalTerminalArtifactPreviewFromHandle( throw new Error('Cannot preview a directory') } assertTerminalFileGrantFresh(grant, fileStats) - const mimeType = RUNTIME_PREVIEWABLE_BINARY_MIME_TYPES[extname(grant.absolutePath).toLowerCase()] + const extension = extname(grant.absolutePath).toLowerCase() + const fontMimeType = FONT_FILE_MIME_TYPES[extension] + const mimeType = fontMimeType ?? RUNTIME_PREVIEWABLE_BINARY_MIME_TYPES[extension] if (mimeType) { const binaryMaxBytes = maxContentBytes === undefined @@ -65,7 +68,7 @@ export async function readLocalTerminalArtifactPreviewFromHandle( return { content: buffer.toString('base64'), isBinary: true, - isImage: true, + isImage: !fontMimeType, mimeType } } diff --git a/src/preload/api/doc-preview-api.ts b/src/preload/api/doc-preview-api.ts index 6846063e800..5efd0bcf9bb 100644 --- a/src/preload/api/doc-preview-api.ts +++ b/src/preload/api/doc-preview-api.ts @@ -7,6 +7,7 @@ export type DocPreviewGrantOwner = environmentId: string worktreeSelector: string worktreeRoot: string + fileAccess?: 'terminal-artifact' } export type DocPreviewGrantRequest = { diff --git a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx b/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx index 42d9e8c7fc9..1fa9a722376 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx +++ b/src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.tsx @@ -356,7 +356,7 @@ export function HtmlDocPreview({ diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.test.ts b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.test.ts new file mode 100644 index 00000000000..6a72f2da023 --- /dev/null +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type { DocPreviewGrantLocation } from '@/lib/doc-preview-grants' +import type { TerminalArtifactGrantTarget } from '@/runtime/runtime-terminal-artifact-grant' +import { readDocPreviewArtifactRequest } from './doc-preview-artifact-share' + +const mocks = vi.hoisted(() => ({ acquire: vi.fn(), call: vi.fn() })) +vi.mock('@/runtime/runtime-terminal-artifact-grant', () => ({ + acquireTerminalArtifactGrant: mocks.acquire, + pinTerminalArtifactGrantTarget: (target: TerminalArtifactGrantTarget) => ({ + ...target, + expectedEnvironmentPairingRevision: 12 + }) +})) +vi.mock('@/runtime/runtime-rpc-client', () => ({ callRuntimeRpc: mocks.call })) + +beforeEach(() => { + vi.resetAllMocks() + mocks.call.mockResolvedValue({ content: '

report

', isBinary: false }) +}) + +function location(): DocPreviewGrantLocation { + return { + owner: { + kind: 'runtime', + environmentId: 'vps', + worktreeSelector: 'id:source', + worktreeRoot: '/repo', + fileAccess: 'terminal-artifact' + }, + root: '/tmp/reports', + requestBase: '/tmp/reports', + entryRelativePath: 'report.html' + } +} + +it.each([ + ['/tmp/reports/report.html', '/tmp/reports/report.html'], + ['C:/reports/report.html', 'C:\\Reports\\report.html'] +])( + 'prepares %s from the canonical host grant and pins its pairing', + async (requested, canonical) => { + mocks.acquire.mockResolvedValue({ + grantId: 'host-grant', + absolutePath: canonical, + readOnly: false + }) + await expect( + readDocPreviewArtifactRequest(location(), requested, 'source-key') + ).resolves.toMatchObject({ + content: '

report

', + contentType: 'text/html', + sourceKey: 'source-key' + }) + expect(mocks.call).toHaveBeenCalledWith( + { kind: 'environment', environmentId: 'vps' }, + 'files.readTerminalArtifactPreview', + { worktree: 'id:source', grantId: 'host-grant', absolutePath: canonical }, + { timeoutMs: 15_000, expectedEnvironmentPairingRevision: 12 } + ) + } +) + +it('refuses a redirected source rather than sharing a different host file', async () => { + mocks.acquire.mockResolvedValue({ + grantId: 'host-grant', + absolutePath: '/private/secret.html', + readOnly: false + }) + await expect( + readDocPreviewArtifactRequest(location(), '/tmp/reports/report.html', 'source-key') + ).rejects.toThrow() + expect(mocks.call).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx index 2969fc9b4dc..ba0aa2df754 100644 --- a/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx +++ b/src/renderer/src/components/browser-pane/workspace-doc/doc-preview-artifact-share.tsx @@ -13,8 +13,17 @@ import { fileArtifactSourceKey, type FileArtifactOwner } from '@/lib/file-artifa import { basename } from '@/lib/path' import { readRuntimeFilePreview } from '@/runtime/runtime-file-read-client' import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' -import { relativePathInsideRoot } from '../../../../../shared/cross-platform-path' +import { + isWindowsAbsolutePathLike, + normalizeRuntimePathForComparison, + relativePathInsideRoot +} from '../../../../../shared/cross-platform-path' import type { RuntimeFilePreviewResult } from '../../../../../shared/runtime-types' +import { + acquireTerminalArtifactGrant, + pinTerminalArtifactGrantTarget, + type TerminalArtifactGrantTarget +} from '@/runtime/runtime-terminal-artifact-grant' /** The host a grant reads from, spelled as the editor's route for that host. */ export function docPreviewGrantFileOwner(owner: DocPreviewGrantOwner): FileArtifactOwner { @@ -29,7 +38,7 @@ export function docPreviewGrantFileOwner(owner: DocPreviewGrantOwner): FileArtif } } -function readDocPreviewGrantFile( +async function readDocPreviewGrantFile( owner: DocPreviewGrantOwner, filePath: string ): Promise { @@ -38,6 +47,37 @@ function readDocPreviewGrantFile( const context = { target: { kind: 'local' as const }, worktreeId: null, worktreePath: null } return readRuntimeFilePreview({ ...context, connectionId: owner.connectionId }, filePath) } + if (owner.fileAccess === 'terminal-artifact') { + const target = { kind: 'environment' as const, environmentId: owner.environmentId } + const context: TerminalArtifactGrantTarget = pinTerminalArtifactGrantTarget({ + target, + worktreeId: owner.worktreeSelector, + absolutePath: filePath + }) + const grant = await acquireTerminalArtifactGrant(context) + const samePath = + grant && + (isWindowsAbsolutePathLike(filePath) + ? normalizeRuntimePathForComparison(grant.absolutePath) === + normalizeRuntimePathForComparison(filePath) + : grant.absolutePath === filePath) + if (!grant || !samePath) { + throw new Error('outside_grant_root') + } + return callRuntimeRpc( + target, + 'files.readTerminalArtifactPreview', + { + worktree: owner.worktreeSelector, + grantId: grant.grantId, + absolutePath: grant.absolutePath + }, + { + timeoutMs: 15_000, + expectedEnvironmentPairingRevision: context.expectedEnvironmentPairingRevision + } + ) + } // The grant's own selector and root, which may be a chat's scratch folder rather than a workspace. const relativePath = relativePathInsideRoot(owner.worktreeRoot, filePath) if (!relativePath) { diff --git a/src/renderer/src/components/terminal-pane/terminal-file-open-routing.ts b/src/renderer/src/components/terminal-pane/terminal-file-open-routing.ts index 31056fadf74..b5c783672a4 100644 --- a/src/renderer/src/components/terminal-pane/terminal-file-open-routing.ts +++ b/src/renderer/src/components/terminal-pane/terminal-file-open-routing.ts @@ -236,7 +236,8 @@ export function openDetectedFilePath( } // Route local HTML to Orca browser, including system-browser opens OS could not launch. - if (isHtmlFilePath(mappedFilePath) && hostGrant === null) { + // Why: a read-only grant comes from a host that re-grants only to the printing terminal, so preview reads would fail. + if (isHtmlFilePath(mappedFilePath) && !hostGrant?.readOnly) { if (deps.openInSourceGroup) { refuseExplicitNonEditorRoute() return diff --git a/src/renderer/src/components/terminal-pane/terminal-link-host-workspace-file.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-host-workspace-file.test.ts index c098cee15cd..13dd0ee0650 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-host-workspace-file.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-host-workspace-file.test.ts @@ -49,6 +49,80 @@ function hostAnswers(result: unknown): void { } describe('a paired-server link outside its own workspace', () => { + it('opens granted HTML outside every registered workspace as a preview', async () => { + hostAnswers({ + worktree: 'wt-feat', + relativePath: null, + absolutePath: '/tmp/report.html', + exists: true, + isDirectory: false, + openTarget: { + kind: 'absolute-file', + provider: 'local', + absolutePath: '/tmp/report.html', + grantId: 'file-grant' + } + }) + const plan = { status: 'doc-preview' } as const + const previewPlan = vi + .spyOn(filePreview, 'getWorkspaceFilePreviewPlan') + .mockReturnValueOnce(plan) + const openPreview = vi.spyOn(filePreview, 'openFileInBrowserTab').mockReturnValueOnce(plan) + try { + openDetectedFilePath('/tmp/report.html', null, null, featureWorktree) + await flushDoubleRaf() + + expect(openPreview).toHaveBeenCalledWith({ + filePath: '/tmp/report.html', + worktreeId: 'wt-feat' + }) + expect(openFileMock).not.toHaveBeenCalled() + expect(openFilePathMock).not.toHaveBeenCalled() + expect(downloadAndOpenRemoteTerminalFile).not.toHaveBeenCalled() + } finally { + previewPlan.mockRestore() + openPreview.mockRestore() + } + }) + + it('keeps HTML from a host that cannot re-grant it in the editor', async () => { + hostAnswers({ + worktree: 'wt-feat', + relativePath: null, + absolutePath: '/tmp/report.html', + exists: true, + isDirectory: false, + openTarget: { + kind: 'absolute-file', + provider: 'local', + absolutePath: '/tmp/report.html', + grantId: 'file-grant', + readOnly: true + } + }) + const previewPlan = vi + .spyOn(filePreview, 'getWorkspaceFilePreviewPlan') + .mockReturnValue({ status: 'doc-preview' }) + const openPreview = vi.spyOn(filePreview, 'openFileInBrowserTab') + try { + openDetectedFilePath('/tmp/report.html', null, null, featureWorktree) + await flushDoubleRaf() + + expect(openPreview).not.toHaveBeenCalled() + expect(openFileMock).toHaveBeenCalledWith( + expect.objectContaining({ + filePath: '/tmp/report.html', + terminalArtifactGrantId: 'file-grant', + readOnly: true + }), + expect.anything() + ) + } finally { + previewPlan.mockRestore() + openPreview.mockRestore() + } + }) + it('retains the host-resolved HTML owner when opening in another workspace', async () => { storeState.unifiedTabsByWorktree = { 'wt-feat': [ diff --git a/src/renderer/src/components/terminal-pane/terminal-link-remote-runtime-ssh-open.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-remote-runtime-ssh-open.test.ts index ba871fd8c05..3e0c835ad06 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-remote-runtime-ssh-open.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-remote-runtime-ssh-open.test.ts @@ -264,7 +264,7 @@ describe('handleOscLink', () => { vi.mocked(getWorkspaceFilePreviewPlan).mockReturnValueOnce({ status: 'unsupported', message: 'nope', - reason: 'outside-worktree' + reason: 'no-channel' }) openDetectedFilePath('/home/me/repo/report.html', null, null, { diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 13eafb184a8..1a26b6cf6d8 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -1772,7 +1772,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Dateien außerhalb des Arbeitsbereichs können auf einem gekoppelten Server noch nicht in der Vorschau angezeigt werden.", "webClientUnavailable": "Dokumentvorschauen sind im Web-Client nicht verfügbar." } }, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b2811c49ac7..38676c157c3 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -1862,7 +1862,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Files outside the workspace can't be previewed on a paired server yet.", "webClientUnavailable": "Document previews aren't available in the web client." } }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 1f6ad220bd0..edadfbacc8e 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -1345,7 +1345,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Los archivos fuera del espacio de trabajo aún no se pueden previsualizar en un servidor emparejado.", "webClientUnavailable": "Las vistas previas de documentos no están disponibles en el cliente web." } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index e850207425a..560d046861f 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -1548,7 +1548,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Les fichiers en dehors de l'espace de travail ne peuvent pas encore être prévisualisés sur un serveur couplé.", "webClientUnavailable": "Les aperçus de documents ne sont pas disponibles dans le client web." } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 3461e4f0aa2..49650c15476 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -1320,7 +1320,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "ワークスペース外のファイルは、ペアリングされたサーバーではまだプレビューできません。", "webClientUnavailable": "Web クライアントではドキュメントのプレビューを利用できません。" } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index cf6df744352..2a28d36eaa2 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -1320,7 +1320,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "워크스페이스 외부의 파일은 아직 페어링된 서버에서 미리 볼 수 없습니다.", "webClientUnavailable": "문서 미리보기는 웹 클라이언트에서 사용할 수 없습니다." } }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index c778e0f4a09..e0fb0cacd7c 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -2685,7 +2685,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Arquivos fora do espaço de trabalho ainda não podem ser pré-visualizados em um servidor pareado.", "webClientUnavailable": "Prévias de documentos não estão disponíveis no cliente web." } }, diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 78ace191a83..b860f2b1f56 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -1818,7 +1818,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Просмотр файлов за пределами рабочего пространства пока недоступен на сопряжённом сервере.", "webClientUnavailable": "Просмотр документов недоступен в веб-клиенте." } }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index db93306af09..d4ebafa783b 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -1750,7 +1750,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "Çalışma alanı dışındaki dosyalar eşlenen bir sunucuda henüz önizlenemiyor.", "webClientUnavailable": "Belge önizlemeleri web istemcisinde kullanılamıyor." } }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 4d7e6d4b61f..e95bdee8f94 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -1722,7 +1722,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "工作區以外的檔案尚無法在配對伺服器上預覽。", "webClientUnavailable": "文件預覽在 Web 用戶端中不可用。" } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 58d7afff648..f84bd06e550 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -1320,7 +1320,6 @@ }, "file": { "preview": { - "pairedOutsideWorktree": "工作区之外的文件尚无法在配对服务器上预览。", "webClientUnavailable": "文档预览在 Web 客户端中不可用。" } }, diff --git a/src/renderer/src/lib/doc-preview-grants.test.ts b/src/renderer/src/lib/doc-preview-grants.test.ts index 7efa9c6bed8..3f61eb4953c 100644 --- a/src/renderer/src/lib/doc-preview-grants.test.ts +++ b/src/renderer/src/lib/doc-preview-grants.test.ts @@ -15,7 +15,12 @@ vi.mock('@/lib/worktree-runtime-owner', () => ({ runtimeEnvironmentIdOrLocalUnlessTwin: () => (mocks.ambiguous ? null : mocks.environmentId) })) -import { ensureDocPreviewGrant, releaseDocPreviewGrant } from './doc-preview-grants' +import { + buildDocPreviewGrantRequest, + ensureDocPreviewGrant, + releaseDocPreviewGrant +} from './doc-preview-grants' +import { createTestStore, makeWorktree } from '@/store/slices/store-test-helpers' beforeEach(() => { vi.clearAllMocks() @@ -140,3 +145,30 @@ describe('doc preview grant lifetime', () => { }) }) }) + +describe('outside-workspace document grants', () => { + it.each([ + ['/srv/repo', '/tmp/reports/proposal.html', '/tmp/reports'], + ['C:/repo', 'C:/reports/proposal.html', 'C:/reports'] + ])( + 'keeps %s as the source workspace while granting only the opened document', + (workspaceRoot, filePath, root) => { + mocks.environmentId = 'env-1' + const state = createTestStore().getState() + state.getKnownWorktreeById = () => + makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: workspaceRoot }) + expect(buildDocPreviewGrantRequest(state, 'wt-1', filePath)).toEqual({ + owner: { + kind: 'runtime', + environmentId: 'env-1', + worktreeSelector: 'id:wt-1', + worktreeRoot: workspaceRoot, + fileAccess: 'terminal-artifact' + }, + requestBase: root, + root, + entryRelativePath: 'proposal.html' + }) + } + ) +}) diff --git a/src/renderer/src/lib/doc-preview-grants.ts b/src/renderer/src/lib/doc-preview-grants.ts index 31e88dffc84..c29d2cff2c4 100644 --- a/src/renderer/src/lib/doc-preview-grants.ts +++ b/src/renderer/src/lib/doc-preview-grants.ts @@ -48,9 +48,26 @@ export function buildDocPreviewGrantRequest( relativePath: worktreeRelativePath } : chatScratchFileAddress(filePath) - if (!environmentId || !base) { + if (!environmentId) { return null } + if (!base) { + if (!worktreeRoot) { + return null + } + return { + owner: { + kind: 'runtime', + environmentId, + worktreeSelector: toRuntimeWorktreeSelector(worktreeId), + worktreeRoot, + fileAccess: 'terminal-artifact' + }, + requestBase: root, + root, + entryRelativePath: basename(filePath) + } + } return { owner: { kind: 'runtime', diff --git a/src/renderer/src/lib/file-preview.test.ts b/src/renderer/src/lib/file-preview.test.ts index cd33dc981ea..cbaf5d39520 100644 --- a/src/renderer/src/lib/file-preview.test.ts +++ b/src/renderer/src/lib/file-preview.test.ts @@ -352,10 +352,9 @@ describe('openFileInBrowserTab', () => { expect(mocks.createBrowserTab).not.toHaveBeenCalled() }) - // Reject outside-worktree paired paths with a boundary message instead of a worktree-scoped files.read 404. - it('names the worktree boundary for a paired document outside the workspace', () => { + it('previews a paired document outside the workspace without a server browser', () => { mocks.environmentId = 'runtime-1' - mocks.browserAvailability = { state: 'enabled', provider: 'paired-runtime' } + mocks.browserAvailability = { state: 'hidden', reason: 'streaming unavailable' } openFilePreviewToSide({ language: 'html', @@ -364,11 +363,13 @@ describe('openFileInBrowserTab', () => { sourceGroupId: 'group-1' }) - expect(mocks.toastError).toHaveBeenCalledWith( - "Files outside the workspace can't be previewed on a paired server yet." + expect(mocks.createBrowserTab).toHaveBeenCalledWith( + ...docPreviewCall('/tmp/agent-scratch/report.html', { + split: { sourceGroupId: 'group-1', splitDirection: 'right', activate: false } + }) ) expect(mocks.createEmptySplitGroup).not.toHaveBeenCalled() - expect(mocks.createBrowserTab).not.toHaveBeenCalled() + expect(mocks.toastError).not.toHaveBeenCalled() }) it('keeps previewing an SSH document outside the worktree root', () => { diff --git a/src/renderer/src/lib/file-preview.ts b/src/renderer/src/lib/file-preview.ts index c3fa5a1705e..0aa673cebe3 100644 --- a/src/renderer/src/lib/file-preview.ts +++ b/src/renderer/src/lib/file-preview.ts @@ -6,7 +6,7 @@ import { getWorkspaceClientCreationActionPolicy } from '@/lib/client-creation-ac import { webClientDocPreviewRefusal } from '@/lib/doc-preview-web-client' import { useCallback } from 'react' import { useShallow } from 'zustand/react/shallow' -import { basename, getRelativePathInsideRoot } from '@/lib/path' +import { basename } from '@/lib/path' import { getConnectionIdForFileFromState } from '@/lib/connection-owner-resolution' import { activateBrowserWorkspaceTab } from '@/lib/browser-workspace-tab-activation' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/worktree-runtime-owner' @@ -15,13 +15,11 @@ import { REMOTE_FILE_BROWSER_UNSUPPORTED_MESSAGE, TWIN_FILE_BROWSER_UNSUPPORTED_MESSAGE } from '@/lib/workspace-file-browser-open-target' -import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' import { findSiblingGroupId } from '@/store/slices/tabs' import type { CreateBrowserTabOptions } from '@/store/slices/browser/browser-slice-contract' import { ORCA_BROWSER_BLANK_URL } from '../../../shared/constants' -import { chatScratchFileAddress } from '@/runtime/runtime-chat-scratch-file-address' import { selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspace-record-selectors' import { findWorkspaceShowingDoc } from './file-preview-page-conversion' @@ -29,14 +27,6 @@ export { convertBrowserPageToWorkspaceDoc } from './file-preview-page-conversion export type PreviewableLanguage = 'html' -/** Localized lazily: a module constant would freeze the language at import time. */ -function pairedOutsideWorktreeMessage(): string { - return translate( - 'auto.lib.file.preview.pairedOutsideWorktree', - "Files outside the workspace can't be previewed on a paired server yet." - ) -} - function getLocalFilePreviewPlan( state: AppState, worktreeId: string, @@ -57,7 +47,7 @@ function getLocalFilePreviewPlan( export type WorkspaceFilePreviewPlan = | { status: 'browser-tab'; url: string; title: string } | { status: 'doc-preview' } - | { status: 'unsupported'; message: string; reason: 'no-channel' | 'outside-worktree' } + | { status: 'unsupported'; message: string; reason: 'no-channel' } export function getWorkspaceFilePreviewPlan( state: AppState, @@ -90,16 +80,6 @@ export function getWorkspaceFilePreviewPlan( } // Document preview needs no remote browser/screencast capability. if (runtimeEnvironmentIdOrLocalUnlessTwin(state, worktreeId)) { - const worktreeRoot = state.getKnownWorktreeById(worktreeId)?.path ?? null - const outsideWorktree = worktreeRoot && !getRelativePathInsideRoot(filePath, worktreeRoot) - // Paired files.read is bounded to worktrees/chat scratch roots; explain out-of-root paths before they become preview 404s. - if (outsideWorktree && !chatScratchFileAddress(filePath)) { - return { - status: 'unsupported', - message: pairedOutsideWorktreeMessage(), - reason: 'outside-worktree' - } - } return webClientDocPreviewRefusal() ?? { status: 'doc-preview' } } const availability = getWorkspaceClientCreationActionPolicy(state, worktreeId)['managed-browser'] @@ -119,8 +99,7 @@ export function canShowWorkspaceFileBrowserAction( filePath: string ): boolean { const plan = getWorkspaceFilePreviewPlan(state, worktreeId, filePath) - // Keep unsupported paired-path actions visible so activation can explain their workspace boundary. - return plan.status !== 'unsupported' || plan.reason === 'outside-worktree' + return plan.status !== 'unsupported' } export function useWorkspaceFileBrowserActionPredicate( diff --git a/tests/e2e/helpers/paired-html-preview-inventory.ts b/tests/e2e/helpers/paired-html-preview-inventory.ts index bf1ac0ca552..02b85f73015 100644 --- a/tests/e2e/helpers/paired-html-preview-inventory.ts +++ b/tests/e2e/helpers/paired-html-preview-inventory.ts @@ -120,25 +120,34 @@ export function requireSingleDocWorkspace( // Read through the embedder because Playwright cannot directly enter a real webview’s separate partition. export async function readDocPreviewRenderedText( page: Page, - selector: string + selector: string, + entryFileName?: string ): Promise { - return page.evaluate(async (targetSelector) => { - const guest = document.querySelector('webview[src^="orca-preview://"]') as { - executeJavaScript?: (code: string) => Promise - } | null - if (!guest?.executeJavaScript) { - return null - } - try { - const text = await guest.executeJavaScript( - `document.querySelector(${JSON.stringify(targetSelector)})?.textContent ?? null` - ) - return typeof text === 'string' ? text : null - } catch { - // Why: the guest rejects until it is attached and dom-ready; the caller polls. - return null - } - }, selector) + return page.evaluate( + async ({ targetSelector, entryFileName }) => { + const guestSelector = entryFileName + ? `webview[src^="orca-preview://"][src$=${JSON.stringify(`/${encodeURIComponent(entryFileName)}`)}]` + : 'webview[src^="orca-preview://"]' + const guest = document.querySelector(guestSelector) + if ( + !guest || + !('executeJavaScript' in guest) || + typeof guest.executeJavaScript !== 'function' + ) { + return null + } + try { + const text: unknown = await guest.executeJavaScript( + `document.querySelector(${JSON.stringify(targetSelector)})?.textContent ?? null` + ) + return typeof text === 'string' ? text : null + } catch { + // Why: the guest rejects until it is attached and dom-ready; the caller polls. + return null + } + }, + { targetSelector: selector, entryFileName } + ) } // Combine guest rect with webview offset for a real Chromium user-gesture click. diff --git a/tests/e2e/paired-outside-workspace-html-link.spec.ts b/tests/e2e/paired-outside-workspace-html-link.spec.ts new file mode 100644 index 00000000000..9ddb359b918 --- /dev/null +++ b/tests/e2e/paired-outside-workspace-html-link.spec.ts @@ -0,0 +1,165 @@ +import { copyFileSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { expect, test } from './helpers/orca-app' +import { + createRuntimeDesktopPairingOffer, + launchPairedElectronClient +} from './helpers/paired-electron-client' +import { readDocPreviewRenderedText } from './helpers/paired-html-preview-inventory' +import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { waitForActiveTerminalManager } from './helpers/terminal' +import { openTerminalWorkspaceRootLink } from './helpers/terminal-workspace-root-link' + +test.use({ orcaAppExtraEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) + +test('opens an unregistered host HTML path from a terminal and keeps asset access scoped', async ({ + orcaPage, + testRepoPath +}, testInfo) => { + // Boots a paired hub and client, then opens two documents and approves their asset folders. + test.setTimeout(240_000) + const directory = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-outside-html-'))) + const filePath = path.join(directory, 'proposal.html') + const workspaceAssetReport = path.join( + path.dirname(testRepoPath), + `${path.basename(directory)}.html` + ) + writeFileSync( + filePath, + 'Unregistered HTML

Unregistered host document

' + + '

not granted

' + + '' + + '

font waiting

' + ) + copyFileSync( + path.resolve('src/renderer/src/assets/fonts/Geist-Variable.woff2'), + path.join(directory, 'font.woff2') + ) + writeFileSync( + path.join(directory, 'asset.js'), + 'document.querySelector("#asset").textContent = "approved asset loaded"' + ) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + const offer = await createRuntimeDesktopPairingOffer(orcaPage) + const client = await launchPairedElectronClient(offer, testInfo, 'Unregistered HTML host') + try { + await expect + .poll( + () => + client.page.evaluate( + (root) => + window.__store + ?.getState() + .allWorktrees() + .some((item) => item.path === root), + testRepoPath + ), + { timeout: 120_000 } + ) + .toBe(true) + const worktreeId = await client.page.evaluate( + async ({ root, environmentId }) => { + const state = window.__store?.getState() + const workspace = state?.allWorktrees().find((item) => item.path === root) + if (!state || !workspace) { + throw new Error('Missing source workspace') + } + await state.updateSettings({ terminalLinkClickBehavior: 'actions' }) + state.setActiveWorktree(workspace.id, `runtime:${environmentId}`) + return workspace.id + }, + { root: testRepoPath, environmentId: client.environmentId } + ) + await ensureTerminalVisible(client.page) + await waitForActiveTerminalManager(client.page) + const terminalTabId = await client.page.evaluate(() => window.__store?.getState().activeTabId) + if (!terminalTabId) { + throw new Error('Missing source terminal') + } + + await openTerminalWorkspaceRootLink(client.page, testInfo, filePath) + const popup = client.page.locator('[data-link-action-popover]') + await popup.getByRole('button', { name: 'Open file', exact: false }).click() + await expect + .poll(() => readDocPreviewRenderedText(client.page, 'h1')) + .toBe('Unregistered host document') + await expect.poll(() => readDocPreviewRenderedText(client.page, '#asset')).toBe('not granted') + await expect( + client.page.getByRole('status').filter({ hasText: 'This preview wants to read' }) + ).toContainText(directory) + await client.page.getByRole('button', { name: 'Allow folder', exact: true }).click() + await expect + .poll(() => readDocPreviewRenderedText(client.page, '#asset')) + .toBe('approved asset loaded') + await expect.poll(() => readDocPreviewRenderedText(client.page, '#font')).toBe('font loaded') + + const document = await client.page.evaluate( + ({ worktreeId, filePath, directory }) => { + const state = window.__store?.getState() + return { + location: state?.browserTabsByWorktree[worktreeId]?.find( + (tab) => tab.docLocation?.filePath === filePath + )?.docLocation, + registered: state?.allWorktrees().some((item) => item.path === directory) + } + }, + { worktreeId, filePath, directory } + ) + expect(document).toEqual({ + location: { kind: 'workspace-doc', worktreeId, filePath }, + registered: false + }) + await client.page.screenshot({ + path: testInfo.outputPath('unregistered-host-html-preview.png') + }) + + const workspaceAssetName = 'outside-doc-asset.js' + writeFileSync( + path.join(testRepoPath, workspaceAssetName), + 'document.querySelector("#asset").textContent="workspace asset loaded"' + ) + writeFileSync( + workspaceAssetReport, + '

Outside report with workspace assets

not granted

' + + `` + ) + await client.page.evaluate( + ({ worktreeId, filePath }) => { + window.__store?.getState().createBrowserTab(worktreeId, 'data:text/html,', { + docLocation: { kind: 'workspace-doc', worktreeId, filePath }, + browserRuntimeEnvironmentId: null, + activate: true + }) + }, + { worktreeId, filePath: workspaceAssetReport } + ) + await expect + .poll(() => + readDocPreviewRenderedText(client.page, 'h1', path.basename(workspaceAssetReport)) + ) + .toBe('Outside report with workspace assets') + await expect( + client.page.getByRole('status').filter({ hasText: 'This preview wants to read' }) + ).toContainText(path.basename(testRepoPath)) + await client.page.getByRole('button', { name: 'Allow folder', exact: true }).click() + await expect + .poll(() => + readDocPreviewRenderedText(client.page, '#asset', path.basename(workspaceAssetReport)) + ) + .toBe('workspace asset loaded') + + await client.page.locator(`[data-tab-id="${terminalTabId}"]`).click() + await openTerminalWorkspaceRootLink(client.page, testInfo, filePath, 'open') + await expect + .poll(() => readDocPreviewRenderedText(client.page, 'h1', 'proposal.html')) + .toBe('Unregistered host document') + } finally { + await client.dispose() + rmSync(workspaceAssetReport, { force: true }) + rmSync(directory, { recursive: true, force: true }) + } +})