fix(server): environment-hosted browser tabs behave like a normal browser #16963
Mergedjuliusmarmingemerged 23 commits into
main fromrefs/pull/16963/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge added labelsmacroscope-review
- apps/server/src/preview/ServerBrowser.ts line 886OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -854,3 +872,15 @@854872 NodeCrypto.createHash("sha256").update(tabKey(tab.threadId, tab.tabId)).digest("hex"),855873 );856874875+ /**876+ * Settles the status of a navigation that became a download. A tab opened877+ * straight to the file has no page to show, so it reports the file with its878+ * download; a page that linked to it keeps showing itself.879+ */880+ const settleDownloadNavigation = (881+ tab: ServerTab,882+ url: string,883+ offered: { readonly id: string; readonly fileName: string } | undefined,884+ ) => {885+ // A newer aborted navigation settles the status itself.886+ if (tab.abortedNavigationUrl !== null) return;apps/server/src/preview/PortScanner.ts lines 371 to 374OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -304,0 +354,21 @@354+ /** Maps socket inodes to the processes holding them, by `/proc/<pid>/fd`. */355+ const findSocketOwners = Effect.fn("PortDiscovery.findSocketOwners")(function* (356+ inodes: ReadonlySet<string>,357+ ) {358+ const owners = new Map<string, { pid: number; processName: string | null }>();359+ const pids = (yield* fileSystem360+ .readDirectory("/proc")361+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>362+ /^\d+$/.test(entry),363+ );364+ let budget = PROC_FD_WALK_LIMIT;365+ for (const pidText of pids) {366+ if (owners.size === inodes.size || budget <= 0) break;367+ // Other users' fds are unreadable; their ports still list, without a pid.368+ const fds = yield* fileSystem369+ .readDirectory(`/proc/${pidText}/fd`)370+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));371+ budget -= fds.length;372+ const links = yield* Effect.forEach(373+ fds,374+ (fd) =>
- @@ -304,0 +356,21 @@356+ inodes: ReadonlySet<string>,357+ ) {358+ const owners = new Map<string, { pid: number; processName: string | null }>();359+ const pids = (yield* fileSystem360+ .readDirectory("/proc")361+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter((entry) =>362+ /^\d+$/.test(entry),363+ );364+ let budget = PROC_FD_WALK_LIMIT;365+ for (const pidText of pids) {366+ if (owners.size === inodes.size || budget <= 0) break;367+ // Other users' fds are unreadable; their ports still list, without a pid.368+ const fds = yield* fileSystem369+ .readDirectory(`/proc/${pidText}/fd`)370+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));371+ budget -= fds.length;372+ const links = yield* Effect.forEach(373+ fds,374+ (fd) =>375+ fileSystem.readLink(`/proc/${pidText}/fd/${fd}`).pipe(Effect.orElseSucceed(() => "")),376+ { concurrency: 16 },@@ -304,0 +391,21 @@391+ * Linux listeners from `/proc/net/tcp{,6}`, for hosts without `lsof`. Null392+ * when neither file is readable, so discovery falls back to common ports.393+ */394+ const scanProcListeners = Effect.fn("PortDiscovery.scanProcListeners")(function* (395+ terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner>,396+ ) {397+ if (hostPlatform !== "linux") return null;398+ const tables = yield* Effect.forEach(["/proc/net/tcp", "/proc/net/tcp6"], (path) =>399+ fileSystem.readFileString(path).pipe(Effect.option),400+ );401+ if (tables.every(Option.isNone)) return null;402+ const listeners = tables.flatMap((table) =>403+ Option.isSome(table) ? parseProcNetTcp(table.value) : [],404+ );405+ const known = yield* Ref.get(socketOwnersRef);406+ const inodes = new Set(listeners.map((listener) => listener.inode));407+ // Listeners rarely change, so the fd walk runs only for sockets not seen before.408+ const unseen = new Set([...inodes].filter((inode) => !known.has(inode)));409+ const found = unseen.size === 0 ? new Map() : yield* findSocketOwners(unseen);410+ const owners = new Map([...known].filter(([inode]) => inodes.has(inode)));411+ for (const inode of unseen) owners.set(inode, found.get(inode) ?? null);@@ -525,4 +653,6 @@525653 .pipe(526654 Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),527655 Effect.catchTags({528- ProcessSpawnError: recoverLsofProbeFailure,656+ // A missing lsof stays missing; later scans skip straight to the fallback.657+ ProcessSpawnError: (error) =>658+ Ref.set(lsofMissingRef, true).pipe(Effect.andThen(recoverLsofProbeFailure(error))),apps/server/src/preview/ServerBrowser.ts lines 816 to 843Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -787,7 +800,12 @@787800 errorText,788801 timestamp: new Date().toISOString(),789802 });790- if (!isMainNavigation(request) || errorText.includes("ERR_ABORTED")) return;803+ if (!isMainNavigation(request)) return;804+ // An aborted navigation is usually a download; its `download` event settles the status.805+ if (errorText.includes("ERR_ABORTED")) {806+ tab.abortedNavigationUrl = request.url();807+ return;808+ }791809 tab.loading = false;792810 const { code, description } = ServerBrowserPage.parseNetError(errorText);793811 report(tab, {apps/web/src/hooks/useThreadActions.ts line 560Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -555,3 +556,4 @@555556 threadRef,556557 );557558 clearTerminalUiState(threadRef);559+ clearThreadPreviewState(threadRef);packages/shared/src/preview.ts line 73OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -57,3 +57,17 @@5757 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");5858 }595960+const SEARCH_URL = "https://duckduckgo.com/?q=";61+/** A bare host that is always an address: localhost, an IPv4 literal, or a bracketed IPv6 one. */62+const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;63+64+/**65+ * Turns what a user typed in an address bar into the URL to open: an address66+ * as `normalizePreviewUrl` reads it, or else a web search for the text. Text67+ * is an address when it has a scheme, or no spaces and a host that has a dot,68+ * a port, or is localhost or an IP. Throws only for empty input or an69+ * explicit unsupported scheme.70+ */71+export function resolveAddressBarInput(rawInput: string): string {72+ const trimmed = rawInput.trim();73+ if (trimmed.includes("://") || trimmed.length === 0) return normalizePreviewUrl(trimmed);
- packages/shared/src/preview.ts lines 94 to 95Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -57,3 +57,18 @@5757 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");5858 }595960+const SEARCH_URL = "https://duckduckgo.com/?q=";61+/** A bare host that is always an address: localhost, an IPv4 literal, or a bracketed IPv6 one. */62+const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;63+64+/**65+ * Turns what a user typed in an address bar into the URL to open: an address66+ * as `normalizePreviewUrl` reads it, or else a web search for the text. Text67+ * is an address when it has a scheme, or no spaces and a host that has a dot,68+ * a port, or is localhost or an IP. Throws only for empty input or an69+ * explicit unsupported scheme.70+ */71+export function resolveAddressBarInput(rawInput: string): string {72+ const trimmed = rawInput.trim();73+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) || trimmed.length === 0)74+ return normalizePreviewUrl(trimmed);
- @@ -787,4 +816,7 @@787816 errorText,788817 timestamp: new Date().toISOString(),789818 });790- if (!isMainNavigation(request) || errorText.includes("ERR_ABORTED")) return;819+ if (!isMainNavigation(request)) return;820+ // A navigation a newer one replaced leaves the status to the newer one.821+ const generation = navigationGenerations.get(request);822+ if (generation !== undefined && generation !== tab.navigationGeneration) return;@@ -857,3 +925,21 @@925+ void reportLoaded(tab);926+ return;927+ }928+ report(tab, {929+ _tag: "LoadFailed",930+ url: url.slice(0, 2048),931+ title: "",932+ code: -3,933+ description: "ERR_ABORTED",934+ ...(offered === undefined ? {} : { download: offered }),935+ });936+ };937+857938 const saveDownload = async (tab: ServerTab, download: Download) => {858939 const id = NodeCrypto.randomUUID();859940 const path = NodePath.join(downloadDir(tab), id);941+ const navigation =942+ download.url() === tab.abortedNavigation?.url ? tab.abortedNavigation.generation : null;943+ if (navigation !== null) clearAbortedNavigation(tab);944+ // A tab whose own address was the file shows it in place; see settleAbortedNavigation.945+ const shownInTab = navigation !== null && tab.page.url() === "about:blank";
- packages/shared/src/preview.ts lines 81 to 82OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -59,0 +62,21 @@62+const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;63+const BARE_HOST_PORT_PATTERN = /^[^/?#:@]+:\d+(?:[/?#]|$)/;64+65+/**66+ * Turns what a user typed in an address bar into the URL to open: an address67+ * as `normalizePreviewUrl` reads it, or else a web search for the text. Text68+ * is an address when it has a scheme, or no spaces and a host that has a dot,69+ * a port, or is localhost or an IP. Throws only for empty input or an70+ * explicit unsupported scheme (`ftp://`, `mailto:`, `data:`).71+ */72+export function resolveAddressBarInput(rawInput: string): string {73+ const trimmed = rawInput.trim();74+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) || trimmed.length === 0)75+ return normalizePreviewUrl(trimmed);76+ if (!/\s/.test(trimmed)) {77+ // `mailto:x` or `data:...` is an explicit scheme; `example.com:8080` or78+ // `devbox:8080` is a bare host and port. `normalizePreviewUrl` would read79+ // `mailto:alice@example.com` as credentials on a bare host, so reject here.80+ const protocol = previewUrlProtocol(trimmed);81+ if (protocol !== undefined && !BARE_HOST_PORT_PATTERN.test(trimmed)) {82+ if (protocol !== "http:" && protocol !== "https:") {
juliusmarminge merged this5754121
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed