🙌 OpenHands: AI-Driven Development
feat(apps): add authenticated backend view helper (#17656)
Graham Neubiga3ef3898520d
diff --git a/.pr/16573/catalog-tests.png b/.pr/16573/catalog-tests.pngdeleted file mode 100644index 6433bf2dea..0000000000Binary files a/.pr/16573/catalog-tests.png and /dev/null differdiff --git a/.pr/conversation-panel-split-vitest.png b/.pr/conversation-panel-split-vitest.pngdeleted file mode 100644index ef31e3d158..0000000000Binary files a/.pr/conversation-panel-split-vitest.png and /dev/null differdiff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsxindex dc903f4d6c..4c924bd091 100644--- a/__tests__/components/backends/add-backend-modal.test.tsx+++ b/__tests__/components/backends/add-backend-modal.test.tsx@@ -95,7 +95,7 @@ beforeEach(() => {interval: 5,});deviceFlowMocks.pollForToken.mockReset();- deviceFlowMocks.pollForToken.mockImplementation(() => new Promise(() => { }));+ deviceFlowMocks.pollForToken.mockImplementation(() => new Promise(() => {}));__resetActiveStoreForTests();});diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsxindex caea01e951..c4144fb692 100644--- a/__tests__/components/backends/manage-backends-modal.test.tsx+++ b/__tests__/components/backends/manage-backends-modal.test.tsx@@ -735,9 +735,7 @@ describe("ManageBackendsModal", () => {);await user.click(- await screen.findByTestId(- "manage-backends-reconnect-cloud-login-button",- ),+ await screen.findByTestId("manage-backends-reconnect-cloud-login-button"),);await waitFor(() => {@@ -786,9 +784,7 @@ describe("ManageBackendsModal", () => {);await user.click(- await screen.findByTestId(- "manage-backends-reconnect-cloud-login-button",- ),+ await screen.findByTestId("manage-backends-reconnect-cloud-login-button"),);expect(diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsxindex f323c64a87..104d844255 100644--- a/__tests__/hooks/query/use-backends-health.test.tsx+++ b/__tests__/hooks/query/use-backends-health.test.tsx@@ -200,7 +200,10 @@ describe("useBackendsHealth", () => {apiKey: "",authMode: "cookie",};- getCloudOrganizationsMock.mockResolvedValue({ items: [], currentOrgId: null });+ getCloudOrganizationsMock.mockResolvedValue({+ items: [],+ currentOrgId: null,+ });const { result } = renderHook(() => useBackendsHealth([cookieBackend]), {wrapper,diff --git a/docs/ACP_AGENTS.md b/docs/ACP_AGENTS.mdindex b73475733d..4d5856ee96 100644--- a/docs/ACP_AGENTS.md+++ b/docs/ACP_AGENTS.md@@ -27,7 +27,7 @@ flowchart LR```The Agent Server owns the subprocess and the credentials; Agent Canvas only-records *which* agent to run and surfaces a form for the secrets it needs. The+records _which_ agent to run and surfaces a form for the secrets it needs. Theagent choice is stored per backend, so switching backends can switch agents.## Supported providers@@ -38,11 +38,11 @@ The provider list is sourced from the SDK registry[`src/constants/acp-providers.ts`](../src/constants/acp-providers.ts). Adding orchanging a provider happens upstream in the SDK, not here.-| Provider | Default command |-|---|---|+| Provider | Default command |+| --------------- | ---------------------------------------------- || **Claude Code** | `npx -y @agentclientprotocol/claude-agent-acp` |-| **Codex** | `npx -y @agentclientprotocol/codex-acp` |-| **Gemini CLI** | `npx -y @google/gemini-cli --acp` |+| **Codex** | `npx -y @agentclientprotocol/codex-acp` |+| **Gemini CLI** | `npx -y @google/gemini-cli --acp` |See [Authentication](#authentication) for how each one authenticates.@@ -64,13 +64,13 @@ or self-hosted backend), the provider CLI finds that login automatically — nokey required. On a clean cloud sandbox there's no stored login, so an API key isneeded instead.-| Provider | Subscription login (auto-detected) | API key |-|---|---|---|-| **Claude Code** | A Claude Code login (Pro/Max), from Claude Code's own credential store: the **macOS Keychain**, or `~/.claude/.credentials.json` on Linux | `ANTHROPIC_API_KEY` *(onboarding)* |-| **Codex** | A ChatGPT login (`codex login`) cached at `~/.codex/auth.json` | `OPENAI_API_KEY` *(onboarding)* |-| **Gemini CLI** | Your Google login (`gemini`/`gemini --acp`) cached at `~/.gemini/oauth_creds.json` | `GEMINI_API_KEY` *(onboarding)* |+| Provider | Subscription login (auto-detected) | API key |+| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |+| **Claude Code** | A Claude Code login (Pro/Max), from Claude Code's own credential store: the **macOS Keychain**, or `~/.claude/.credentials.json` on Linux | `ANTHROPIC_API_KEY` _(onboarding)_ |+| **Codex** | A ChatGPT login (`codex login`) cached at `~/.codex/auth.json` | `OPENAI_API_KEY` _(onboarding)_ |+| **Gemini CLI** | Your Google login (`gemini`/`gemini --acp`) cached at `~/.gemini/oauth_creds.json` | `GEMINI_API_KEY` _(onboarding)_ |-All three collect an *optional* API key (+ base URL) in onboarding. As noted+All three collect an _optional_ API key (+ base URL) in onboarding. As notedabove, **a subscription / OAuth login takes priority over an API key** — when theprovider's CLI is signed in, a key set in the environment is not used. Verifiedper provider:@@ -89,7 +89,7 @@ per provider:`ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL`.The one exception is the **base URL** (`*_BASE_URL`): a custom value points the-CLI at a different endpoint (a proxy or gateway) and *does* take effect even+CLI at a different endpoint (a proxy or gateway) and _does_ take effect evenunder a login — for Gemini it rides the ACP `gateway` param. It's an advancedoverride, not needed for normal use.@@ -102,7 +102,7 @@ First-time users get a four-step onboarding modal. To onboard an ACP agent:2. **Check backend** — confirms Agent Canvas can reach the Agent Server.3. **Set up credentials** — enter the provider's credentials. Beyond the APIkey (+ optional base URL), this step also collects the credentials a- *containerized* backend needs, since a fresh container has no host login:+ _containerized_ backend needs, since a fresh container has no host login:- **Codex** — `CODEX_AUTH_JSON` (the contents of `~/.codex/auth.json`).- **Claude Code** — `CLAUDE_CODE_OAUTH_TOKEN` (a Pro/Max OAuth token).- **Gemini CLI** — `GOOGLE_APPLICATION_CREDENTIALS_JSON` (Vertex SA / ADC JSON)@@ -114,6 +114,7 @@ First-time users get a four-step onboarding modal. To onboard an ACP agent:there's no host login to fall back on. When the login probe detects anexisting session, the step shows a "you're already signed in" banner andstays skippable.+4. **Say hello** — creates your first conversation and closes the modal.> [!NOTE]@@ -148,11 +149,11 @@ point Canvas at it). In short:# canvas_ui_control calls use client_tools; the Python mount keeps# pre-migration conversations loadable when persisted metadata imports# canvas_ui_tool.-# Minimum image: 1.47.0-python (Canvas's minimumAgentServer: the session-# socket). Override SHA with a newer build.+# Minimum image: 1.51.0-python (Canvas's minimumAgentServer, including the+# managed Canvas App backend bridge). Override SHA with a newer build.docker run -d --name oh-acp -p 8010:8000 -v acp-data:/workspace \-v "$(pwd)/tools:/canvas-tools:ro" -e OH_EXTRA_PYTHON_PATH=/canvas-tools \- ghcr.io/openhands/agent-server:1.47.0-python+ ghcr.io/openhands/agent-server:1.51.0-python# 2. Canvas pointed at the container.VITE_BACKEND_BASE_URL=http://localhost:8010 npm run dev:frontend@@ -196,7 +197,7 @@ needed.> [!NOTE]> **Pick a non-flash Gemini model.** gemini-cli 0.45.x re-resolves any `*-flash`-> model id at generation time to its *current default* flash (e.g.+> model id at generation time to its _current default_ flash (e.g.> `gemini-2.5-flash` silently ran `gemini-3-flash`, which 404s on projects that> don't serve it — software-agent-sdk#3532). Only a non-flash id sticks, so> Canvas preselects `gemini-2.5-pro`. If a Gemini turn fails with@@ -221,7 +222,7 @@ Open **Settings → Agent** at any time:**Custom** to point at any other ACP server.- **Command** — the command line used to spawn the subprocess. Selecting a presetfills this in; editing it to match another preset re-detects that provider.- API keys are *not* entered here — they live in the Secrets panel.+ API keys are _not_ entered here — they live in the Secrets panel.- **Model** — choose a suggested model for the provider or enter a custom modeloverride. Built-in providers save a concrete model rather than leaving itblank.diff --git a/specs/canvas-extensions.md b/specs/canvas-extensions.mdindex 94eec5306f..b5c0b9a140 100644--- a/specs/canvas-extensions.md+++ b/specs/canvas-extensions.md@@ -127,19 +127,55 @@ temporary Blob URL. A direct `<script src>` or `import(backendUrl)` cannot carry`X-Session-API-Key`, so it is not the v1 loading path. Importing the bundle doesnot activate it; Canvas calls `activate` only for an enabled installation.+### Optional app backend views++Schema 1 routed pages may embed an app-owned HTTP UI through the optional+`host.appBackendView` helper. The helper is present only when all parts of the+Agent Server bridge contract are available:++- `/server_info.capabilities` contains `canvas_app_backend_bridge_v1`;+- `/server_info.app_backend_ingress_url` is a valid HTTP(S) URL; and+- the installed `@openhands/typescript-client` exports+ `CanvasExtensionsClient.createAppBackendSession()` and+ `revokeAppBackendSession()`.++Extensions call `host.appBackendView.mount({ container })`; they never receive+an Agent Server session key, inspect local storage, construct an ingress origin,+or derive one from `window.location`. Canvas requests a short-lived session from+the discovered ingress, validates that the returned URL has the same origin,+and renders it in an iframe using only the server-provided allowlisted sandbox+tokens. `allow-same-origin` is required so authenticated fetch, WebSocket, and+Worker APIs retain the app ingress origin and partitioned session cookie; the+separate ingress origin is the authority boundary. Top-navigation, downloads,+and storage-access tokens remain rejected. The host owns loading, safe errors,+retry, a validated new-tab fallback, session revocation, and disposal on page+unmount or backend switch.++This remains additive to schema 1. Self-contained ESM loading, routed page+registration, and the native editor are unchanged. There is no generic runtime,+VS Code app, arbitrary URL proxy, mandatory sidecar, or frontend tarball loader.++The pinned `@openhands/typescript-client` `1.53.0` ships the bridge API+(first defined in draft `OpenHands/software-agent-sdk#5272`), so the client+export requirement above is satisfied by a released client. The helper is+feature-detected at runtime on the live Agent Server: `server_info.capabilities`+must advertise `canvas_app_backend_bridge_v1` and `app_backend_ingress_url`+must be a valid HTTP(S) URL. Canvas requires Agent Server `1.51.0` or newer,+which is above the first release exposing this bridge contract.+## Agent Server APIThe API deliberately mirrors plugin distribution management while remaining aseparate runtime:-| Method | Path | Purpose |-| -------- | ------------------------------------------------- | --------------------------------------------------------- |-| `GET` | `/api/canvas-extensions/installed` | List installed extensions and parsed manifests |-| `POST` | `/api/canvas-extensions/install` | Install from git or a backend-local path; always disabled |-| `GET` | `/api/canvas-extensions/installed/{name}` | Read one installation |-| `PATCH` | `/api/canvas-extensions/installed/{name}` | Set enabled state |-| `DELETE` | `/api/canvas-extensions/installed/{name}` | Uninstall |-| `GET` | `/api/canvas-extensions/installed/{name}/bundle` | Return the entrypoint as JavaScript text |+| Method | Path | Purpose |+| -------- | ------------------------------------------------ | --------------------------------------------------------- |+| `GET` | `/api/canvas-extensions/installed` | List installed extensions and parsed manifests |+| `POST` | `/api/canvas-extensions/install` | Install from git or a backend-local path; always disabled |+| `GET` | `/api/canvas-extensions/installed/{name}` | Read one installation |+| `PATCH` | `/api/canvas-extensions/installed/{name}` | Set enabled state |+| `DELETE` | `/api/canvas-extensions/installed/{name}` | Uninstall |+| `GET` | `/api/canvas-extensions/installed/{name}/bundle` | Return the entrypoint as JavaScript text |A refresh endpoint (`POST /api/canvas-extensions/installed/{name}/refresh`) isplanned but not part of the current router; the service-layer staged check/applydiff --git a/src/api/canvas-extensions-service.test.ts b/src/api/canvas-extensions-service.test.tsindex 9b61b1d754..69d2d1c67d 100644--- a/src/api/canvas-extensions-service.test.ts+++ b/src/api/canvas-extensions-service.test.ts@@ -1,4 +1,7 @@-import { AgentServerClient } from "@openhands/typescript-client/clients";+import {+ AgentServerClient,+ CanvasExtensionsClient,+} from "@openhands/typescript-client/clients";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import CanvasExtensionsService, {CanvasExtensionsUnsupportedError,@@ -13,6 +16,7 @@ import type { InstalledCanvasExtensionInfo } from "#/types/canvas-extension";vi.mock("@openhands/typescript-client/clients", () => ({AgentServerClient: vi.fn(),+ CanvasExtensionsClient: vi.fn(),}));const get = vi.fn();@@ -20,6 +24,10 @@ const post = vi.fn();const patch = vi.fn();const remove = vi.fn();const request = vi.fn();+const getServerInfo = vi.fn();+const createAppBackendSession = vi.fn();+const revokeAppBackendSession = vi.fn();+const closeAppBackendClient = vi.fn();const localBackend: Backend = {id: "local",@@ -63,10 +71,20 @@ beforeEach(() => {patch,delete: remove,request,+ server: { getServerInfo },close: vi.fn(),} as unknown as AgentServerClient;} as unknown as typeof AgentServerClient,);+ vi.mocked(CanvasExtensionsClient).mockImplementation(+ function MockCanvasExtensionsClient() {+ return {+ createAppBackendSession,+ revokeAppBackendSession,+ close: closeAppBackendClient,+ };+ } as never,+ );});afterEach(() => {@@ -205,4 +223,102 @@ describe("CanvasExtensionsService", () => {).rejects.toThrow("root-relative path");expect(AgentServerClient).not.toHaveBeenCalled();});++ it("returns no app view helper when the captured backend lacks bridge capability", async () => {+ getServerInfo.mockResolvedValue({ capabilities: [] });++ await expect(+ CanvasExtensionsService.createAppBackendViewClient(+ extension.name,+ localBackend,+ ),+ ).resolves.toBeNull();+ expect(createAppBackendSession).not.toHaveBeenCalled();+ });++ it("creates and revokes app sessions through the discovered bridge ingress", async () => {+ getServerInfo.mockResolvedValue({+ capabilities: ["canvas_app_backend_bridge_v1"],+ app_backend_ingress_url: "https://apps.example.test",+ });+ createAppBackendSession.mockResolvedValue({+ ingress_url: "https://apps.example.test/app-backends/demo-extension/",+ expires_at: "2026-09-23T16:00:00Z",+ iframe_sandbox:+ "allow-forms allow-modals allow-popups allow-same-origin allow-scripts",+ });++ const viewClient = await CanvasExtensionsService.createAppBackendViewClient(+ extension.name,+ localBackend,+ );++ expect(viewClient).not.toBeNull();+ await expect(viewClient!.createSession()).resolves.toEqual({+ url: "https://apps.example.test/app-backends/demo-extension/",+ expiresAt: "2026-09-23T16:00:00Z",+ iframeSandbox:+ "allow-forms allow-modals allow-popups allow-same-origin allow-scripts",+ });+ await viewClient!.revokeSession();+ viewClient!.dispose();+ expect(CanvasExtensionsClient).toHaveBeenCalledWith({+ host: localBackend.host,+ apiKey: localBackend.apiKey,+ timeout: 60000,+ workingDir: expect.any(String),+ appBackendIngressUrl: "https://apps.example.test/",+ });+ expect(createAppBackendSession).toHaveBeenCalledWith(+ extension.name,+ undefined,+ );+ expect(revokeAppBackendSession).toHaveBeenCalledWith(extension.name);+ expect(closeAppBackendClient).toHaveBeenCalledTimes(1);+ });++ it("forwards cancellation to the app session request", async () => {+ getServerInfo.mockResolvedValue({+ capabilities: ["canvas_app_backend_bridge_v1"],+ app_backend_ingress_url: "https://apps.example.test",+ });+ createAppBackendSession.mockResolvedValue({+ ingress_url: "https://apps.example.test/app-backends/demo-extension/",+ expires_at: "2026-09-23T16:00:00Z",+ iframe_sandbox: "allow-scripts",+ });+ const viewClient = await CanvasExtensionsService.createAppBackendViewClient(+ extension.name,+ localBackend,+ );+ const controller = new AbortController();++ await viewClient!.createSession(controller.signal);++ expect(createAppBackendSession).toHaveBeenCalledWith(+ extension.name,+ controller.signal,+ );+ });++ it("rejects and revokes a session outside the discovered ingress origin", async () => {+ getServerInfo.mockResolvedValue({+ capabilities: ["canvas_app_backend_bridge_v1"],+ app_backend_ingress_url: "https://apps.example.test",+ });+ createAppBackendSession.mockResolvedValue({+ ingress_url: "https://attacker.example/app-backends/demo-extension/",+ expires_at: "2026-09-23T16:00:00Z",+ iframe_sandbox: "allow-scripts",+ });+ const viewClient = await CanvasExtensionsService.createAppBackendViewClient(+ extension.name,+ localBackend,+ );++ await expect(viewClient!.createSession()).rejects.toThrow(+ "session URL is invalid",+ );+ expect(revokeAppBackendSession).toHaveBeenCalledWith(extension.name);+ });});diff --git a/src/api/canvas-extensions-service.ts b/src/api/canvas-extensions-service.tsindex 3350ef8dc1..9f2d3dc7da 100644--- a/src/api/canvas-extensions-service.ts+++ b/src/api/canvas-extensions-service.ts@@ -1,6 +1,10 @@-import { AgentServerClient } from "@openhands/typescript-client/clients";+import {+ AgentServerClient,+ CanvasExtensionsClient,+} from "@openhands/typescript-client/clients";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";+import type { CanvasExtensionAppViewSession } from "#/extensions/canvas-extension-app-view";import {getActiveBackend,isNoBackend,@@ -13,9 +17,32 @@ import type {} from "#/types/canvas-extension";const CANVAS_EXTENSIONS_BASE_PATH = "/api/canvas-extensions";+const CANVAS_APP_BACKEND_BRIDGE_CAPABILITY = "canvas_app_backend_bridge_v1";const REMOTE_EXTENSION_SOURCE_PATTERN =/^(?:github:|https?:\/\/|git:\/\/|file:\/\/|[\w.-]+@[\w.-]+:)/i;+interface AppBackendServerInfo {+ capabilities?: string[];+ app_backend_ingress_url?: string | null;+}++export interface CanvasExtensionAppBackendViewClient {+ createSession: (+ signal?: AbortSignal,+ ) => Promise<CanvasExtensionAppViewSession>;+ revokeSession: () => Promise<void>;+ dispose: () => void;+}++function parseHttpUrl(value: string): URL | null {+ try {+ const url = new URL(value);+ return url.protocol === "http:" || url.protocol === "https:" ? url : null;+ } catch {+ return null;+ }+}+export type CanvasExtensionsUnsupportedReason =| "no-backend"| "cloud-backend"@@ -89,6 +116,78 @@ async function mapUnsupported<T>(operation: () => Promise<T>): Promise<T> {}}+async function createAppBackendViewClient(+ name: string,+ backend: Backend,+): Promise<CanvasExtensionAppBackendViewClient | null> {+ const clientOptions = getAgentServerClientOptions({+ host: backend.host,+ apiKey: backend.apiKey,+ timeout: 60000,+ });+ const serverClient = new AgentServerClient(clientOptions);+ let info: AppBackendServerInfo;+ try {+ info = (await serverClient.server.getServerInfo()) as AppBackendServerInfo;+ } finally {+ serverClient.close();+ }+ const ingressUrl = info.app_backend_ingress_url+ ? parseHttpUrl(info.app_backend_ingress_url)+ : null;+ if (+ !Array.isArray(info.capabilities) ||+ !info.capabilities.includes(CANVAS_APP_BACKEND_BRIDGE_CAPABILITY) ||+ !ingressUrl+ ) {+ return null;+ }++ const sessionClient = new CanvasExtensionsClient({+ ...clientOptions,+ appBackendIngressUrl: ingressUrl.href,+ });+ let disposed = false;+ let hasSession = false;+ const revokeSession = async () => {+ if (!hasSession) return;+ try {+ await sessionClient.revokeAppBackendSession(name);+ } finally {+ hasSession = false;+ }+ };+ return {+ createSession: async (signal) => {+ if (disposed) throw new Error("Canvas App backend view is disposed");+ const session = await sessionClient.createAppBackendSession(name, signal);+ hasSession = true;+ const sessionUrl = parseHttpUrl(session.ingress_url);+ if (sessionUrl?.origin !== ingressUrl.origin) {+ await revokeSession();+ throw new Error("Canvas App backend session URL is invalid");+ }+ return {+ url: sessionUrl.href,+ expiresAt: session.expires_at,+ iframeSandbox: session.iframe_sandbox,+ };+ },+ revokeSession,+ dispose: () => {+ if (disposed) return;+ disposed = true;+ if (!hasSession) {+ sessionClient.close();+ return;+ }+ void revokeSession()+ .catch(() => undefined)+ .finally(() => sessionClient.close());+ },+ };+}+function installedExtensionPath(name: string): string {return `${CANVAS_EXTENSIONS_BASE_PATH}/installed/${encodeURIComponent(name)}`;}@@ -170,6 +269,14 @@ class CanvasExtensionsService {);}+ static async createAppBackendViewClient(+ name: string,+ backend: Backend,+ ): Promise<CanvasExtensionAppBackendViewClient | null> {+ if (isNoBackend(backend) || backend.kind === "cloud") return null;+ return createAppBackendViewClient(name, backend);+ }+static async fetchIcon(name: string): Promise<Blob> {const client = getClient();return mapUnsupported(() =>diff --git a/src/components/features/canvas-extensions/canvas-extensions-runtime.test.tsx b/src/components/features/canvas-extensions/canvas-extensions-runtime.test.tsxindex 0fe2ad5e37..304dd7f30b 100644--- a/src/components/features/canvas-extensions/canvas-extensions-runtime.test.tsx+++ b/src/components/features/canvas-extensions/canvas-extensions-runtime.test.tsx@@ -98,6 +98,10 @@ describe("CanvasExtensionsRuntimeProvider", () => {vi.spyOn(CanvasExtensionsService, "fetchBundle").mockResolvedValue("fixture source",);+ vi.spyOn(+ CanvasExtensionsService,+ "createAppBackendViewClient",+ ).mockResolvedValue(null);});afterEach(() => {@@ -186,4 +190,84 @@ describe("CanvasExtensionsRuntimeProvider", () => {);expect(screen.getByTestId("page-count")).toHaveTextContent("0");});++ it("revokes mounted app views when the selected backend changes", async () => {+ const secondBackend: Backend = {+ ...backend,+ id: "second-extension-backend",+ name: "Second extension backend",+ host: "http://127.0.0.1:8001",+ };+ setRegisteredBackends([backend, secondBackend]);+ const createSession = vi.fn().mockResolvedValue({+ url: "https://apps.example.test/app-backends/demo-extension/",+ expiresAt: "2026-09-23T16:00:00Z",+ iframeSandbox:+ "allow-forms allow-modals allow-popups allow-same-origin allow-scripts",+ });+ const revokeSession = vi.fn().mockResolvedValue(undefined);+ const disposeClient = vi.fn();+ vi.mocked(+ CanvasExtensionsService.createAppBackendViewClient,+ ).mockResolvedValue({+ createSession,+ revokeSession,+ dispose: disposeClient,+ });+ const viewContainer = document.createElement("div");+ const moduleLoader = vi.fn().mockResolvedValue({+ activate: (host: CanvasExtensionHost) => {+ host.appBackendView?.mount({ container: viewContainer });+ host.registerPage("dashboard", () => undefined);+ },+ });++ const rendered = renderRuntime(moduleLoader);++ await waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ expect(viewContainer.querySelector("iframe")).not.toBeNull();++ setActiveSelection({ backendId: secondBackend.id });++ await waitFor(() => expect(revokeSession).toHaveBeenCalledTimes(1));+ expect(disposeClient).toHaveBeenCalledTimes(1);+ rendered.unmount();+ });++ it("disposes registrations from the previous backend before activating the next", async () => {+ const secondBackend: Backend = {+ ...backend,+ id: "second-extension-backend",+ name: "Second extension backend",+ host: "http://127.0.0.1:8001",+ };+ setRegisteredBackends([backend, secondBackend]);+ const disposeFirst = vi.fn();+ const disposeSecond = vi.fn();+ const moduleLoader = vi.fn().mockResolvedValue({+ activate: (host: CanvasExtensionHost) => {+ host.registerPage("dashboard", () => undefined);+ return host.backend.id === backend.id ? disposeFirst : disposeSecond;+ },+ });++ const rendered = renderRuntime(moduleLoader);+ await waitFor(() =>+ expect(screen.getByTestId("page-count")).toHaveTextContent("1"),+ );++ setActiveSelection({ backendId: secondBackend.id });++ await waitFor(() => expect(disposeFirst).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(CanvasExtensionsService.fetchBundle).toHaveBeenLastCalledWith(+ extension.name,+ expect.objectContaining({ id: secondBackend.id }),+ ),+ );+ expect(disposeSecond).not.toHaveBeenCalled();++ rendered.unmount();+ expect(disposeSecond).toHaveBeenCalledTimes(1);+ });});diff --git a/src/components/features/canvas-extensions/canvas-extensions-runtime.tsx b/src/components/features/canvas-extensions/canvas-extensions-runtime.tsxindex bda286ed4d..f3bb693db2 100644--- a/src/components/features/canvas-extensions/canvas-extensions-runtime.tsx+++ b/src/components/features/canvas-extensions/canvas-extensions-runtime.tsx@@ -1,9 +1,12 @@import React from "react";import { useNavigate } from "react-router";+import { useTranslation } from "react-i18next";import CanvasExtensionsService from "#/api/canvas-extensions-service";import { useActiveBackend } from "#/contexts/active-backend-context";+import { mountCanvasExtensionAppView } from "#/extensions/canvas-extension-app-view";import { loadCanvasExtensionModule } from "#/extensions/canvas-extension-module-loader";import { useCanvasExtensions } from "#/hooks/query/use-canvas-extensions";+import { I18nKey } from "#/i18n/declaration";import {CANVAS_EXTENSION_HOST_API_VERSION,type CanvasExtensionDispose,@@ -97,6 +100,7 @@ export function CanvasExtensionsRuntimeProvider({}: CanvasExtensionsRuntimeProviderProps) {const active = useActiveBackend();const navigate = useNavigate();+ const { t, i18n } = useTranslation("openhands");const query = useCanvasExtensions();const [pages, setPages] = React.useState<RegisteredCanvasExtensionPage[]>([]);const [errors, setErrors] = React.useState<ReadonlyMap<string, string>>(@@ -143,6 +147,17 @@ export function CanvasExtensionsRuntimeProvider({activeRef.current = active;const enabledExtensionsRef = React.useRef(enabledExtensions);enabledExtensionsRef.current = enabledExtensions;+ const appViewLabels = React.useMemo(+ () => ({+ loading: t(I18nKey.SETTINGS$APPS_VIEW_LOADING),+ retry: t(I18nKey.SETTINGS$APPS_VIEW_RETRY),+ openInNewTab: t(I18nKey.SETTINGS$APPS_VIEW_OPEN_NEW_TAB),+ unavailable: t(I18nKey.SETTINGS$APPS_VIEW_UNAVAILABLE),+ }),+ [i18n.resolvedLanguage, t],+ );+ const appViewLabelsRef = React.useRef(appViewLabels);+ appViewLabelsRef.current = appViewLabels;React.useEffect(() => {let cancelled = false;@@ -166,6 +181,22 @@ export function CanvasExtensionsRuntimeProvider({if (cancelled) return;const extensionModule = await moduleLoader(source);if (cancelled) return;+ const appBackendViewClient =+ await CanvasExtensionsService.createAppBackendViewClient(+ extension.name,+ backend,+ ).catch(() => null);+ if (cancelled) {+ appBackendViewClient?.dispose();+ return;+ }+ const mountedAppViews = new Set<CanvasExtensionDispose>();+ const disposeAppBackendViews = () => {+ for (const dispose of mountedAppViews) dispose();+ mountedAppViews.clear();+ appBackendViewClient?.dispose();+ };+ disposers.push(disposeAppBackendViews);const host: CanvasExtensionHost = {apiVersion: CANVAS_EXTENSION_HOST_API_VERSION,@@ -205,11 +236,42 @@ export function CanvasExtensionsRuntimeProvider({request: (request) =>CanvasExtensionsService.requestAgentServer(request, backend),},+ ...(appBackendViewClient+ ? {+ appBackendView: {+ mount: ({ container }) => {+ const mounted = mountCanvasExtensionAppView({+ container,+ labels: appViewLabelsRef.current,+ createSession: ({ signal }) =>+ appBackendViewClient.createSession(signal),+ revokeSession: () => appBackendViewClient.revokeSession(),+ });+ let disposed = false;+ const dispose = () => {+ if (disposed) return;+ disposed = true;+ mountedAppViews.delete(dispose);+ mounted.dispose();+ };+ mountedAppViews.add(dispose);+ return dispose;+ },+ },+ }+ : {}),};- const disposeActivation = await extensionModule.activate(host);+ let disposeActivation: void | CanvasExtensionDispose;+ try {+ disposeActivation = await extensionModule.activate(host);+ } catch (error) {+ disposeAppBackendViews();+ throw error;+ }if (cancelled) {if (typeof disposeActivation === "function") disposeActivation();+ disposeAppBackendViews();return;}if (typeof disposeActivation === "function") {diff --git a/src/extensions/canvas-extension-app-view.test.ts b/src/extensions/canvas-extension-app-view.test.tsnew file mode 100644index 0000000000..1c105626df--- /dev/null+++ b/src/extensions/canvas-extension-app-view.test.ts@@ -0,0 +1,258 @@+import { fireEvent } from "@testing-library/dom";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ mountCanvasExtensionAppView,+ type CanvasExtensionAppViewLabels,+ type CanvasExtensionAppViewSession,+} from "./canvas-extension-app-view";++const labels: CanvasExtensionAppViewLabels = {+ loading: "Loading app view",+ retry: "Retry",+ openInNewTab: "Open in new tab",+ unavailable: "App view unavailable",+};++const session: CanvasExtensionAppViewSession = {+ url: "https://apps.example.test/app-backends/demo/",+ expiresAt: "2026-08-14T06:10:00Z",+ iframeSandbox:+ "allow-forms allow-modals allow-popups allow-same-origin allow-scripts",+};++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++describe("mountCanvasExtensionAppView", () => {+ it("mounts a server-provided HTTPS view in an isolated frame", async () => {+ const container = document.createElement("div");+ document.body.append(container);++ mountCanvasExtensionAppView({+ container,+ labels,+ createSession: vi.fn().mockResolvedValue(session),+ });++ expect(container).toHaveTextContent(labels.loading);+ const frame = await vi.waitUntil(() => container.querySelector("iframe"));+ expect(frame).toHaveAttribute("src", session.url);+ expect(frame).toHaveAttribute("sandbox", session.iframeSandbox);+ expect(frame).toHaveAttribute(+ "sandbox",+ expect.stringContaining("allow-same-origin"),+ );++ fireEvent.load(frame);+ expect(container).not.toHaveTextContent(labels.loading);+ });++ it.each([+ "not a URL",+ "javascript:alert(1)",+ "data:text/html,unsafe",+ "file:///tmp/app",+ `${window.location.origin}/app-backends/demo/`,+ ])(+ "rejects an unsafe bootstrap URL and revokes its session: %s",+ async (url) => {+ const container = document.createElement("div");+ const revokeSession = vi.fn().mockResolvedValue(undefined);++ mountCanvasExtensionAppView({+ container,+ labels,+ createSession: vi.fn().mockResolvedValue({ ...session, url }),+ revokeSession,+ });++ await vi.waitFor(() =>+ expect(container).toHaveTextContent(labels.unavailable),+ );+ expect(revokeSession).toHaveBeenCalledTimes(1);+ expect(container.querySelector("iframe")).toBeNull();+ expect(container.querySelector("a")).toBeNull();+ },+ );++ it("rejects sandbox permissions outside the bridge isolation contract", async () => {+ const container = document.createElement("div");++ mountCanvasExtensionAppView({+ container,+ labels,+ createSession: vi.fn().mockResolvedValue({+ ...session,+ iframeSandbox: `${session.iframeSandbox} allow-top-navigation`,+ }),+ });++ await vi.waitFor(() =>+ expect(container).toHaveTextContent(labels.unavailable),+ );+ expect(container.querySelector("iframe")).toBeNull();+ });++ it("shows an error with retry and opens only the validated URL", async () => {+ const container = document.createElement("div");+ const createSession = vi+ .fn<() => Promise<CanvasExtensionAppViewSession>>()+ .mockRejectedValueOnce(new Error("backend not ready"))+ .mockResolvedValueOnce(session);+ const open = vi.spyOn(window, "open").mockImplementation(() => null);++ mountCanvasExtensionAppView({ container, labels, createSession });++ await vi.waitFor(() =>+ expect(container).toHaveTextContent(labels.unavailable),+ );+ expect(container).not.toHaveTextContent("backend not ready");+ fireEvent.click(container.querySelector("button")!);+ const frame = await vi.waitUntil(() => container.querySelector("iframe"));+ fireEvent.error(frame);++ const link = await vi.waitUntil(() => container.querySelector("a"));+ fireEvent.click(link);+ expect(open).toHaveBeenCalledWith(+ session.url,+ "_blank",+ "noopener,noreferrer",+ );+ expect(createSession).toHaveBeenCalledTimes(2);+ });++ it("shows retry and new-tab fallback when an iframe never loads", async () => {+ vi.useFakeTimers();+ const container = document.createElement("div");++ mountCanvasExtensionAppView({+ container,+ labels,+ createSession: vi.fn().mockResolvedValue(session),+ });++ await vi.advanceTimersByTimeAsync(0);+ expect(container.querySelector("iframe")).not.toBeNull();+ expect(container).toHaveTextContent(labels.loading);++ await vi.advanceTimersToNextTimerAsync();+ expect(container).toHaveTextContent(labels.unavailable);+ expect(container.querySelector("button")).toHaveTextContent(labels.retry);+ expect(container.querySelector("a")).toHaveAttribute("href", session.url);+ expect(container.querySelector("iframe")).toBeNull();+ });++ it("waits for an aborted session request before starting its retry", async () => {+ const container = document.createElement("div");+ const firstSession = deferred<CanvasExtensionAppViewSession>();+ const createSession = vi+ .fn<+ (context: {+ signal: AbortSignal;+ }) => Promise<CanvasExtensionAppViewSession>+ >()+ .mockImplementationOnce(({ signal }) => {+ signal.addEventListener("abort", () => {+ firstSession.reject(new DOMException("Aborted", "AbortError"));+ });+ return firstSession.promise;+ })+ .mockResolvedValueOnce(session);++ const mounted = mountCanvasExtensionAppView({+ container,+ labels,+ createSession,+ });+ const firstSignal = createSession.mock.calls[0][0].signal;++ mounted.retry();+ expect(firstSignal.aborted).toBe(true);+ expect(createSession).toHaveBeenCalledTimes(1);++ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(2));+ expect(createSession.mock.calls[1][0].signal.aborted).toBe(false);+ });++ it("aborts a pending mount and revokes a late session on disposal", async () => {+ const container = document.createElement("div");+ const pending = deferred<CanvasExtensionAppViewSession>();+ const revokeSession = vi.fn().mockResolvedValue(undefined);+ let signal: AbortSignal | undefined;+ const mounted = mountCanvasExtensionAppView({+ container,+ labels,+ createSession: ({ signal: nextSignal }) => {+ signal = nextSignal;+ return pending.promise;+ },+ revokeSession,+ });++ mounted.dispose();+ expect(signal?.aborted).toBe(true);+ expect(container).toBeEmptyDOMElement();++ pending.resolve(session);+ await vi.waitFor(() => expect(revokeSession).toHaveBeenCalledTimes(1));+ expect(container).toBeEmptyDOMElement();+ });++ it("revokes the current session before replacing or disposing its view", async () => {+ const container = document.createElement("div");+ const revokeSession = vi.fn().mockResolvedValue(undefined);+ const mounted = mountCanvasExtensionAppView({+ container,+ labels,+ createSession: vi.fn().mockResolvedValue(session),+ revokeSession,+ });++ const firstFrame = await vi.waitUntil(() =>+ container.querySelector("iframe"),+ );+ fireEvent.error(firstFrame);+ fireEvent.click(container.querySelector("button")!);++ await vi.waitFor(() => expect(revokeSession).toHaveBeenCalledTimes(1));+ await vi.waitUntil(() => container.querySelector("iframe") !== firstFrame);+ mounted.dispose();+ await vi.waitFor(() => expect(revokeSession).toHaveBeenCalledTimes(2));+ expect(container).toBeEmptyDOMElement();+ });++ it("does not remount when disposed while retry is revoking", async () => {+ const container = document.createElement("div");+ const revocation = deferred<void>();+ const createSession = vi.fn().mockResolvedValue(session);+ const mounted = mountCanvasExtensionAppView({+ container,+ labels,+ createSession,+ revokeSession: () => revocation.promise,+ });++ const frame = await vi.waitUntil(() => container.querySelector("iframe"));+ fireEvent.error(frame);+ fireEvent.click(container.querySelector("button")!);+ mounted.dispose();+ revocation.resolve();++ await Promise.resolve();+ expect(createSession).toHaveBeenCalledTimes(1);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/src/extensions/canvas-extension-app-view.ts b/src/extensions/canvas-extension-app-view.tsnew file mode 100644index 0000000000..67100b54ee--- /dev/null+++ b/src/extensions/canvas-extension-app-view.ts@@ -0,0 +1,241 @@+export interface CanvasExtensionAppViewSession {+ url: string;+ expiresAt: string;+ iframeSandbox: string;+}++export interface CanvasExtensionAppViewLabels {+ loading: string;+ retry: string;+ openInNewTab: string;+ unavailable: string;+}++export interface CanvasExtensionAppViewSessionContext {+ signal: AbortSignal;+}++export interface MountCanvasExtensionAppViewOptions {+ container: HTMLElement;+ labels: CanvasExtensionAppViewLabels;+ createSession: (+ context: CanvasExtensionAppViewSessionContext,+ ) => Promise<CanvasExtensionAppViewSession>;+ revokeSession?: () => Promise<void>;+}++export interface MountedCanvasExtensionAppView {+ dispose: () => void;+ retry: () => void;+}++const IFRAME_LOAD_TIMEOUT_MS = 15000;+const SAFE_SANDBOX_TOKENS = new Set([+ "allow-forms",+ "allow-modals",+ "allow-popups",+ "allow-same-origin",+ "allow-scripts",+]);++class InvalidCanvasExtensionAppViewSessionError extends Error {}++function validatedSession(+ session: CanvasExtensionAppViewSession,+): CanvasExtensionAppViewSession {+ let url: URL;+ try {+ url = new URL(session.url);+ } catch {+ throw new InvalidCanvasExtensionAppViewSessionError();+ }+ if (+ (url.protocol !== "http:" && url.protocol !== "https:") ||+ url.username ||+ url.password ||+ url.origin === window.location.origin+ ) {+ throw new InvalidCanvasExtensionAppViewSessionError();+ }++ const sandboxTokens = session.iframeSandbox.split(/\s+/).filter(Boolean);+ if (+ sandboxTokens.length === 0 ||+ sandboxTokens.some((token) => !SAFE_SANDBOX_TOKENS.has(token))+ ) {+ throw new InvalidCanvasExtensionAppViewSessionError();+ }++ return { ...session, url: url.href, iframeSandbox: sandboxTokens.join(" ") };+}++function createStatus(message: string): HTMLDivElement {+ const status = document.createElement("div");+ status.setAttribute("role", "status");+ status.className =+ "flex h-full min-h-64 w-full items-center justify-center text-sm text-muted";+ status.textContent = message;+ return status;+}++function createAction(label: string, onClick: () => void): HTMLButtonElement {+ const button = document.createElement("button");+ button.type = "button";+ button.className =+ "inline-flex min-h-10 cursor-pointer items-center justify-center rounded-lg bg-primary px-4 text-sm font-semibold text-[var(--oh-accent-foreground)] transition-opacity hover:opacity-80";+ button.textContent = label;+ button.addEventListener("click", onClick);+ return button;+}++export function mountCanvasExtensionAppView({+ container,+ labels,+ createSession,+ revokeSession,+}: MountCanvasExtensionAppViewOptions): MountedCanvasExtensionAppView {+ container.classList.add("h-full", "min-h-0", "w-full");+ let disposed = false;+ let generation = 0;+ let controller: AbortController | null = null;+ let loadTimeout: ReturnType<typeof setTimeout> | null = null;+ let activeMount: Promise<void> | null = null;+ let hasSession = false;++ const clearLoadTimeout = () => {+ if (loadTimeout === null) return;+ clearTimeout(loadTimeout);+ loadTimeout = null;+ };++ const revoke = async () => {+ if (!hasSession || !revokeSession) return;+ hasSession = false;+ try {+ await revokeSession();+ } catch (error) {+ console.error("Canvas App view session cleanup failed", error);+ }+ };++ const renderError = (message: string, url?: string) => {+ if (disposed) return;+ const wrapper = document.createElement("div");+ wrapper.className =+ "flex h-full min-h-64 w-full items-center justify-center p-8";+ const panel = document.createElement("div");+ panel.setAttribute("role", "alert");+ panel.className =+ "flex w-full max-w-lg flex-col items-center rounded-xl border border-border bg-surface-card p-8 text-center";+ const description = document.createElement("p");+ description.className =+ "mb-6 mt-0 max-w-md text-base font-medium leading-6 text-content";+ description.textContent = message;+ const actions = document.createElement("div");+ actions.className = "flex flex-wrap items-center justify-center gap-3";+ actions.append(createAction(labels.retry, retry));++ if (url) {+ const link = document.createElement("a");+ link.className =+ "inline-flex min-h-10 cursor-pointer items-center justify-center rounded-lg border border-border px-4 text-sm font-semibold text-content hover:bg-surface-raised";+ link.href = url;+ link.target = "_blank";+ link.rel = "noopener noreferrer";+ link.textContent = labels.openInNewTab;+ link.addEventListener("click", (event) => {+ event.preventDefault();+ window.open(url, "_blank", "noopener,noreferrer");+ });+ actions.append(link);+ }+ panel.append(description, actions);+ wrapper.append(panel);+ container.replaceChildren(wrapper);+ };++ const mount = async () => {+ const currentGeneration = ++generation;+ controller?.abort();+ clearLoadTimeout();+ controller = new AbortController();+ container.replaceChildren(createStatus(labels.loading));++ try {+ const response = await createSession({+ signal: controller.signal,+ });+ hasSession = true;+ const created = validatedSession(response);+ if (disposed || currentGeneration !== generation) {+ await revoke();+ return;+ }++ const frame = document.createElement("iframe");+ frame.src = created.url;+ frame.title = labels.loading;+ frame.setAttribute("sandbox", created.iframeSandbox);+ frame.className = "h-full w-full border-0 bg-white";+ frame.addEventListener(+ "load",+ () => {+ if (!disposed && currentGeneration === generation) {+ clearLoadTimeout();+ container.replaceChildren(frame);+ }+ },+ { once: true },+ );+ frame.addEventListener(+ "error",+ () => {+ if (!disposed && currentGeneration === generation) {+ clearLoadTimeout();+ renderError(labels.unavailable, created.url);+ }+ },+ { once: true },+ );+ loadTimeout = setTimeout(() => {+ loadTimeout = null;+ if (!disposed && currentGeneration === generation) {+ renderError(labels.unavailable, created.url);+ }+ }, IFRAME_LOAD_TIMEOUT_MS);+ container.replaceChildren(createStatus(labels.loading), frame);+ } catch {+ if (hasSession) await revoke();+ if (disposed || currentGeneration !== generation) return;+ renderError(labels.unavailable);+ }+ };++ function retry() {+ if (disposed) return;+ generation += 1;+ controller?.abort();+ clearLoadTimeout();+ const previousMount = activeMount;+ activeMount = (async () => {+ await previousMount;+ await revoke();+ if (!disposed) await mount();+ })();+ }++ activeMount = mount();++ return {+ retry,+ dispose: () => {+ if (disposed) return;+ disposed = true;+ generation += 1;+ controller?.abort();+ clearLoadTimeout();+ container.replaceChildren();+ void revoke();+ },+ };+}diff --git a/src/fixtures/canvas-extensions/demo-page/extension.js b/src/fixtures/canvas-extensions/demo-page/extension.jsindex 16d83a302c..2798ceb7ec 100644--- a/src/fixtures/canvas-extensions/demo-page/extension.js+++ b/src/fixtures/canvas-extensions/demo-page/extension.js@@ -14,7 +14,13 @@ export function activate(host) {: `Host API ${host.apiVersion} on backend ${host.backend.id}`;detail.style.cssText = "margin-top:0.75rem;opacity:0.75;";- wrapper.append(title, detail);+ const bridgeStatus = document.createElement("p");+ bridgeStatus.dataset.testid = "demo-extension-app-backend-status";+ bridgeStatus.textContent = host.appBackendView+ ? "App backend view available"+ : "App backend view unavailable";++ wrapper.append(title, detail, bridgeStatus);container.append(wrapper);return () => wrapper.remove();});diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex f1e2e4de8e..70604beefb 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -44352,6 +44352,74 @@"tr": "Erişilebilir çalışma alanı yok. Yöneticinizden erişim izinlerinizi kontrol etmesini isteyin.","uk": "Немає доступних робочих просторів. Попросіть адміністратора перевірити ваші права доступу."},+ "SETTINGS$APPS_VIEW_LOADING": {+ "en": "Loading app view...",+ "ja": "アプリビューを読み込み中...",+ "zh-CN": "正在加载应用视图...",+ "zh-TW": "正在載入應用程式檢視...",+ "ko-KR": "앱 보기를 불러오는 중...",+ "no": "Laster appvisning...",+ "ar": "جارٍ تحميل عرض التطبيق...",+ "de": "App-Ansicht wird geladen...",+ "fr": "Chargement de la vue de l’application...",+ "it": "Caricamento della vista dell’app...",+ "pt": "Carregando a visualização do aplicativo...",+ "es": "Cargando la vista de la aplicación...",+ "ca": "S’està carregant la vista de l’aplicació...",+ "tr": "Uygulama görünümü yükleniyor...",+ "uk": "Завантаження подання застосунку..."+ },+ "SETTINGS$APPS_VIEW_RETRY": {+ "en": "Retry",+ "ja": "再試行",+ "zh-CN": "重试",+ "zh-TW": "重試",+ "ko-KR": "다시 시도",+ "no": "Prøv igjen",+ "ar": "إعادة المحاولة",+ "de": "Erneut versuchen",+ "fr": "Réessayer",+ "it": "Riprova",+ "pt": "Tentar novamente",+ "es": "Reintentar",+ "ca": "Torna-ho a provar",+ "tr": "Yeniden dene",+ "uk": "Повторити"+ },+ "SETTINGS$APPS_VIEW_OPEN_NEW_TAB": {+ "en": "Open in new tab",+ "ja": "新しいタブで開く",+ "zh-CN": "在新标签页中打开",+ "zh-TW": "在新分頁中開啟",+ "ko-KR": "새 탭에서 열기",+ "no": "Åpne i ny fane",+ "ar": "فتح في علامة تبويب جديدة",+ "de": "In neuem Tab öffnen",+ "fr": "Ouvrir dans un nouvel onglet",+ "it": "Apri in una nuova scheda",+ "pt": "Abrir em nova aba",+ "es": "Abrir en una pestaña nueva",+ "ca": "Obre en una pestanya nova",+ "tr": "Yeni sekmede aç",+ "uk": "Відкрити в новій вкладці"+ },+ "SETTINGS$APPS_VIEW_UNAVAILABLE": {+ "en": "This app view is not available yet. Check that its backend is ready, then try again.",+ "ja": "このアプリビューはまだ利用できません。バックエンドの準備ができていることを確認して、もう一度お試しください。",+ "zh-CN": "此应用视图尚不可用。请确认其后端已就绪,然后重试。",+ "zh-TW": "此應用程式檢視尚無法使用。請確認其後端已準備就緒,然後再試一次。",+ "ko-KR": "이 앱 보기는 아직 사용할 수 없습니다. 백엔드가 준비되었는지 확인한 후 다시 시도하세요.",+ "no": "Denne appvisningen er ikke tilgjengelig ennå. Kontroller at backend-en er klar, og prøv igjen.",+ "ar": "عرض التطبيق هذا غير متاح بعد. تحقق من أن الواجهة الخلفية جاهزة، ثم حاول مرة أخرى.",+ "de": "Diese App-Ansicht ist noch nicht verfügbar. Prüfe, ob das Backend bereit ist, und versuche es erneut.",+ "fr": "Cette vue d’application n’est pas encore disponible. Vérifiez que son backend est prêt, puis réessayez.",+ "it": "Questa vista dell’app non è ancora disponibile. Verifica che il backend sia pronto, quindi riprova.",+ "pt": "Esta visualização do aplicativo ainda não está disponível. Verifique se o backend está pronto e tente novamente.",+ "es": "Esta vista de la aplicación aún no está disponible. Comprueba que su backend esté listo e inténtalo de nuevo.",+ "ca": "Aquesta vista de l’aplicació encara no està disponible. Comprova que el backend estigui preparat i torna-ho a provar.",+ "tr": "Bu uygulama görünümü henüz kullanılamıyor. Arka ucun hazır olduğunu kontrol edip yeniden deneyin.",+ "uk": "Це подання застосунку ще недоступне. Перевірте, чи готовий його бекенд, і повторіть спробу."+ },"SETTINGS$PROVIDER_CONNECTION_BULK_ADD": {"ar": "إضافة جماعية","ca": "Afegir en lot",diff --git a/src/lib/index.ts b/src/lib/index.tsindex bdf1cc893b..bc6de03d56 100644--- a/src/lib/index.ts+++ b/src/lib/index.ts@@ -44,6 +44,8 @@ export {CANVAS_EXTENSION_HOST_API_VERSION,CANVAS_EXTENSION_MANIFEST_SCHEMA_VERSION,type CanvasExtensionAgentServerRequest,+ type CanvasExtensionAppBackendViewHost,+ type CanvasExtensionAppBackendViewMountOptions,type CanvasExtensionContributions,type CanvasExtensionDispose,type CanvasExtensionHost,diff --git a/src/types/canvas-extension.ts b/src/types/canvas-extension.tsindex 5a47b00ad8..109d7815c1 100644--- a/src/types/canvas-extension.ts+++ b/src/types/canvas-extension.ts@@ -68,6 +68,16 @@ export interface CanvasExtensionAgentServerRequest {headers?: Record<string, string>;}+export interface CanvasExtensionAppBackendViewMountOptions {+ container: HTMLElement;+}++export interface CanvasExtensionAppBackendViewHost {+ mount: (+ options: CanvasExtensionAppBackendViewMountOptions,+ ) => CanvasExtensionDispose;+}+export interface CanvasExtensionHost {readonly apiVersion: typeof CANVAS_EXTENSION_HOST_API_VERSION;readonly extension: Readonly<{@@ -90,6 +100,7 @@ export interface CanvasExtensionHost {request: CanvasExtensionAgentServerRequest,) => Promise<T>;};+ readonly appBackendView?: CanvasExtensionAppBackendViewHost;}export interface CanvasExtensionModule {diff --git a/tests/e2e/canvas-extensions/app-backend-sandbox.spec.ts b/tests/e2e/canvas-extensions/app-backend-sandbox.spec.tsnew file mode 100644index 0000000000..304e4cdfa2--- /dev/null+++ b/tests/e2e/canvas-extensions/app-backend-sandbox.spec.ts@@ -0,0 +1,169 @@+import { createHash } from "node:crypto";+import http, { type IncomingMessage } from "node:http";+import type { Duplex } from "node:stream";+import { test, expect } from "@playwright/test";++const SESSION_COOKIE = "app_session=browser-test";+let appOrigin: string;++type RequestRecord = {+ kind: "http" | "websocket";+ path: string;+ origin: string | null;+ cookie: string | null;+};++const requests: RequestRecord[] = [];+const sockets = new Set<Duplex>();+let appServer: http.Server;++function recordRequest(kind: RequestRecord["kind"], request: IncomingMessage) {+ requests.push({+ kind,+ path: request.url ?? "",+ origin: request.headers.origin ?? null,+ cookie: request.headers.cookie ?? null,+ });+}++test.beforeAll(async () => {+ appServer = http.createServer((request, response) => {+ recordRequest("http", request);+ if (request.url === "/app") {+ response.setHeader("content-type", "text/html");+ response.end(`<!doctype html><script>+ const results = {};+ Promise.all([+ fetch('/api', { method: 'POST', credentials: 'include' }).then(async response => {+ results.fetch = { ok: response.ok, body: await response.text() };+ }),+ new Promise(resolve => {+ const socket = new WebSocket('${appOrigin.replace("http", "ws")}/socket');+ socket.onopen = () => { results.websocket = 'open'; socket.close(); resolve(); };+ socket.onerror = () => { results.websocket = 'error'; resolve(); };+ }),+ new Promise(resolve => {+ const worker = new Worker('/worker.js');+ worker.onmessage = event => { results.worker = event.data; worker.terminate(); resolve(); };+ worker.onerror = event => { results.worker = 'error:' + event.message; resolve(); };+ }),+ ]).then(() => parent.postMessage(results, '*'));+ </script>`);+ return;+ }+ if (request.url === "/api") {+ response.end("api-ok");+ return;+ }+ if (request.url === "/worker.js") {+ response.setHeader("content-type", "application/javascript");+ response.end("postMessage('worker-ok')");+ return;+ }+ response.writeHead(404).end();+ });+ appServer.on("upgrade", (request, socket) => {+ sockets.add(socket);+ socket.once("close", () => sockets.delete(socket));+ recordRequest("websocket", request);+ const key = request.headers["sec-websocket-key"];+ if (typeof key !== "string") {+ socket.destroy();+ return;+ }+ const accept = createHash("sha1")+ .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)+ .digest("base64");+ socket.write(+ `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`,+ );+ });+ await new Promise<void>((resolve) =>+ appServer.listen(0, "127.0.0.1", resolve),+ );+ const address = appServer.address();+ if (!address || typeof address === "string") {+ throw new Error("App backend browser test failed to bind a TCP port.");+ }+ appOrigin = `http://localhost:${address.port}`;+});++test.afterAll(async () => {+ for (const socket of sockets) socket.destroy();+ await new Promise<void>((resolve, reject) =>+ appServer.close((error) => (error ? reject(error) : resolve())),+ );+});++test("the isolated app ingress retains origin for authenticated browser APIs", async ({+ browserName,+ context,+ page,+}) => {+ test.skip(+ browserName !== "chromium",+ "App sandbox browser behavior is verified in Chromium.",+ );+ requests.length = 0;+ await context.addCookies([+ {+ name: "app_session",+ value: "browser-test",+ url: appOrigin,+ sameSite: "Lax",+ },+ ]);+ await page.goto("/");+ const resultsPromise = page.evaluate(+ () =>+ new Promise<Record<string, unknown>>((resolve) => {+ window.addEventListener("message", (event) => resolve(event.data), {+ once: true,+ });+ }),+ );+ await page.evaluate(+ ({ appOrigin }) => {+ const frame = document.createElement("iframe");+ frame.sandbox.add(+ "allow-forms",+ "allow-modals",+ "allow-popups",+ "allow-same-origin",+ "allow-scripts",+ );+ frame.src = `${appOrigin}/app`;+ document.body.append(frame);+ },+ { appOrigin: appOrigin },+ );++ await expect(resultsPromise).resolves.toEqual({+ fetch: { ok: true, body: "api-ok" },+ websocket: "open",+ worker: "worker-ok",+ });+ const browserApiRequests = requests+ .filter(({ path }) => ["/api", "/socket", "/worker.js"].includes(path))+ .sort((left, right) => left.path.localeCompare(right.path));+ expect(browserApiRequests).toEqual([+ {+ kind: "http",+ path: "/api",+ origin: appOrigin,+ cookie: SESSION_COOKIE,+ },+ {+ kind: "websocket",+ path: "/socket",+ origin: appOrigin,+ cookie: SESSION_COOKIE,+ },+ {+ kind: "http",+ path: "/worker.js",+ origin: null,+ cookie: SESSION_COOKIE,+ },+ ]);+});diff --git a/tests/e2e/mock-llm/canvas-extensions/mock-llm-canvas-extensions.spec.ts b/tests/e2e/mock-llm/canvas-extensions/mock-llm-canvas-extensions.spec.tsindex 166a6689ae..fbe90d00b6 100644--- a/tests/e2e/mock-llm/canvas-extensions/mock-llm-canvas-extensions.spec.ts+++ b/tests/e2e/mock-llm/canvas-extensions/mock-llm-canvas-extensions.spec.ts@@ -194,6 +194,9 @@ test.describe("Apps lifecycle", () => {await expect(extensionPage(page)).toContainText("Host API 1 on backend default-local",);+ await expect(+ page.getByTestId("demo-extension-app-backend-status"),+ ).toHaveText("App backend view unavailable");await page.goto(`${PAGE_PATH}/nested`, { waitUntil: "domcontentloaded" });await expect(extensionPage(page)).toContainText(