fix(browser): resolve session preview addresses and bound remote header waits

This commit is contained in:
Luke Parker 2026-11-16 14:00:48 +10:00
parent 9e4db6980f
commit baec1df883
7 changed files with 114 additions and 9 deletions

View file

@ -762,7 +762,7 @@ export function createBrowserPane(input: {
if (!url || !(remote ? await remote.stat(action.path, signal) !== null : await workspaceFile(url, roots)))
throw new CodedError(Browser.FailureCode.previewUnavailable, "The workspace file no longer exists or cannot be read by this session.")
signal.throwIfAborted()
const existing = inventory(binding).tabs.find((tab) => tab.url === url)
const existing = inventory(binding).tabs.find((tab) => tab.url.split(/[?#]/, 1)[0] === url)
const tab = existing ? load(binding, existing.id) : create(binding)
if (!tab) throw new Error("Workspace preview tab is unavailable.")
@ -792,7 +792,7 @@ export function createBrowserPane(input: {
const existing = inventory(binding).tabs.find((tab) => {
const live = page(binding, tab.id)
return tab.url === file || (!!live && openingFiles.get(live) === file)
return tab.url.split(/[?#]/, 1)[0] === file || (!!live && openingFiles.get(live) === file)
})
if (existing) {
@ -801,12 +801,14 @@ export function createBrowserPane(input: {
return { value: existing, files: [] }
}
}
const opened = create(binding)
const tabID = opened.state().id
if (file) openingFiles.set(opened, file)
if (action.focus !== false) dispatchBinding(binding, { type: "tab.focused", tabID })
try {
await opened.ready

View file

@ -301,7 +301,7 @@ export function normalizeURL(input: string, policy?: Policy) {
if (reason)
throw new Error(
policy?.fileRoots?.length
policy?.fileRoots?.length || policy?.remote
? "Only HTTP, HTTPS, about:blank, and file URLs inside the workspace are supported."
: "Only HTTP, HTTPS, and about:blank URLs are supported.",
)
@ -323,7 +323,7 @@ export function refusal(input: string, policy?: Policy) {
// A web page is refused only for its credentials.
if (URL.canParse(url) && /^https?:$/.test(new URL(url).protocol)) return "browser.address.credentials"
return policy?.fileRoots?.length ? "browser.address.workspace" : "browser.address.web"
return policy?.fileRoots?.length || policy?.remote ? "browser.address.workspace" : "browser.address.web"
}
// The URL an address opens: a blank page for none, else the address with a scheme, `http` for this machine's names.

View file

@ -1,5 +1,7 @@
import { expect, test } from "bun:test"
import { previewAddress, previewFile, previewResource, reloadAddress } from "./preview"
import { refusal } from "./policy"
import { navigationNotice } from "./refusal-notice"
const roots = ["/work/repo #1"]
@ -7,6 +9,22 @@ const file = "file:///work/repo%20%231/index.html?q=1#anchor"
const view = "oc-preview://first/work/repo%20%231/index.html?q=1#anchor"
test("a remote policy opens only its own session's workspace and explains a refusal as a workspace restriction", () => {
const remote = "workspace://ses_x/"
const address = `${remote}dir/page.html?q=1#h`
const actual = "oc-preview://host/dir/page.html?q=1#h"
expect(previewAddress(address, "host", [], remote)).toBe(actual)
expect(previewFile(actual, "host", [], remote)).toBe(address)
expect(refusal(address, {remote})).toBeUndefined()
expect(refusal(address, {})).toBe("browser.address.web")
for (const other of [file, "workspace://ses_other/dir/page.html"]) {
expect(previewAddress(other, "host", roots, remote)).toBeUndefined()
expect(refusal(other, {remote})).toBe("browser.address.workspace")
expect(navigationNotice(other, {remote}).reason).toBe("browser.address.workspace")
}
})
test("reload chooses the shown preview file for a virtual route, otherwise lets Chromium reload", () => {
expect(reloadAddress(view.replace("index.html", "virtual"), file, "first", roots)).toBe(file)
expect(reloadAddress(view, file, "first", roots)).toBeUndefined()

View file

@ -36,5 +36,5 @@ export function navigationNotice(url: string, policy: Policy, owner: "agent" | "
if (action) return { reason: "external", target: url, action: owner === "agent" ? "copy" : action } as const
return { reason: policy.fileRoots?.length ? "browser.address.workspace" : "browser.address.web" } as const
return { reason: policy.fileRoots?.length || policy.remote ? "browser.address.workspace" : "browser.address.web" } as const
}

View file

@ -0,0 +1,66 @@
import { afterAll, beforeAll, expect, test } from "bun:test"
import { GlobalRegistrator } from "@happy-dom/global-registrator"
import { remotePreview } from "./remote-preview"
import { workspaceFileURL } from "./link"
import { previewAddress } from "./preview"
import { resolvePreviewRequest, type PreviewSource } from "./workspace-file"
// Main uses the host HTTP stack, not the DOM's CORS preflight implementation.
beforeAll(() => GlobalRegistrator.unregister())
afterAll(() => GlobalRegistrator.register())
test("the authenticated read under a server base path names exactly the file validated by stat", async () => {
const checked: string[] = []
const reads: string[] = []
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(req) {
const url = new URL(req.url)
expect(url.searchParams.get("location[directory]")).toBe("/work")
expect(req.headers.get("authorization")).toBe("fixture")
expect(req.headers.get("accept-encoding")).toBe("identity")
expect(url.pathname.startsWith("/sub/api/fs/read/")).toBe(true)
reads.push(decodeURIComponent(url.pathname.slice("/sub/api/fs/read/".length)))
return new Response("x")
},
})
const controller = new AbortController()
const source = remotePreview(
{ id: "test", url: `${server.url}sub`, sameMachine: false, headers: { authorization: "fixture" } },
"ses_x",
{ directory: "/work" },
controller.signal,
async (path) => {
checked.push(path)
return 1
},
)
const grants = new Map<string, PreviewSource>([["grant", source]])
const names = ["dir/50% off.html", "#?.txt", "a%2fb", "%252e%252e/[slug]", "日本語.txt"]
try {
for (const path of names) {
const url = previewAddress(workspaceFileURL("/work", path, "ses_x"), "grant", [], source.prefix)
const file =
url && (await resolvePreviewRequest(`${url}?ignored=yes`, "GET", undefined, grants, controller.signal))
if (!file || file.type !== "remote") throw new Error("expected remote file")
expect(await (await file.read(file.path, undefined, controller.signal)).text()).toBe("x")
}
expect(checked).toEqual(names)
expect(reads).toEqual(names)
} finally {
controller.abort()
await server.stop(true)
}
})

View file

@ -14,7 +14,7 @@ export function remotePreview(
type: "remote",
prefix: workspacePrefix(session),
stat: (path, signal) => stat(path, AbortSignal.any([lifetime, signal, AbortSignal.timeout(15_000)])).catch(() => null),
read(path, range, signal) {
async read(path, range, signal) {
const encoded = path.split("/").map(encodeURIComponent).join("/")
const url = new URL(`api/fs/read/${encoded}`, `${server.url.replace(/\/+$/, "")}/`)
url.searchParams.set("location[directory]", location.directory)
@ -25,9 +25,15 @@ export function remotePreview(
if (range) headers.set("range", range)
// Never send the page's headers or follow a redirect supplied by the server. Node streams the response with
// backpressure and a body inactivity timeout; revoking the attachment also interrupts active readers.
return fetch(url, { headers, redirect: "error", signal: AbortSignal.any([signal, lifetime]) })
// Bound the wait for headers, not the duration of a large response. Detach still aborts its body.
const timeout = new AbortController()
const timer = setTimeout(() => timeout.abort(), 15_000)
try {
return await fetch(url, { headers, redirect: "error", signal: AbortSignal.any([signal, lifetime, timeout.signal]) })
} finally {
clearTimeout(timer)
}
},
}
}

View file

@ -29,6 +29,7 @@ import {
} from "./model-machine"
import { PageIcon } from "./page-icon"
import { artifactLink, artifactWebURL } from "./artifact-link"
import { remotePath, workspacePrefix } from "./remote-address"
import barStyles from "./bar.css?inline"
import commentStyles from "./comment.css?inline"
import tabStyles from "./tabs.css?inline"
@ -83,6 +84,18 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
// The native pane is a desktop feature.
if (ctx.app.platform !== "desktop") return
ctx.add(LinkHandler, {
priority: 6,
match: (link) => link.origin === undefined && link.href.startsWith("workspace://"),
open(link) {
const session = link.session
const pane = model()
if (session?.id && !session.server.builtin && remotePath(link.href, workspacePrefix(session.id)) && pane?.available(session))
return pane.openURL(session, link.href)
ctx.toast.show({ variant: "error", title: ctx.t("refused.workspace") })
},
})
// Tab trigger styles render with the strip, before the pane chunk loads.
ctx.add(Style, tabStyles)
ctx.add(Style, commentStyles)